surround.vim 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "------------------------------------------------------------------------------
  2. " Wrap text with specific tokens. The 'Surround' functions currently supports
  3. " two strategies for surrounding text: 'eol', surround text from cursor to the
  4. " end of line; and 'word', surround only the word
  5. "------------------------------------------------------------------------------
  6. fu! Surround(args)
  7. let [action, open, close] = a:args
  8. let l:ccol = getcurpos()[2]
  9. let l:line = getline('.')
  10. if line[ccol] == ''
  11. call setline('.' , line . open . close)
  12. call cursor('.', len(getline('.')))
  13. return
  14. endif
  15. let l:cursor_to_end = line[ccol:]
  16. let l:line_to_cursor = line[:ccol]
  17. if action == 'eol'
  18. call setline('.', line_to_cursor . open . cursor_to_end . close)
  19. call cursor('.', len(getline('.')))
  20. elseif action == 'word'
  21. let l:word = expand("<cword>")
  22. let l:cursor_to_end = substitute(cursor_to_end, word, open . word . close, '')
  23. call setline('.', line_to_cursor . cursor_to_end)
  24. call cursor('.', len(word) + ccol + 2)
  25. endif
  26. endf
  27. command! -nargs=+ Surround
  28. \ let s:args = split(<q-args>) |
  29. \ let s:key = s:args[0] |
  30. \ let s:str = printf('nnoremap %s <esc>:call Surround(%s)<cr>', s:key, s:args[1:]) |
  31. \ exe s:str
  32. "Surround <leader>( eol ( )
  33. "Surround <leader>{ word { }