4

I've the following sample content which I want to edit:

<table>
<tr><td title="Title 1">col1</td><td>col2</td><td>col3</td></tr>
<tr><td title="Title 2">col1</td><td>col2</td><td>col3</td></tr>
<tr><td title="Title 3">col1</td><td>col2</td><td>col3</td></tr>
</table>

Note: It doesn't matter it's HTML, that kind of operation can apply to any format, so I'm not interested in HTML parsers.

Where I'd like to copy all values of title into separate column, so the expected result is:

<table>
<tr><td title="Title 1">col1</td><td>col2</td><td>col3</td><td>Title 1</td></tr>
<tr><td title="Title 2">col1</td><td>col2</td><td>col3</td><td>Title 2</td></tr>
<tr><td title="Title 3">col1</td><td>col2</td><td>col3</td><td>Title 3</td></tr>
</table>

My plan is to find all td title using global command (g) and execute normal commands:

  1. Copy quoted text (f"lyt").
  2. Find </td></tr> (/<.td><.tr>, <CR>?).
  3. Append <div> (a<div>, <Esc>?)
  4. Paste yanked text (p).
  5. Append </div> (a</div>, <Esc>?)

But I don't know how to simulate presses of Enter and Escape after search or text appending.

I've tried this:

:g/td title/norm f"lyt"/<.td><.tr><CR>f>a<td><Esc>pa</td><Esc>

but it doesn't work, because <CR> and <Esc> aren't recognised as keystrokes.

Although it works when I insert these keystrokes manually while typing the command by using Control-V, then Control+Enter (^M) or Control+Escape (^[).

Is there any alternative method where I can insert those keystrokes without using Control-V?

4

exec the norm command. From :h :norm:

An alternative is to use :execute, which uses an
expression as argument.  This allows the use of
printable characters to represent special characters.

Example: 
        :exe "normal \<c-w>\<c-w>"

Note the usage of double quotes and the \ before < for the special characters.

Your example would translate to something like:

:g/td title/ exec 'norm f"lyt"/<.td><.tr>' . "\<CR>f>a<td>\<Esc>pa</td>\<Esc>"

Here, I have used single quotes for the initial part of the command, both because it has " inside, and because single quotes give you a literal string without interpretation. Then, double-quoted strings where you need <CR>, <Esc> to be interpreted.

  • 4
    \n and \e can be used in place of \<CR> and \<Esc>, respectively, in an expression string - they're easier to type. Also, \t in place of \<Tab> and \b in place of \<BS>. – djjcast Mar 29 '16 at 2:23
  • 1
    @djjcast, yes the full list being available at :h string. – muru Mar 29 '16 at 2:26

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.