A Django site.
July 14, 2008
» Use Vim As A Syntax Highlighting Pager

It has been some time since I’ve done a Vim Tip of the Week, but I came across something today that I thought I would share.  This tip will allow you to use Vim, with all its syntax highlighting glory, as a pager (similar to less or more).

If you use cat or less or more regularly to quickly view files, but you’d like to keep the same syntax highlighting that you’d get in Vim you can use an included config that makes Vim act as a pager.  Setup the following within your .bashrc file, or wherever you keep your shell aliases:

alias vless='vim -u /usr/share/vim/vim71/macros/less.vim'

You’ll then need to re-read that file, which can be done using:

. .bashrc

At this point you can use vless to view a file, which will use the beloved syntax highlighting.  Normal pager shortcuts should work.  q to quit, / to search, pg-up, pg-dn, etc.

Random Posts

June 12, 2008

John Anderson
sontek
sontek ( John M. Anderson )
» Vim Tip: Use Ctrl-Space for omni and keyword completion.

Having Ctrl+Space for auto-completion is great because its a much more natural binding than the vim defaults.

Sometimes omni completion doesn’t find things properly (such as when searching in the current buffer), so I like to fall back to keyword completion if no results are found in omni-completion.

Put this in your .vimrc to get the same effect:

inoremap <expr> <C-Space> pumvisible() \|\| &omnifunc == '' ?
\ "\<lt>C-n>" :
\ "\<lt>C-x>\<lt>C-o><c-r>=pumvisible() ?" .
\ "\"\\<lt>c-n>\\<lt>c-p>\\<lt>c-n>\" :" .
\ "\" \\<lt>bs>\\<lt>C-n>\"\<CR>"
imap <C-@> <C-Space>

This provides an even more powerful feel to the code completion in vim.

June 9, 2008

John Anderson
sontek
sontek ( John M. Anderson )
» Vim Tip: Save file with root permissions

Have you ever opened up a configuration file in vim and then after you do all your editing you realize you don’t have permissions to save?

A simple command that will re-open your current buffer with root permissions is this:

exe “%!sudo tee %” | e!

You can bind this in your vimrc and then never waste time editing a read-only file again!

May 11, 2008

John Anderson
sontek
sontek ( John M. Anderson )
» Python with a modular IDE (Vim)

On Thursday, May 9th, 2008 the Utah Python User Group decided to settle the debate that has plagued us developers since the beginning of time: If you were a programming language, what editor would you use?

I was tasked with showing Eclipse with the PyDev plugin in all its glory–but we all know–real men / developers don’t use IDE’s, so we are going to talk about using Python and Vim together, reaching a state of Zen that the Dalai LLama would be jealous of and establishing more Feng Shui than Martha Stewart’s Kitchen.

Freely jump between your code and python class libraries

There are 2 ways to add your ability to jump between python class libraries, the first is to setup vim to know where the Python libs are so you can use ‘gf’ to get to them (gf is goto file). You can do this by adding this snippet to your .vimrc:

python << EOF
import os
import sys
import vim
for p in sys.path:
    if os.path.isdir(p):
        vim.command(r"set path+=%s" % (p.replace(" ", r"\ ")))
EOF

With that snippet you will be able to go to your import statements and hit ‘gf’ on one of them and it’ll jump you to that file.

Continuing accessibility of the Python class libraries we are going to want to use ctags to generate an index of all the code for vim to reference:

$ ctags -R -f ~/.vim/tags/python.ctags /usr/lib/python2.5/

and then in your .vimrc

set tags+=$HOME/.vim/tags/python.ctags

This will give you the ability to use CTRL+] to jump to the method/property under your cursor in the system libraries and CTRL+T to jump back to your source code.

I also have 2 tweaks in my .vimrc so you can use CTRL+LeftArrow and CTRL+RightArrow to move between the files with more natural key bindings.

map <silent><C-Left> <C-T>
map <silent><C-Right> <C-]>

You can also see all the tags you’ve been to with “:tags”

Code Completion

To enable code completion support for Python in Vim you should be able to add the following line to your .vimrc:

autocmd FileType python set omnifunc=pythoncomplete#Complete

but this relies on the fact that your distro compiled python support into vim (which they should!).

Then all you have to do to use your code completion is hit the unnatural, wrist breaking, keystrokes CTRL+X, CTRL+O. I’ve re-bound the code completion to CTRL+Space since we are making vim an IDE! Add this command to your .vimrc to get the better keybinding:

inoremap <Nul> <C-x><C-o>

Along with code completion, you will also have call tip support. Here is a screenshot:

Vim with Code Completion
Documentation

No IDE is complete without the ability to access the class libraries documentation! You’ll need to grab this vim plugin. This gives you the ability to type :Pydoc os.path or use the keystrokes <Leader>pw and <Leader>pW to search for the item under the cursor. (Vim’s default <Leader> is “\”). Here is a screenshot:

Vim with PyDoc integration

Syntax Checking

Vim already has built in syntax highlighting for python but I have a small tweak to vim to give you notifications of small syntax errors like forgetting a colon after a for loop. Create a file called ~/.vim/syntax/python.vim and add the following into it:

syn match pythonError "^\s*def\s\+\w\+(.*)\s*$" display
syn match pythonError "^\s*class\s\+\w\+(.*)\s*$" display
syn match pythonError "^\s*for\s.*[^:]$” display
syn match pythonError “^\s*except\s*$” display
syn match pythonError “^\s*finally\s*$” display
syn match pythonError “^\s*try\s*$” display
syn match pythonError “^\s*else\s*$” display
syn match pythonError “^\s*else\s*[^:].*” display
syn match pythonError “^\s*if\s.*[^\:]$” display
syn match pythonError “^\s*except\s.*[^\:]$” display
syn match pythonError “[;]$” display
syn keyword pythonError         do

Now that you have the basics covered, lets get more complicated checking added. Add these 2 lines to your .vimrc so you can type :make and get a list of syntax errors:

autocmd BufRead *.py set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
autocmd BufRead *.py set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m

You will have the ability to to type :cn and :cp to move around the error list. You can also type :clist to see all the errors, and finally, sometimes you will want to check the syntax of small chunks of code, so we’ll add the ability to execute visually selected lines of code, add this snippet to your .vimrc:

python << EOL
import vim
def EvaluateCurrentRange():
eval(compile('\n'.join(vim.current.range),'','exec'),globals())
EOL
map <C-h> :py EvaluateCurrentRange()

Now you will be able to visually select a method/class and execute it by hitting “Ctrl+h”.

Browsing the source

Moving around the source code is an important feature in most IDE’s with their project explorers, so to get that type of functionality in vim we grab the Tag List plugin. This will give you the ability to view all opened buffers easily and jump to certain method calls in those buffers. Here is a screenshot of it in action:

Vim TagList Plugin

The other must-have feature of an IDE when browsing code is being able to open up multiple files in tabs. To do this you type :tabnew to open up a file in a new tab and than :tabn and :tabp to move around the tabs. Add these to lines to your .vimrc to be able to move between the tabs with ALT+LeftArrow and ALT+RightArrow:


map <silent><A-Right> :tabnext<CR>
map <silent><A-Left> :tabprevious<CR>

Debugging

To add debugging support into vim, we use the pdb module. Add this to your ~/.vim/ftplugin/python.vim to have the ability to quickly add break points and clear them out when you are done debugging:

python << EOF
def SetBreakpoint():
    import re
    nLine = int( vim.eval( 'line(".")'))

    strLine = vim.current.line
    strWhite = re.search( '^(\s*)', strLine).group(1)

    vim.current.buffer.append(
       "%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
         {'space':strWhite, 'mark': '#' * 30}, nLine - 1)

    for strLine in vim.current.buffer:
        if strLine == "import pdb":
            break
    else:
        vim.current.buffer.append( 'import pdb', 0)
        vim.command( 'normal j1')

vim.command( 'map <f7> :py SetBreakpoint()<cr>')

def RemoveBreakpoints():
    import re

    nCurrentLine = int( vim.eval( 'line(".")'))

    nLines = []
    nLine = 1
    for strLine in vim.current.buffer:
        if strLine == ‘import pdb’ or strLine.lstrip()[:15] == ‘pdb.set_trace()’:
            nLines.append( nLine)
        nLine += 1

    nLines.reverse()

    for nLine in nLines:
        vim.command( ‘normal %dG’ % nLine)
        vim.command( ‘normal dd’)
        if nLine < nCurrentLine:
            nCurrentLine -= 1

    vim.command( ‘normal %dG’ % nCurrentLine)

vim.command( ‘map <s-f7> :py RemoveBreakpoints()<cr>’)
EOF

With that code you can now hit F7 and Shift-F7 to add/remove breakpoints. Then you just launch your application with !python % (percent being the current file, you can declare your main file here if its different).

Another tweak I use is to have my vim inside screen with a horizontal split, that way I can see the python interpreter and debug while still having vim there so I can easily fix my code. Here is a screenshot of that in action:

Vim with Screen

Snippets

A great time saver with stanard IDE’s is code snippets, so you can type a few key strokes and get a lot of code out of it. An example of this would be a django model, instead of typing out the complete declaration you could type ‘mmo<tab><tab>’ and have a skeleton of your model done for you. To do this in vim we grab the Snippets EMU plugin.

Check out a great screencast of snippetsEmu in action here

You can get my full setup here

Emacs

Here is a great post on how to do the same with Emacs.

April 19, 2008

Scott Paul Robertson
spr
Spr: The Ramblings
» Full Code Navigation: Cscope

Not long ago we discussed ctags here, and how it can quickly let you navigate your code, helping you find definitions of variables and functions. You'll have taken notice that sometimes you want to navigate in the reverse: where is this function called, who includes this file, etc. Cscope builds a database of such information (and more). We can include it with ctags and have very impressive code searching.

If you want a detailed introduction, there is a great cscope and vim tutorial available. I'll just give you a quick run down of using it.

  1. At the base of your C or C++ source tree run cscope -R -b -q

  2. Add this to your .vimrc:

    if has("cscope")
      set cst
      set csto=1
      if filereadable("cscope.out")
        cs add cscope out
      endif
    endif
    
  3. Start Vim in the same directory as the generated cscope.out file. (If not, just do :cs add <cscope.out file>).

  4. To find where a function is called do :cs find c <function>. To find where a symbol is defined do :cs find s <symbol. You'll notice that if there are multiple matches a menu pops up to let you pick. This is the case for using CTRL-] on symbols as well.

  5. Make some handy mappings:

    nmap <C-\>s :cs find s <C-R>=expand("<cword>")<CR><CR>
    nmap <C-\>c :cs find c <C-R>=expand("<cword>")<CR><CR>
    

Cscope can do many other searches. See the tutorial or just type :he cscope in Vim.

March 29, 2008

Hans Fugal
no nic
The Fugue :
» sh.vim

Have you ever been frustrated with perfectly valid bash syntax being highlighted as incorrect in vim? Like this:


#!/bin/sh
foo=$(ls /tmp)

$() is a perfectly valid, nay preferred substitute for backticks. The problem is that vim is deciding this is pure old bourne shell instead of whatever else we'd like it to be. If you change the shebang to #!/bin/bash and re-edit the file, then the error markings go away. But maybe you're writing for the nebulous POSIX shell, not bash nor sh. Or maybe you just don't care and you don't want vim complaining that you're using bashisms even though your shebang says sh. You can set the defaults so that it reflects your system and preferences. It's all there in :help sh.vim.

March 17, 2007

Byron Clark
byronc
byronc bits
» Editing ViM Macros

At the BYU UUG meeting this week, Peter mentioned a great ViM trick that I’ve never seen before. Here’s my feeble attempt to document it.

Because ViM macros are stored in registers they can be edited. This means that if you create a long macro and then realize that you forgot to send the cursor to the beginning of the line before finishing the recording, you don’t have to create the entire macro again, you can just add the motion command. You use it like this:

  1. Start recording your macro by typing q and then the single character ([0-9a-zA-Z"] are allowed). The single character is the register your macro will be stored in.
  2. Enter the commands you want included in the macro.
  3. Type q to finish recording the macro.
  4. At this point you could run the macro by using @ and the register name.
  5. To modify the macro, move to a blank line and type "Rp replacing R with the register name of your macro. This will paste all the commands in your macro to the current line.
  6. After making the changes you need, save the macro by typing 0"Ry$ replacing R with the register name you want to use for the macro. The register name does not have to be the same as the original.