Category: Vim

vim: my 2 cents yaml debugger

Par mc, 18 novembre 2009 10 h 55 min

my ~/.vim/ftplugin/yaml.vim

" put yamllint or any yamlparser in your $PATH
" personnaly, i have
" yamllint () { perl -MYAML -e 'print Dump YAML::LoadFile("'"$1"'")' }
" in my .zshenv
" type ,c in normal mode to know if you file is valid
 
nnoremap ,c :!yamllint %<cr>
 
" the common mistakes are 
"
" forget a space after the : at the end of a key
" /:\S
" replace : by ; at the end of a key
" /^[^:]+;\s
" forget the comma when you write [ key, { a: a } ]
" /\v\[^,]+\{
"
" put it all together: 
" now you can type ,E in normal mode to walk through 
" the common mistakes you wrote
 
nnoremap ,E /\v:\S<bar>\[[^,]+\{<bar>^[^:]+;\s<cr>

perl completion in vim: i finally try it

Par mc, 10 novembre 2009 1 h 20 min

I was waiting a long time to have a perl completion system in vim. I waited because i’m lazy and because i thought someone more skilled than me will finally handle that. I don’t know about PPI or other perl parsing technics and i expected the completion to be really smart.

Time passed and there is no such thing in the place. I used ctags completion but it’s very borring to see packages names of your whole @INC when you try to complete a method name.

Still waiting for something really smart, i spent 2 evenings to write a ‘not so smart completion’ … my first use cases surprised me is it seems to be smart enought to go on waiting for another long time :-) .

I’ll try a daily use starting tomorrow and will feedback in a week. If you can’t wait for testing, debugging, feedback:

the perlcfu git repo

use vim as package management tool

Par mc, 23 octobre 2009 18 h 34 min

- i wrote some commands that gives me a list of rpm archives i can install on my system.
- i piped the result to vim –
- now i want to search on the list, install some of those packages and keep track on what i installed.

first: split the screen:

:sp /tmp/installed_rpm

now you get:
- the installed at top
- the candidates at bottom

then write a macro:

:nnoremap ,i dd<c-w>kp:!yum install <c-r><c-a><cr>

now, you just have to put the cursor on a candidate and type ,i to install and keep track. yes it works: i’m using it right now :)

the macro means:

:nnoremap ,i  # when you type ,i in normal mode 
dd            # delete the line
<c-w>k        # jump to the top window
p             # paste the line
:!yum install # begin to write a shell command: yum install
<c-r><c-a>    # append the current line to the command
              # :h c_ctrl-r_ctrl-a for futher information
<cr>          # validate the shell command by typing <cr> [ENTER]

those kind of things is why i don’t ever consider using another editor.

perl onliners, vim and iso2709

Par mc, 12 octobre 2009 12 h 47 min

tips of this post are cool even if you don’t deal with iso2709.

i wrote a post to explain how sweet it can be to use vim to deal with stdout. Now i want to see the content of a iso2709 file.

as the record separator of iso2709 is « \x1d » but vim

- can’t define a separator different from the standard ones ( combining « \r » and « \n » )
- is very bad to manage very long lines (what an iso2709 file actually is for it)

to navigate in your file, it would be cool to append a « \n » just after « \1xe » (field separator) but with no side effect on the original file. Perl do it easily by mixing -E -0 and -n.

-e flag is to execute perl code ( -E to include perl 5.10 features )

perl -E 'say "hello"'

-n make this code executed for each lines of a read file ( $_ : line content, $. : line number )

cat /etc/hosts
# can be written
perl -nEprint /etc/hosts
grep -n localhost /etc/hosts
# can be written
perl -nE '/localhost/ and print "$. : $_"' /etc/hosts

-0 can change the record separator so

perl -0x1e -nEsay biblio.iso2709

read the file field by field ( -0×1xe ) and append a « \n » (say does it) at the end of each one. Pipe it to vi and you’ll have a fast way to walk through your file.

perl -0x1e -nEsay biblio.iso2709  | vim -

also, set dy (display) to uhex to see the hex codes of the separators ( « \x1d » for the record, « \x1e » for field, « \x1f » for subfield)

:set dy=uhex

also note that perl -n accepts some sed style range

# just see the records 10 to 23
perl -0x1d -nE'  10..23 and print' biblio.iso2709  | vim -
# just see from record 10 to the record that contains the word 'plan9'
perl -0x1d -nE'  10../plan9/ and print' biblio.iso2709  | vim -

and the awk style BEGIN and END blocks

# count the number of records
perl -0x1d -nE 'END { say $. }' biblio.iso2709

rollback double encoding

Par mc, 28 août 2009 9 h 39 min

i just edited an sql dump to remove the noise left by a double utf8 encoding using vim. when you are in command line and type ctrl+f, you enter in a history buffer (so you can edit your commands with vi behaviors). I copied the history in my .zshrc and have a simple filter to do it again simply, now.

# act as filter, remove the double encoding
rollback_double_encode () { 
    perl -Mutf8 -CSD -pe '
	s/é/é/g;
	s/è/è/g;
	s/ê/ê/g;
	s/î/Î/g;
	s/ô/ô/g;
	s/ç/ç/g;
	s/ï/ï/g;
	s/ë/ë/g;
	s/à/à/g;
    ' "$@"
}

well … i imagine it’s not complete but i don’t know a better solution. any idea ?

edit koha code with vim

Par mc, 27 juin 2009 18 h 51 min

Using a terminal based editor is cool: you can remotely edit the code on our server and share your screen to make a collaborative work session with someone elsewhere (screen -xS koha). But some claims that they work faster with IDEs. I want to share my tips for koha editing.

[color=blue]always from the koha root[/color]

When i start a koha devel session, i change directory to koha root and update the code and refresh the tags

cd ~/src/koha
git pull --rebase
ctags --languages=perl -R -f TAGS

[color=blue]tags[/color]

If you don’t know about tags: this is an amazing way to navigate into the code:

- goto a function call (cursor under the function name)
- split the window ( <c-w>f )
- call the tag ( <c-]> )

you have now 2 windows: one on the function call, one on the function def.
you can go to any other tag: type :tag Add<tab> to see all koha functions begining by tags.

tags can also be used to complete the code: in insertmode, type Add<c-x]> and choose the function name in the menu.

[color=blue]open templates[/color]

this is my ~/.vim/plugin/koha. it provides easy way to access to a template or include:

- drive the cursor over the name of the template
- in normal mode, type ,to (template open).
- ensure it’s the good template name
- type enter
- et voila …

" if vim is in a koha root
if isdirectory('C4')
	let g:koha_itmpl='koha-tmpl/intranet-tmpl/prog/en/modules' " intranet templates
	let g:koha_iinc='koha-tmpl/intranet-tmpl/prog/en/includes' " intranet includes
 
	" ,te: template edit: just prepare :e with correct path to template root 
	" ,to; template open: just prepare :e with correct path to the template
	" under the cursor
	" ,ie and ,io are the same for includes 
	nnoremap ,te :e <c-r>=g:koha_itmpl<cr>
	nmap ,to ,te/<c-r><c-f>
	nnoremap ,ie :e <c-r>=g:koha_iinc<cr>
	nmap ,io ,ie/<c-r><c-f>
 
	" add include in the path ... so gf works inside templates
	exec 'set path+='.g:koha_iinc
endif

[color=blue]edit templates[/color]

this is my ~/.vim/plugin/html_template.vim

inoremap <V <!-- TMPL_VAR NAME="" --><c-o>F"
inoremap <L <!-- TMPL_LOOP NAME="" --><!--/TMPL_LOOP --><c-o>F"
inoremap <I <!-- TMPL_IF X><!-- /TMPL_IF --><esc>FXs
inoremap <U <!-- TMPL_UNLESS X><!-- /TMPL_UNLESS --><esc>FXs
inoremap <EI <!-- TMPL_ELSIF NAME="" --><c-o>F"
inoremap <EL <!-- TMPL_ELSE -->
inoremap <# <!-- TMPL_INCLUDE NAME="" --><c-o>F"

now, in insert mode: type <V or <I or ..

et voila

HTH

wim ch’est bon!

Par mc, 6 avril 2009 9 h 32 min

par defaut, la completion du mode commande se fait facon vieux tcsh: une serie de permet de parcourir la liste des completions possibles.

Perso, je préfère avoir la liste des completions possibles pour affiner moi-même en saisissant la suite.

set wim=longest,list

mon vim bien fléché

Par mc, 5 avril 2009 17 h 12 min

A force de fréquenter vi, on utilise de moins en moins les flêches pour se ballader dans le buffer en mode normal (les w,b,f,t,),% et la foule d’autres moouvements biens plus précis et puissants remplacent vite ces 4 outils).

Si vous en venez a vouloir faire usage des fleches, tous les anciens conseillent l’utilisation de leurs équivalents vi (hkjl). J’étais peu convaincu au début et les premiers jours de pratique sont difficiles mais je trouve maintenant que cet apprentissage, pas si compliqué, se justifie totalement pour plein de petites choses.

Que faire alors de ces 4 touches devenues obsolètes?

Ma réponse s’appelle ~/.vim/plugin/buffer_navigation.vim … c’est un fichier que je train depuis des années dans ma conf. vim et dont je ne me passerais pour rien au monde:

noremap <down> :blast!<cr>
noremap <right> :bnext!<cr>
noremap <left> :bprevious!<cr>
noremap <up> :ls<cr>:buffer

En effet, si il est aisé d’ouvrir un nouveau buffer avec un autre fichier (voir :e ou gf), la navigation entre les buffers passe par le mode commande et c’est lourd ! (enfin je trouve)

Voila donc comment j’ai recyclé mes flêches:

Les fleches droite et gauche permettent donc d’aller au buffer suivant (:bn pour buffer next) et précedent (:bp pour buffer previous).

La fleche du haut liste les buffers (avec leur numero) et attend la saisie du numero de buffer ou aller.

La fleche du bas va au dernier buffer … en pratique je ne m’en sers pas …

Mon kit de surVIe

Par matts, 30 mars 2009 17 h 27 min

Vi :

highlight accolade 	: %
recherche 		: /
recherche arrière	: ?
recherche suivant	: n 	(next)
recherche précédent	: N
recherche mot courant	: *
mot suivant		: w 	(word)
mot précédent		: b 	(back)
recharger le fichier    : :e %
ouvrir le fichier	: gf 	(go file)
changer le mot		: cw 	(change word)
changer tout le mot	: ciw 	(change inner word)
complétion		: Control-P
fenêtre suivante        : Control-w w
revenir à l'endroit précédent du curseur : Control-o (old place)
exécuter une commande sur tous les buffers : :bufdo(!) :macommande


Emacs :

début de ligne		: Control-A (Control-A, A quand on est dans un screen)
fin de ligne		: Control-E
couper jusqu'à la fin de la ligne : Control-K
mot suivant 		: Meta f 	(forward)
mot précédent 		: Meta b 	(backward)

Shell :

arguments de la dernière commande 	: !*
réexecuter la dernière commande		: !!

vim vs ipython: quickfix

Par mc, 25 janvier 2009 1 h 22 min

J’ai lu avec intéret les 2 posts d’arnaud sur ipython et pour le moment je fais mieux avec vim (et depuis des années, pas avec la version 2012!)

pour le fait de pouvoir manipuler la stdout d’une commande, qx existe en perl et il doit y avoir un truc du meme gout en python:

my @lines = qx(ls); 
my $i=0;
print $i++,": $_" for @lines;

pour %edit … toi quoi vient du monde des IDEs, je pige pas que tu utilises ce truc! j’ai ouvert google, tappé « Eclipse python » et suis tombé là dessus.

maintenant: quand je te disais que vim était tout a fait bien, demonstration:

dpkg -L vim-runtime | grep perl | vim -

que vois-je?

/usr/share/vim/vim71/syntax/perl.vim

syntax highlight
.vimrc: syn on

/usr/share/vim/vim71/indent/perl.vim
/usr/share/vim/vim71/ftplugin/perl.vim

un filetype plugin et indent
.vimrc: filetype plugin indent on

/usr/share/vim/vim71/compiler/perl.vim

un compiler! kesako? et bien a part le debbuger interactif, vim dispose des fonctions minimales d’un IDE:

- la commande :make permet de lancer la commande externe make
- la sortie d’erreur est utilisé par vim pour créer une liste d’erreurs, la liste des fichiers et des lignes ou ces erreurs se sont produites.
- apres execution, vim se met sur la premiere erreur
- :clist te permet d’afficher la liste des erreurs, tu tappes le numero d’erreur pour y acceder

ouais mais tu vas pas créer un makefile pour un script python? right! c’est pourquoi tu peux choisir la commande qui sera executée a la place de make grace a makeprg. La chose est que le symbole % est expand comme le nom du fichier courant.

et puis la clist, comment elle est générée? réponse: vim utilise la variable errorformat qui contient une liste de motifs et des instructions pour savoir quoi en faire. C’est avec cette variable que vim traite la stderr.

le fichier compiler se limite en général a déclarer correctement ces deux variables. ensuite, tu appelles la commande compiler (soit directement depuis le mode commande de vim, soit en ajoutant dans ~/.vim/ftplugin/perl.vim)

alors que ces fichiers sont tres riches pour perl, tout ou presque reste a faire pour python (bonne chance pour le errorformat).

autre variable intéressante: autowrite qui enregistre automatiquement avant :make.

allez, exercice:

vim jefaispi.py
:set aw makeprg=python\ %
# edit, edit, edit
:make
# edit, edit, edit
:make
ZZ

sauf que ca va vite etre chiant de tapper setmakeprg=… a chaque fois que je code et je n’ai pas envie de remplir un par un les fichiers ~/.vim/ftplugin/* avec l’interpreteur qui va bien … d’autant que tu utilises de temps en temps des options de l’interpreteur (perso en perl: -wc, -T -I …) … en plus c’est presque aussi chiant de tapper :make que de relancer …

et la, marco te sors son vimrc .. enfin .. un petit bout:

" don't need to write before :make
set aw
" :MP perl %
" to set perl as 'makeprg'
command -nargs=* MP exec 'set mp=' . escape(<q-args>,' ')
nnoremap ,c :make<cr>

ok … on refait la meme chose qu’avant:

vim jefaispi.py
:MP python %
# edit, edit, edit
,c
# edit, edit, edit
,c
ZZ

Panorama Theme by Themocracy