Emacs Fill Prefix in Vim
2 years, 6 months ago — 3 Comments — Permalink
I was recently presented with the problem of adding consistent prefixes to paragraphs of text whilst respecting the text width setting, for example when responding to email you may wish to prefix text with the authors initials like so:
SC> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do SC> eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non.
As a Vim user, I searched for a way to do this automatically and the best I came up with was to set Vim to use the GNU fmt program (available in the coreutils package for us Mac users stuck with lesser BSD equivalents) e.g. :se formatprg=fmt\ -p\ SC\>. The downside to this is having to specify the prefix manually. Emacs has the ability to automatically set the fill prefix and use that prefix to format paragraphs. Since you can write Vim plugins in Python, I came up with the following:
function! FillPrefix() py << EOF import vim cur_line = vim.current.line if not cur_line: prefix = '' # Unset prefix if called on empty line else: prefix = 'n:' + cur_line.split(' ')[0] vim.command('set comments=%s' % prefix) EOF endfunction
This takes the first word from the line you called it on and sets that to the prefix. Now when you hit gq on a line with that prefix, it’ll be wrapped with a consistent prefix and text width. My colleague and fellow workflow enthusiast, Affan, came up with a more Emacs-like alternative which uses the cursor position to determine the prefix:
function! SetQuotePrefixFromCursor() python << EOF import vim cursor_col = vim.current.window.cursor[1] quote_prefix = vim.current.line[:cursor_col] if quote_prefix: set_cmd = 'set comments=n:%s' % quote_prefix else: set_cmd = 'set comments=' # Cancel quoting prefix vim.command(set_cmd) EOF endfunction
I saved this as fillprefix.py in my .vim folder and bound the <leader>fp shortcut to it:
nmap <silent> <leader>fp :call SetQuotePrefixFromCursor()<CR>
As a side note, autocompletion (C-x C-O) came in handy when exploring the Vim Python module, although oddly requires Emacs style C-n and C-p to navigate.