Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using backslashes in vim abbreviations

Tags:

vim

I want to be able to write \bit and have it expand to something in vim. How do I encode a backslash in the left-hand side of an abbreviation, though?

I tried all of these:

:iab \bit replacement_text
:iab <Bslash>bit replacement_text
:iab <bs>bit replacement_text

but got E474: Invalid argument for all of these.

The map_backslash help-topic suggests <Bslash>, but this doesn't seem to work.

like image 450
Peter Avatar asked Nov 05 '09 00:11

Peter


4 Answers

:set iskeyword+=\

in vimrc_tex (or just vimrc) works perfectly.

like image 66
AlanRobertClark Avatar answered Nov 04 '22 06:11

AlanRobertClark


You can define your abbreviation on "bit", and then test if it is preceded by "", if so, return the new text, or "bit" otherwise.

function! s:Expr(default, repl) expr
  if getline('.')[col('.')-2]=='\'
    return "\<bs>".a:repl
  else
    return a:default
  endif
endfunction

:inoreab bit <c-r>=<sid>Expr('bit', 'foobar')<cr>

That's the kind of tricks I used in MapNoContext().

EDIT: see :h abbreviations for the reasons why what you asked can't be achieved directly.

EDIT2: It can be easily encapsulated this way:

function! s:DefIab(nore, ...) abort
  let opt = ''
  let i = 0
  while i != len(a:000)
    let arg = a:000[i]
    if arg !~? '<buffer>\|<silent>'
      break
    endif
    let opt .= ' '.arg
    let i += 1
  endwhile

  if i+2 != len(a:000)
    throw "Invalid number of arguments"
  endif
  let lhs = a:000[i]
  let rhs = a:000[i+1]

  exe 'i'.a:nore.'ab'.opt.' '.lhs.' <c-r>=<sid>Expr('.string(lhs).', '.string(rhs).')<cr>'
endfunction

command! -nargs=+ InoreabBSlash call s:DefIab('nore', <f-args>)

And used with a simple:

InoreabBSlash <buffer> locbit foobar

or

InoreabBSlash bit foobar
like image 35
Luc Hermitte Avatar answered Nov 04 '22 07:11

Luc Hermitte


I suggest using backslash on both sides, vim is happy that way:

inoreabbr \bit\ replacement_text

Note that I am using the "nore" version of abbr, better to be clear if you don't intend a recursive expansion. I have been using the below abbreviations for a long time and they work great:

inoreabbr \time\ <C-R>=strftime("%d-%b-%Y @ %H:%M")<CR>
inoreabbr \date\ <C-R>=strftime("%d-%b-%Y")<CR>
like image 3
haridsv Avatar answered Nov 04 '22 07:11

haridsv


you could

   inoremap \bit replacementtext

Also if you dont like the lag an alternative leader like backtick ` (above the tab for me)

   :iab `f foobar

if you are not using them in your code often

like image 1
michael Avatar answered Nov 04 '22 05:11

michael