Why is \r a newline for Vim?

后端 未结 5 2009
执笔经年
执笔经年 2020-11-27 09:30

From question How to replace a character for a newline in Vim?. You have to use \\r when replacing text for a newline, like this

:%s/%/\\r/g
         


        
相关标签:
5条回答
  • 2020-11-27 09:36

    :help NL-used-for-Nul

    Technical detail:

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


    0 讨论(0)
  • 2020-11-27 09:37

    From vim docs on patterns:

    \r matches <CR>

    \n matches an end-of-line - When matching in a string instead of buffer text a literal newline character is matched.

    0 讨论(0)
  • 2020-11-27 09:52

    First of all, open :h :s to see the section "4.2 Substitute" of documentation on "Change". Here's what the command accepts:

    :[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
    

    Notice the description about pattern and string

    For the {pattern} see |pattern|.
    {string} can be a literal string, or something
    special; see |sub-replace-special|.

    So now you know that the search pattern and replacement patterns follow different rules. If you follow the link to |pattern|, it takes you to the section that explains the whole regexp patterns used in Vim.

    Meanwhile, |sub-replace-special| takes you to the subsection of "4.2 Substitute", which contains the patterns for substitution, among which is \r for line break/split.

    (The shortcut to this part of manual is :h :s%)

    0 讨论(0)
  • 2020-11-27 09:53

    Another aspect to this is that \0, which is traditionally NULL, is taken in s//\0/ to mean "the whole matched pattern". (Which, by the way, is redundant with, and longer than, &).

    • So you can't use \0 to mean NULL, so you use \n
    • So you can't use \n to mean \n, so you use \r.
    • So you can't use \r to mean \r, but I don't know who would want to add that char on purpose.

    —☈

    0 讨论(0)
  • 2020-11-27 09:58

    From http://vim.wikia.com/wiki/Search_and_replace :

    When Searching

    ...

    \n is newline, \r is CR (carriage return = Ctrl-M = ^M)

    When Replacing

    ...

    \r is newline, \n is a null byte (0x00).

    0 讨论(0)
提交回复
热议问题