Search code examples
m4

include file and indent every line


I want to include a file and have all the lines indented. I want it to be a code block in a markdown document.

Basically I want something like this:

text
include(somefile)
text

to have this output:

text
    content
    from
    somefile
text

I looked through the manual and found patsubst. I also found this question and answer: How to indent a block of text in an m4 macro

That works for files containing no commas:

$ 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

But when I include a file that contains a comma:

$ 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

The problem seems to be the naive way m4 does macro expansion. The comma from the included text is interpreted as syntax of the patsubst macro. The solution (should be) simple: quote the included text.

But if I quote the include then just the first line is indented:

$ cat patsubstincludecommaquote 
text
patsubst(`include(textcomma)', `^', `    ')
text

$ m4 patsubstincludecommaquote
text
    some text.
with sentences.
and, commas.

text

I have tried different combinations of quoting and literal newlines instead of regex newlines. But all I got so far is either the excess arguments error message or just the first line indented.

How can I include text with comma, and maybe other m4 syntax, and have it indented in m4?


Solution

  • Why don't you use external commands?

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