sdpfj
sdpfj

Reputation: 11

Dynamically replacing (or appending/prepending) to selection in Vim

I have the following paragraph in a plain text file that I am viewing (and editing) in Vim:

The synthesis and secretion of estrogens is stimulated by follicle-stimulating hormone (FSH), which is, in turn, controlled by the hypothalamic gonadotropin releasing hormone (GnRH). High levels of estrogens suppress the release of GnRH (bar) providing a negative-feedback control of hormone levels.

I am creating cloze deletion flashcards out of the text in this text file (ie. fill in the blank questions) which I will then feed to a home-made flashcard program I've written. My format for a cloze deletion is as follows:

The synthesis and secretion of [estrogens] is stimulated by [follicle-stimulating hormone]

This would produce two flashcards (when the text file is parsed by my flashcard program):

The synthesis and secretion of [...] is stimulated by follicle-stimulating hormone
The synthesis and secretion of [estrogens] is stimulated by [...]

I would like to automate the creation of these flashcards using Vim. The manual option would be to write a '[' to the beginning of each cloze deletion and a ']' at the end, but this is tedious and I'd like to use Vim's automation abilities. Ideally, I would like to be able to:

  1. select a region of text to clozeify
  2. execute a macro on this text

This macro would:

  1. prepend '[' to the selection
  2. append ']' to the selection

and exit.

How would I achieve this using Vim? When I try to use Ctrl-R in Visual Selection Mode it doesn't seem to work.

Essentially, the replacement I would like to do is:

:%s/(CONTENT OF VISUAL SELECT)/[(CONTENT OF VISUAL SELECT)]/g

Upvotes: 1

Views: 78

Answers (1)

romainl
romainl

Reputation: 196626

This is very easy to do with built-in commands:

v<motion>
c[<C-r>"]<Esc>

Breakdown:

  • v<motion> is what you already do to visually select the text to transform.
  • c cuts the visually selected text to the unnamed register and puts you in insert mode.
  • [ inserts an opening bracket.
  • <C-r>" inserts the content of the unnamed register.
  • ] inserts a closing bracket.
  • <Esc> puts you back into normal mode.

With that in mind, you can record a macro of the edit above and play it back on any visual selection:

v<motion>
qq
c[<C-r>"]<Esc>
q

then:

v<motion>@q

Breakdown:

  • qq starts recording in register q.
  • q stops recording.

or create a visual mode mapping:

xnoremap <key> c[<C-r>"]<Esc>

If that's something you need to do often, you should probably take a look at Surround or Sandwich, which make all that considerably easier.

Reference:

:help c
:help i_ctrl-r
:help recording

Upvotes: 1

Related Questions