Search code examples
vimabbreviation

Define persistent abbreviations in Vim


Vim does not seem able to create global abbreviations. So I created an abbreviations file (called autocorrect.vim) with the following line in my .vimrc file:

 :source ~/autocorrect.vim

I then manually added my abbreviations to this file. If I work in any document these abbreviations are available to me.

However, if I am working in a new document and try to add new abbreviations to this list or remove abbreviations, it last only for the session. Once I quit vim I lose all changes. To make abbreviations permanent I have to manually edit the autocorrect.vim file directly.

The thing is that if I work in a new document and add abbreviations I can see that they have been added to my abbreviations list (by calling :ab). However, when I exit they are lost. How can I make these changes global and permanent?

I am hoping to find a solution that does not require a plugin.


Solution

  • In order to persist configuration in Vim, it has to be saved in a configuration file, with :help vimrc as the most prominent one. This has both pros (no matter what you do interactively in Vim, any screw-up can be fixed by restarting Vim) and cons (what you want is difficult to do). I see the following options:

    • Instead of defining abbreviations on the fly with :ab et al, you need to put the command into a separate configuration file, either in your ~/.vimrc, or in a separate config (e.g. ~/.vim/plugin/myabbreviations.vim). This ensures that the abbreviation is persisted for new Vim sessions. You also need to :source the config to import the new abbreviation into your current session. (With the separate config, reloading shouldn't be an issue; it might if your .vimrc is poorly written.) This may sound tedious, but you can define custom :commands to quickly locate, and an :autocmd BufWritePost to automatically :source it. On the other hand, this is a path towards a "plugin solution" that you don't want.
    • Vim supports sessions (:help session-file) that (with the default 'sessionoptions') store mappings and abbreviations. So if you :mksession after defining a new abbreviation (or just before quitting Vim) and load that session (via :source) in another Vim instance, you'll get to keep your abbreviations, too. Unfortunately, without a plugin, session handling also is a manual process and easy to forget. Also, the granularity of what gets persistent cannot be controlled; it's mostly all-or-nothing.
    • As already mentioned in the comments, there are plugins that make this straightforward. If this is only about abbreviations for you (and you're happy with the other configuration handling in general), it might be worth a try.

    I personally use the first option, with custom commands (:Abbreviate, :SnippetEdit, etc.) that open dedicated scripts.