为什么Windows上的Vim使用\ n进行搜索?

时间:2010-09-30 18:25:08

标签: windows vim newline

所以我正在改变

中的代码
foo()
{

foo() {

我注意到搜索模式要求我搜索\n,但当我尝试将其替换为\n时,我获得了^@字符,我不得不替换与\r

我似乎很奇怪,我使用\n进行搜索并替换为\r,我知道为什么会这样做?

作为参考,我的解决方案是:%s/\n\s*{/ {\r/g

2 个答案:

答案 0 :(得分:17)

搜索部分和替换部分的语法是任意不同的。一些相同的代码被重复用于表示不同的东西。是的,这令人困惑。

    | 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可能会被隐藏,被视为“换行符”的一部分,所以是的...您可以始终将完整性恢复到您的文件并强制显示所有回车符打开文件并执行:

:e ++ff=unix

同样在更换时,“在这里打破线”根据您的平台做不同的事情。它可能会插入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>

答案 1 :(得分:1)

我认为你的问题是因为像Linux这样的类Unix操作系统使用换行符(又名“换行”)(0x0A)作为行结束标记,但Windows使用回车+换行符(0x0D 0x0A) 。 vim试图进行某种映射,使Windows的两字节行结束看起来像一个“行尾”。

在相关的说明中,以下命令似乎在Windows机器上将Unix风格的文件转换为Windows风格,并在Unix机器上将Windows风格的文件转换为Unix文件:

:%s/^V^M/^V^M/g

其中^V表示按住控制键并按下V键,同样^M表示按住控制键并按M.