7

Disclaimer: I tried to find a generic title for this question but I was overcomplicating the whole thing...

Use case:

In a JS file, I have an expression like:

if (someVar === 'someValue') {
    statements;
}

and, for debugging purposes, I sometimes want to include a console.log in the line above:

console.log('someVar:', someVar);
if (someVar === 'someValue') {
    statements;
}

(Working) Attemp:

I want to have some keybinding to achieve this, so I tried:

nnoremap <Leader>L "ayiwOconsole.log(':', );<Esc>2F'"apf "ap

that basically yanks word under cursor to register a, then writes an empty console.log(':', ); template in the line above, moves to the desired positions and pastes register a twice.

It works, but it feels kinda dirty. Can you guys think of a more elegant way to do the same?

5

You can use <C-R> from insert mode to insert the contents of a register. That way you can insert the whole line at once, including the repeat of the variable name.

For example:

nnoremap <Leader>L "ayiwOconsole.log('<C-R>a:', <C-R>a);<Esc>

You might want to consider adding a visual mode mapping as well, in which case you can use that also to log the value of an expression, and not just a single variable that will match a word:

xnoremap <Leader>L "ayOconsole.log('<C-R>a:', <C-R>a);<Esc>

See :help i_CTRL-R for more details on how <C-R> works in insert mode.

  • 1
    Thanks, filbranden! It definitely looks better than mine! – Jordi Nebot Nov 13 at 19:46
9

Can you guys think of a more elegant way to do the same?

Well, at least we can try our best :-)

nnoremap <silent><Leader>L :put! =printf('console.log(''%s:'',  %s);', expand('<cword>'), expand('<cword>'))<CR>
  • Thank you, Matt! I'll give it a try :) – Jordi Nebot Nov 13 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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