Thursday, 2 October 2014

Reformatting latex code with Vim

Vim can be used as a very  nice latex IDE with the help of the vim-latex plugin. Unfortunatelly format indenting the selected code (SHIFT+=) does not include latex comments (using the '%' delimiter).
This issue can be solved by manually replacing the delimiter with a neutral string before formatting and then restoring the original delimiter.

The code shown below does the job. Any delimiter can be given as the argument of the IndentComments function so that  it can be used with any type of code. The last  line creates a map for calling the function set on latex by pressing '§'.

Just add it to your  ~/.vimrc configuration file.

" Solve the issue of formatting comments 
" @param delimiter  the comment delimiter for the chosen filetype"
function! IndentComments(delimiter) range

    " set a temporary substitute for the delimiter 
    let s:tmp_delimiter = 'delimiter>>>>'

    " replace the delimiter with the substitute
    exec a:firstline.','.a:lastline.' '.'s/'.a:delimiter.'/'.s:tmp_delimiter.'/'

    " reformat all lines in the range
    exec a:firstline.','.a:lastline.' '.'normal! =='

    " put back the original delimiter
    exec a:firstline.','.a:lastline.' '.'s/'.s:tmp_delimiter.'/'.a:delimiter.'/'


" mapping '§' to reformat selected code in latex
:map <silent> § :call IndentComments("%") <CR>

No comments:

Post a Comment