3

How do I write control characters in a file using Vim? For example, I want to write the backspace character, which is invoked using ^? (or the dedicated Backspace) key on the keyboard, to a file. But I can't seem to do that - everything I try just erases a character.

The Unix Programming Environment by Kernighan and Pike says (§2.1 The basics of files):

It is important in each case to distinguish between how the character is stored in a file and how it is interpreted in various situations. For example, when you type a backspace on your keyboard (and assuming that your erase character is backspace), the kernel interprets it to mean that you want to discard whatever character you typed previously. Both that character and the backspace disappear, but the backspace is echoed to your terminal, where it makes the cursor move one position backwards.

If you type the sequence

\←

(i.e., \ followed by a backspace), however, the kernel interprets that to mean that you want a literal backspace in your input, so the \ is discarded and the byte 010 winds up in your file. When the backspace is echoed on your terminal, it moves the cursor to sit on top of the \.

When you print a file that contains a backspace, the backspace is passed uninterpreted to your terminal, which again will move the cursor one position backwards. When you use od to display a file that contains a backspace, it appears as a byte with value 010, or, with the -c option, as \b.

Basically, it's saying that writing a backslash before backspace character should work (at least for ed). However I'm not able to write it using Vim. How can I write uncommon control characters into the file (such as backspace)

4

You can use CTRL-V in Insert mode as a prefix to insert the next key as a literal expression.

So if you enter CTRL-V followed by Backslash, you'll get a ^? character inserted.

Another option, if you want to enter a character by its number, is to use CTRL-V followed by a set of digits. (See :help i_CTRL-V_digit.) A backspace character has code 127, so you can enter it with CTRL-V followed by 127, resulting on the same ^? character.

(You can inspect the ^? character with the ga command, which will show <^?> 127, Hex 7f, Oct 177, Digr DT, including the character code in decimal, hexadecimal and octal.)

In fact, one more way to enter this character is using Vim's digraph support. In this case, you can use CTRL-K followed by D, then T, both uppercase, to enter the same ^? character. You can use the :digraphs command to get a table with all available digraphs.

| improve this answer | |
  • 2
    Thank you excellent answer – Lavya Apr 5 at 23:59

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.