Zashas
Zashas

Reputation: 766

Command for putting backticks around the current word

I have to format a lot of files in markdown manually, and I often have to wrap some isolated words in backticks to get them in a code span, i.e.: object.method to `object.method`

I'm using Vim and I was wondering how I could write and map to some key a command which would put backticks around the word under cursor, by just pressing F1 for instance?

Upvotes: 4

Views: 2024

Answers (4)

Xavier T.
Xavier T.

Reputation: 42248

The canonical answer is to use surround plugin by Tim Pope that allows to surround easily a selection.(Unless you don't want to install any plugin)

Upvotes: 5

Luc Hermitte
Luc Hermitte

Reputation: 32966

lh-brackets has several mappings already defined for markdown:

  • backtick will insert a pair of backticks in insert mode, or surround the current word or the current selection (what you were looking for, and that surround also provides with its own "syntax")
  • * -> *<cursor>* ; twice for **<cursor>** (<localleader>* for surrounding)
  • _ -> _<cursor>_ ; twice for __<cursor>__ (_ for surrounding)
  • ~ -> <del><cursor></del> (<localleader>~ for surrounding)
  • <BS> -> in INSERT mode, deletes an empty pair when the cursor is within it.

Upvotes: 2

rangalo
rangalo

Reputation: 5606

Here is a one liner you can try:

:nmap <F4> :s/\(<c-r>=expand("<cword>")<cr>\)/`\1`/<cr>

After this command pressing F4 key will do what you want, i.e. replace the word under cursor with the same word surrounded by backticks.

[UPDATE]

This may not work for something like object.Method. For this here is a new mapping in visual mode. Select the block of text you want to surround with backtick and press F3

:vnoremap <F3> <Esc>`>a`<Esc>`<i`<Esc

Upvotes: 1

romainl
romainl

Reputation: 196691

Another (crude) no-plugin solution for the sake of diversity:

nnoremap <key> ciw`<C-r>"`<Esc>
xnoremap <key> c`<C-r>"`<Esc>

but yeah, just install surround.

Upvotes: 3

Related Questions