I copy stuff from output buffers into C++ code I’m working on in vim.
Often this output gets stuck into strings. And it’d be nice to be able to escape all the control characters automatically rather than going back and hand editing the pasted fragment.
As an example I might copy something like this:
error in file "foo.dat"
And need to put it into something like this
std::string expected_error = "error in file \"foo.dat\""
I’m thinking it might be possible to apply a replace function to the body of the last paste using the start and end marks of the last paste, but I’m not sure how to make it fly.
UPDATE:
Joey Mazzarelli sugested using
`[v`]h:%s/\%V"/\\"/g
after a paste.
Since no explaination was given for what that was going and I initially found it a bit terse, but hard to explain in the comments I thought I’d put an explaination of what I think that does here:
`[ : Move to start of last paste
v : Start visual mode
`] : Move to end of last paste
h : adjust cursor one position left
:% : apply on the lines of the selection
s/ : replace
\%V : within the visual area
" : "
/ : with
\\" : \"
/g : all occurrences
This seems like a good approach, but only handles the one character, “, I’d like it to handle newlines, tabs, and other things that might be expected to fall in text. (Probably not general unicode though) I understand that may not have been clear in the problem definition.
Here are a couple of vimscript functions that should do what you want.
EscapeText()transforms arbitrary text to the C-escaped equivalent. It converts newline to\n, tab to\t, Control+G to\a, etc., and generates octal escapes (like\o032) for special characters that don’t have a friendly name.PasteEscapedRegister()escapes the contents of the register named byv:register, then inserts it into the current buffer. (The register is restored when the function returns, so the function can be called repeatedly without escaping the register contents multiple times.)There are also a couple of key mappings included to make
PasteEscapedRegister()easy to use interactively.<Leader>Ppastes escaped register contents before the cursor position, and<Leader>ppastes after. Both can be prefixed with a register specification, like"a\Pto paste the escaped contents of register a.Here’s the code: