包括文件并缩进每一行



我想包含一个文件,并缩进所有行。我希望它是Markdown文档中的代码块。

基本上我想要这样的东西:

text
include(somefile)
text

有此输出:

text
    content
    from
    somefile
text

我浏览了手册,找到了patsubst。我还发现了这个问题和答案:如何在M4 Macro

中缩进一块文本。

适用于包含逗号的文件:

$ cat textnocomma 
some text.
with sentences.
and no commas.
$ cat patsubstincludenocomma
text
patsubst(include(textnocomma), `^', `    ')
text
$ m4 patsubstincludenocomma
text
    some text.
    with sentences.
    and no commas.
text

但是当我 include时,一个包含逗号的文件:

$ cat textcomma 
some text.
with sentences.
and, commas.
$ cat patsubstincludecomma
text
patsubst(include(textcomma), `^', `    ')
text
$ m4 patsubstincludecomma
text
m4:patsubstincludecommanoquote:3: Warning: excess arguments to builtin `patsubst' ignored
some text.
with sentences.
and
text

问题似乎是M4宏扩展的幼稚方式。包含文本的逗号被解释为patsubst宏的语法。解决方案(应该很简单):引用随附的文本。

但是,如果我引用 include,则只有第一行被缩进:

$ cat patsubstincludecommaquote 
text
patsubst(`include(textcomma)', `^', `    ')
text
$ m4 patsubstincludecommaquote
text
    some text.
with sentences.
and, commas.
text

我尝试了不同的引用和文字新线的组合,而不是正则新线。但是到目前为止,我所得到的就是excess arguments错误消息,或者只是第一行缩进。

如何将文本与逗号或其他M4语法一起包含,并在M4中缩进?

我已经进行了一些研究,可以得出结论,引用include使patsubst不再识别文本中文本中的^(线的开始)。至少在我的系统上。

$ m4 --version
m4 (GNU M4) 1.4.18
...

观察:

$ cat textnocomma 
some text.
with sentences.
and no commas.
$ cat includenocomma 
foo
patsubst(include(textnocomma), `^', `    ')
bar
patsubst(`include(textnocomma)', `^', `    ')
baz
$ m4 includenocomma 
foo
    some text.
    with sentences.
    and no commas.
bar
    some text.
with sentences.
and no commas.
baz

将文本定义为"字符串文字"而不是include

时也会发生这种情况。
$ cat definestringliterals 
define(`sometext', `first line
second line
third line')dnl
foo
patsubst(sometext, `^', `    ')
bar
patsubst(`sometext', `^', `    ')
baz
$ m4 definestringliterals 
foo
    first line
    second line
    third line
bar
    first line
second line
third line
baz

这是一个支持此观察结果的问题和答案:如何匹配gnu m4 _ _properly _

中的newlines

奇怪的是,如果将字符串文字直接放入patsubst

时,这不会发生
$ cat patsubststringliterals 
foo
patsubst(first line
second line
third line, `^', `    ')
bar
patsubst(`first line
second line
third line', `^', `    ')
baz
$ m4 patsubststringliterals 
foo
    first line
    second line
    third line
bar
    first line
    second line
    third line
baz

使用Parens"引用"文本没有此问题。但是现在我的文字周围有帕伦斯:

$ cat textcomma 
some text.
with sentences.
and, commas.
$ cat includecomma 
foo
patsubst(include(textcomma), `^', `    ')
bar
patsubst(`include(textcomma)', `^', `    ')
baz
patsubst((include(textcomma)), `^', `    ')
qux
$ m4 includecomma 
foo
m4:includecomma:2: Warning: excess arguments to builtin `patsubst' ignored
some text.
with sentences.
and
bar
    some text.
with sentences.
and, commas.
baz
    (some text.
    with sentences.
    and, commas.
    )
qux

所以我想这是一个错误。如果引用include,则patsubst将不再识别^,除了第一行。但是引用 include是必要的,以防止文本中的逗号解释为语法。

为什么不使用外部命令?

esyscmd(`sed "s,^,    ," textcomma')

最新更新