The best way to create replacement macros in vim
Using an abbreviation, you can write something like this:
inorea it it("", function () {<cr>});<c-o>k<c-o>f"
The goal <c-o>k<c-o>f"
at the end is to move the cursor inside the double quotes, but it may not work all the time.
Using collation, you can try this:
ino <expr> <tab> <sid>expand_last_word()
let s:your_expansions = {
\ 'it': '\<c-w>it(\"\", function () {\<cr>});\<c-o>k\<right>',
\ }
fu! s:expand_last_word() abort
let last_word = matchstr(getline('.'), '\v<\k+%'.col('.').'c')
return has_key(s:your_expansions, last_word)
\ ? eval('"'.s:your_expansions[last_word].'"')
\ : "\<tab>"
endfu
You will need to add your abbreviations and their extensions to the dictionary s:your_expansions
.
Using the command :read
, you can define large chunks of code and split them into multiple files:
ino <expr> <tab> <sid>expand_last_word()
fu! s:expand_last_word() abort
let last_word = matchstr(getline('.'), '\v<\k+%'.col('.').'c')
if last_word ==# 'it'
return "\<c-w>\<c-o>:r /path/to/some_file\<cr>\<c-o>f\"\<right>"
endif
return "\<tab>"
endfu
/path/to/some_file
Your snippet should contain here :
it("", function () {
});
They are very simple solutions, if you want something more robust you probably need a snippets plugin. One of them is UltiSnips , which requires your version of Vim to be compiled with Python support ( :echo has('python')
or :echo has('python3')
returns 1).
With UltiSnips, you can write your snippet like this:
snippet it "your description" b
it("$0", function () {
});
endsnippet
Here the definition is included between keywords snippet
and endsnippet
. On the first line, you can describe the purpose of your snippet, inside the string, in double quotes. It will show UltiSnips inside the list if you have defined multiple snippets with the same tab trigger and there is ambiguity there.
Ending b
is the ability to prevent a tab trigger from starting it
anywhere other than the beginning of a line.
$0
is a tableau, it denotes the position in which you want the cursor to be after the fragment is fully expanded.
The readme page on github gives a quick start and some video links.
If you want to see snippets written by other people, you can install vim-snippets .
There are other snippet managers out there, but I don't know them well enough to describe the syntax of their snippets. If you'd like to make a comparison, here's one , and here are links for some of them:
source to share
Here abbreviation
's which you can use for your specific example
:inoreabbrev it it("", function () {<cr>});<esc>kf"a
Entering it
followed by a ctrl+ ]in insert mode will display
it("|", function () {
});
and keep you in insert mode.
But I would definitely go to ultisnips and there is a screencast for creating snippets on the same page. This is why I am omitting a snippet here, how you can do it yourself.
source to share