m4

Is there a way to include a subset of lines from an included file using m4?


Is there a way to include a subset of lines from an included file when using m4? something along the lines of include(`source.cpp', 12-15)?

I'm creating a markdown presentation using reveal.js and want to include code samples. In many cases I want to include a subset of lines from a source file. In those cases I've created a copy of the file and trimmed each copy to what should be included at each inclusion. This however leads to multiple source files which need to be updated manually if a common line changes. I want to include the same file in multiple places, specifying which lines to include at each inclusion.

I've thought of using sed but want to avoid external tools if possible. I also want to be able to specify included folders using the m4 -I option.

Suggestions on m4 macros using external tools are welcome, even if an answer using m4 only is appreciated.


Solution

  • Can-do!

    define(`repeat_newline',`ifelse($1,0,,`[^
    ]*
    repeat_newline(decr($1))')')dnl
    define(`quote',``$*'')dnl
    define(`include_lines',`regexp(quote(include($1)),^repeat_newline($2)`\('repeat_newline($3)`\)',`\1')')
    

    Usage: include_lines(my_file.txt, 2, 5) reads 5 lines starting from the third line (2 is zero-indexed). It expands macros in the included file, just like include.