【问题标题】:Why does Vim on windows use \n for searching?为什么 Windows 上的 Vim 使用 \n 进行搜索?
【发布时间】:2011-04-19 12:25:41
【问题描述】:

所以我从

更改代码
foo()
{

foo() {

我注意到搜索模式要求我搜索\n,但是当我尝试用\n 替换它时,我得到了^@ 字符,我不得不用\r 替换它。

我用\n 搜索并替换为\r 对我来说似乎很奇怪,知道为什么会这样吗?

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

【问题讨论】:

  • 你觉得这很奇怪吗?在 Unix 和 Windows 之间移动时,我用来解决回车/换行问题的方法是 :%s/^V^M/^V^M/g
  • @Paul 我觉得这是一个相关的问题。就像它显示一件事,搜索另一件事并写出第三件事一样。

标签: windows vim newline


【解决方案1】:

搜索部分和替换部分的语法任意不同。一些相同的代码被重复用于表示不同的事物。是的,这很混乱。

    | 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>

【讨论】:

    【解决方案2】:

    我认为您的问题是由于类似 Unix 的操作系统(如 Linux)使用换行符(又名“换行符”)(0x0A)作为行尾标记,但 Windows 使用回车符 + 换行符(0x0D 0x0A) . vim 正在尝试进行某种映射,以使 Windows 的两字节行尾看起来像一个“行尾”。

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

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

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

    【讨论】:

    • 我熟悉换行符的区别;我感兴趣的是为什么 Vim 似乎部分掩盖了这一点,以及它使用什么规则来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2015-02-15
    • 2017-04-30
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多