所以我把代码从

foo()
{


foo() {

我注意到搜索模式要求我搜索\n,但是当我试图用\n替换它时,我得到了^@字符,我不得不用\r替换。
在我看来,用\n搜索并替换为\r似乎很奇怪,知道这可能是什么原因吗?
作为参考,我的解决方案是:%s/\n\s*{/ {\r/g

最佳答案

搜索部分和替换部分的语法是任意不同的。一些相同的代码被重新用来表示不同的东西。是啊,真让人困惑。

    | How to type         | In search, means:       | In replacement, means:
----------------------------------------------------------------------------
\n  | \n                  | End-of-line             | <Nul> 0x0
^@  | CTRL-V CTRL-J       | <Nul> 0x0               | <Nul> 0x0
\r  | \r                  | Carriage return 0xD     | "Break the line here"
^M  | CTRL-Enter          | Carriage return 0xD     | "Break the line here"
\^M | \ CTRL-V CTRL-ENTER | \ + carriage return 0xD | Carriage return 0xD

搜索时,根据您的平台,0xD可能被隐藏,被视为“newline”的一部分,所以是的…您始终可以使文件恢复正常,并通过打开文件并执行以下操作强制显示所有回车:
:e ++ff=unix

类似地,在替换时,“break the line here”会根据您的平台执行不同的操作。它可能插入0xA0xD 0xA等。
如果这还不够糟糕:
Technical detail:               *NL-used-for-Nul*
<Nul> characters in the file are stored as <NL> in memory.  In the display
they are shown as "^@".  The translation is done when reading and writing
files.  To match a <Nul> with a search pattern you can just enter CTRL-@ or
"CTRL-V 000".  This is probably just what you expect.  Internally the
character is replaced with a <NL> in the search pattern.  What is unusual is
that typing CTRL-V CTRL-J also inserts a <NL>, thus also searches for a <Nul>
in the file.  {Vi cannot handle <Nul> characters in the file at all}

                        *CR-used-for-NL*
When 'fileformat' is "mac", <NL> characters in the file are stored as <CR>
characters internally.  In the text they are shown as "^J".  Otherwise this
works similar to the usage of <NL> for a <Nul>.

When working with expression evaluation, a <NL> character in the pattern
matches a <NL> in the string.  The use of "\n" (backslash n) to match a <NL>
doesn't work there, it only works to match text in the buffer.

除非处理文字0x00xD字符,否则始终使用\n进行搜索和\r进行替换是一条经验法则,正如您可能已经知道的那样。
另见:
:h /\n
:h /\r
:h s/\n
:h s/\r
:h s/\<CR>

07-24 09:46
查看更多