Removing multiple blank lines when typesetting code listings

Posted on September 29, 2012

The listings package in LaTeX has an option to collapse multiple empty lines into a single empty line when typesetting code lists. Today, there was a question on TeX.SE how to do something similar when using the minted package. The t-vim module uses the same principle as the minted package. So, I wondered how one could collapse multiple empty lines into a single line in t-vim?

In the vim module, it is possible to specify a vimrc file that is sourced when the code snippet is loaded in the editor. I included this option to pass options to syntax highlighting (e.g., for languages like sh and tex, one can specify the flavor using keywords set in the .vimrc file).

One can use this feature to pre-process the file using vim macros. The following regular expression collapses multiple lines to a single line:

%s/\(^\s*\n\)\{2,\}/\r/ge | w

So, we want this regular expression to be run when the file is loaded. The t-vim module writes the file with extension .tmp, so the following snippet works:

au BufEnter *.tmp %s/\(^\s*\n\)\{2,\}/\r/ge | w

We may use this from the t-vim module as follows:

\usemodule[vim]
 
\startvimrc[name=collapse]
au BufEnter *.tmp %s/\(^\s*\n\)\{2,\}/\r/ge | w
\stopvimrc
 
 
\definevimtyping[CPPtyping][syntax=cpp, vimrc=collapse]
 
\starttext
\startCPPtyping
  i++;
 
 
  i++;
 
 
 
 
 
 
  i--;
\stopCPPtyping
\stoptext

Agreed, this is not as simple as the extralines=1 option in the listings package. But, it is not too complicated when you consider the fact that I had not thought about this feature at all when I wrote the t-vim module.


This entry was posted in T-Vim and tagged code formatting, blank lines.