Add TeX macro around (visual) selections in Vim
With simple mappings, we can add a TeX command around visually selected text or around the current word in vim.
This is the mapping for visual mode:
vnoremap <leader>m c\{}<esc>PF{i
Assuming you have a selection in visual mode in vim, this mapping consists of the following commands;
c
(ex command) to cut text and switch to insert mode.\{}
adds the necessary text.<esc>
returns to normal mode.P
inserts the originally selected text before the cursor.F{
moves the cursor to the to first { left of the cursor.i
enters insert mode.
Now the only thing you have to do is to type the name of the TeX command.
The equivalent mapping for normal mode is only slightly different:
nnoremap <leader>m ciw\{}<esc>PF{i
Instead of c
we use ciw
.
This is short for “change inner word”.
That is change the word under the cursor without surrounding whitespace.
Since these commands are specific to TeX files, I have put them in a special
augroup
:
augroup TeX
autocmd!
" For enclosing a word or selected text with a TeX command.
autocmd FileType tex nnoremap <leader>m ciw\{}<esc>PF{i
autocmd FileType tex vnoremap <leader>m c\{}<esc>PF{i
" Add index entry for word or selected text.
autocmd FileType tex nnoremap <leader>i yiwea\index{}<esc>P
autocmd FileType tex vnoremap <leader>i dPa\index{}<esc>P
" Enclose a word or selected text with a \SI command.
autocmd FileType tex nnoremap <leader>si ciw\SI{}{}<esc>F}P2f}i
autocmd FileType tex vnoremap <leader>si c\SI{}{}<esc>F}P2f}i
" For emphasizing a word or selected text.
autocmd FileType tex nnoremap <leader>em ciw\emph{}<esc>P
autocmd FileType tex vnoremap <leader>em c\emph{}<esc>P
" For making a word or selected text bold.
autocmd FileType tex nnoremap <leader>st ciw\textbf{}<esc>P
autocmd FileType tex vnoremap <leader>st c\textbf{}<esc>P
" For making a word or selected text small caps.
autocmd FileType tex nnoremap <leader>sc ciw\textsc{}<esc>P
autocmd FileType tex vnoremap <leader>sc c\textsc{}<esc>P
" For rendering a word or selected text in a typewriter font.
autocmd FileType tex nnoremap <leader>tt ciw\textttz{}<esc>P
autocmd FileType tex vnoremap <leader>tt c\texttt{}<esc>P
" For wrapping a word or selected text in TeX quotation marks
autocmd FileType tex nnoremap <leader>tq ciw``<esc>pa''<esc>
autocmd FileType tex vnoremap <leader>tq c``<esc>pa''<esc>
augroup end
This augroup
also contains similar commands to add an index item for
a word or selection and commands to wrap a number in an SI unit or TeX quotes.
It also has commands to change font styles.
For comments, please send me an e-mail.
Related articles
- Typesetting
- Opening vim in a new terminal
- Switching vim to use native package management
- Switching to the vim editor