Wednesday, October 21, 2009

CTRL-V for Literal Characters

When typing in insert or ex mode, hiting CTRL-V allows you to enter a literal character. Some examples:

CTRL-V CTRL-M # enters a literal carriage-return \r
CTRL-V 10 <enter> # enters a null character

After entering the CTRL-V, you can either enter the character explicitly or type in its decimal code. A list of decimal codes is available through the :digraph ex command. If you're curious why this might be useful, I've used it on a number of occasions in conjunction with a substitution to remove binary characters from a file. An example might be:

:%s/CTRL-V CTRL-M//g # remove erroneous CTRL-M from the current file

You can find out the code for any character by putting it under the cursor and hitting "ga" in normal mode. For entering digraphs, you can also hit CTRL-K from insert mode and type the two letter character code preceeding the desired character.


Steven Bakker said...

"CTRL-V 10 <enter> # enters a literal line-feed \n"

... not really. My vim (7.2.148) inserts a "^@" (i.e. null character). All the other stuff works, though.

BTW, thanks for the "ga" and digraph tips. Never bothered to go hunting for something like that, and it's a big timesaver!

Travis Whitton said...

@Steven You're absolutely correct. I made a typo when putting this together. Thanks for the correction.

GrogBlog said...

I've been scouring the internet looking for this tip.

GrogBlog said...
This comment has been removed by the author.
GrogBlog said...

Additional insight:
On my version of vi (windows cygwin VIM 7.2):
CTRL-V nnn seems to want three digits, it completes and prints the control character after three characters. After only 1 or 2 digits, it is incomplete but will finish when the next non-digit character is pressed:

CTRL-V 000 produces a NULL.
CTRL-V 00 a - produces a NULL character followed by an "a".
CTRL-V 0 a - produces a NULL character followed by an "a".

LF=10 seems to be mapped to NULL on my system as well:

CTRL-V 010 produces a NULL.
CTRL-V 10 a - produces a NULL character followed by an "a".
CTRL-V 10 enter - produces a NULL character followed by a LF.

A related observation is that digraph has two "10" codes listed:

NU ^@ 10 ... LF ^@ 10 ...

Hope that helps somebody. The other published way of creating a null CTRL-V CTRL-SHIFT-@ key does not work under windows.