开发者

Auto insert text at a newline in vim

I am editing a LaTeX file with vim. When I am in the \begin{itemize} environment, is there any way to tell vim to autoinsert \item whenever I open a new开发者_如何学运维 line?


function CR()
    if searchpair('\\begin{itemize}', '', '\\end{itemize}', '')
        return "\r\\item"
    endif
    return "\r"
endfunction
inoremap <expr><buffer> <CR> CR()

Put this into your .vim/ftplugins/tex.vim file (or any .vim inside .vim/ftplugins/tex directory).


I would recommend http://vim-latex.sourceforge.net. This package defines several maps useful for latex. In particular for inserting \item you press <ATL-I>


I know noting about latex but I think it is a good idea to search in vim scripts

use the search button up left :D

for example search for

latex auto completion


I can hit Cntl-I and it'll put it in for me in either normal mode or insert mode. This is what I put in my .vimrc:

:imap <C-i> \item 
:nmap <C-i> o\item 

Note that there is a space at the end of \item.


I hacked the script ZyX supplied and came up with this. It adds support for the o and O commands. It does not require LaTeX-VIM.

function AddItem()
  if searchpair('\\begin{itemize}', '', '\\end{itemize}', '')
    return "\\item "
  else
    return ""
  endif
endfunction

inoremap <expr><buffer> <CR> "\r".AddItem()
nnoremap <expr><buffer> o "o".AddItem()
nnoremap <expr><buffer> O "O".AddItem()


Extended Version of Answer by Samad Lotia and ZyX

Place this in your ~/.vim/after/ftplugin/tex.vim

function! AddItem()
  let [end_lnum, end_col] = searchpairpos('\\begin{', '', '\\end{', 'nW')
  if match(getline(end_lnum), '\(itemize\|enumerate\|description\)') != -1
    return "\\item "
  else
    return ""
  endif
endfunction
inoremap <expr><buffer> <CR> getline('.') =~ '\item $' 
  \ ? '<c-w><c-w>' 
  \ : (col(".") < col("$") ? '<CR>' : '<CR>'.AddItem() )
nnoremap <expr><buffer> o "o".AddItem()
nnoremap <expr><buffer> O "O".AddItem()

Improvements

  • auto-insert of \item also happens for environments enumerate and description
  • auto-insert of \item only happens if the immediate surrounding environment is one of the three (itemize/enumerate/description). It does not happen in following circumstance
  \begin{itemize}
    \item
       \begin{minipage}
        <CURSOR>
       \end{minipage}
  \end{itemize}
  • auto-insert of \item only happens if you are at the end of the line
  • deletion of auto inserted \item by pressing <CR> a second time. If one wants to add some indention in this case, change '<c-w><c-w>' to '<c-w><c-w><c-t>'.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜