\ n和\ r在Vim中不同情况下的不同行为

时间:2015-12-24 14:29:55

标签: vim

假设我有一个只有一个角色'的行,让我们看看\n在不同情况下的效果:

:s/s/a\nb
a^@b
:s/s/a\\nb
a\nb
:s/s/a\\\nb
a\^@b
:s/s/a\\\\nb
a\\nb

:echo "a\nb"
a
b
:echo "a\\nb"
a\nb
:echo "a\\\nb"
a\
b
:echo "a\\\\nb"
a\\nb

那么为什么\n表现不同?然后让我们使用substitute()

查看条件
:echo substitute(" ", " ", "a\nb", "")
a
b
:echo substitute(" ", " ", "a\\nb", "")
a
b
:echo substitute(" ", " ", "a\\\nb", "")
a
b
:echo substitute(" ", " ", "a\\\\nb", "")
a\nb

这一次,\n仍被解释为“换行符”,但如何解释反斜杠?

下一部分,比方说我还有一个只有一个字符''的行,而不是\n\r将会被研究:

:s/s/a\rb
a
b
:s/s/a\\rb
a\rb
:s/s/a\\\rb
a\
b
:s/s/a\\\\rb
a\\rb

\r的效果类似于\n中的:echo "a\nb",反斜杠的规则是相同的。

:echo "a\rb"
b
:echo "a\\rb"
a\rb
:echo "a\\\rb"
b\  "This is the most strange case!!!
:echo "a\\\\rb"
a\\rb

\r在这种情况下做了什么?而第三个子案甚至更奇怪。

:echo substitute(" ", " ", "a\rb", "")
b
:echo substitute(" ", " ", "a\\rb", "")
b
:echo substitute(" ", " ", "a\\\rb", "")
b
:echo substitute(" ", " ", "a\\\\rb", "")
a\rb

但是,我无法理解不同数量的反斜杠表现如何。

我的问题是:

  1. 为什么\n\r:substituteecho直接和substitute()下的行为有所不同?
  2. 使用substitute()时如何解释不同数量的反斜杠效果?
  3. Vim中\n\r之间有什么区别?
  4. 补充1:

    如果我:let s = "a\\\nb"然后<C-r>=s在缓冲区中看到它,我看到了

    a\
            b
    

    如何解释这个?

1 个答案:

答案 0 :(得分:2)

  1. 对于:echosubstitute()\n是换行符,\r是回车符。他们应该按照你的期望做。 \n将光标移动到下一行(第1列),\r将光标移动到第1列相同的行。对于\r,下一个打印的字符将覆盖以前的打印字符。 (我主要关注substitute():echo:substitute位于下方)

  2. 为什么echo和substitute()的行为不同。您需要了解对字符串的解释有多少。对于echo,只有一个发生在substitute()两个发生。

    :echo substitute(" ", " ", "a\\\rb", "")
    b
    :echo substitute(" ", " ", 'a\\\rb', "")
    b\
    
  3. 第二个与你对echo的预期相同。 双引号中的字符串根据:help expr-quote更改了内容。这意味着如果字符串只被解释一次(使用单引号),echo和substitute都会看到同样的事情。

    "a\\\rb"在一次解释后被解释为a\rb,然后在第二次解释后被解释为a<CR>b。这导致只有b被打印。

    1. \r\n会根据使用位置而改变。唯一的区别是:substitute,其中\r用作替换中的换行符。
    2. 这是:substitutesubstitute()行为不同的情况之一,

      :substitue跟随

        <CR>        split line in two at this point
                    (Type the <CR> as CTRL-V <Enter>)                  s<CR>
        \r          idem                                               s/\r
        ...
        \n          insert a <NL> (<NUL> in the file)
                    (does NOT break the line)                          s/\n
      

      <NUL>^@相同,与换行符不同)

      substitute()跟随

      The special meaning is also used inside the third argument {sub} of
      the substitute() function with the following exceptions:
      ...
        - <CR> and \r inserts a carriage-return (CTRL-M).
      ...