0

I am trying to replicate the behavior of beg abbreviation shown on the page https://castel.dev/post/lecture-notes-1/ with vimscript. That means I want to make it so that when I type "beg" in insert mode at the beginning of the line, it calls a function that i choose.

I tried to make it with iabbrev, but it doesn't expand until i hit space, and space is typed after my abbreviation. It also doesn't recognize if it is the beginning of a line.

Another approach I tried is with an auto command. I added to my init.vim the following

function SayHello ()
  if (getline('.') =~ "\s*beg$")
    s/^\(\s*\)beg/\1\\begin{}\r\r\\end{}/
  endif
endfunction

autocmd TextChangedI *.tex call SayHello ()

This almost works, but for one problem. It doesn't work if the autocomplete popup is active, which is always because of a plugin I use. So the effect of this code is that as i first type beg, there is no effect, but if i backspace one letter and add it again, it works as intended. I tried to remedy it by adding the command

autocmd CompleteChanged *.tex call SayHello ()

so that it works anyway if there is autocomplete. Unfortunately it doesn't work, because it tries to edit the buffer of the popup. I tried making the function exit the popup to no effect.

How can I make it work like on the site?

1 Answer 1

2

In insert mode, you can expand an abbreviation with C-]. See :help i_CTRL-].

There's an example of calling a function from an abbreviation towards the end of :help abbreviations. You might also want <expr> (see :help :map-expression):

iabbrev <expr> beg SayHello()

Update: I just looked at the Lecture Notes article; the author uses Ultisnips which uses autocommands rather than abbreviations to implement snippets. If you look at Ultisnips' code you can see it uses the TextChangedP autocmd to address the popup problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.