将环境内容逐字写入文件,调用 Graphviz 并包含源/图像

将环境内容逐字写入文件,调用 Graphviz 并包含源/图像

基于将环境主体逐字写入文件我尝试将环境的内容逐字逐句地写入文件,调用外部工具(在我的情况下是 awesomeGraphviz) 并包含源代码和生成的图形。

listings下面的代码确实有效,但在顶部显示为空白:

\documentclass{article}
\usepackage{graphicx,xcolor}

\makeatletter
\RequirePackage{listings}
\lst@RequireAspects{writefile}
\lstnewenvironment{colenv}[1]{%
\lst@BeginWriteFile{#1.dot}%
}{%
 \lst@EndWriteFile% closes output file
  \immediate\write18{dot -Tpdf -o #1.pdf #1.dot}
  \lstinputlisting{#1.dot}
\includegraphics{#1.pdf}
}
\makeatother

\definecolor{hellgelb}{rgb}{1,1,0.8}
\lstset{%
    frame=single, %
    numbers=left, %
    backgroundcolor=\color{hellgelb}, %
}

\begin{document}

\begin{colenv}{abc}{0.5}{0.5}
digraph G {
 node [shape=box,style=filled,
  color=".6 .3 1.0"];
 edge[arrowhead="none"];
 a [label = "12344445"];
 b [label = "67890"];
 a -> b;
}
\end{colenv}

\end{document}

基本有效

使用上述问题中的第一个解决方案也不起作用,因为#1环境定义中的值丢失了:

\documentclass{article}
\usepackage{graphicx}
\usepackage{xcolor}

\makeatletter
\RequirePackage{listings}
\usepackage{fancyvrb}

\newenvironment{colenv}[1]
  {\typeout{Writing file #1}\VerbatimOut{#1.dot}}
  {\endVerbatimOut %
% Here it does not work
 \immediate\write18{dot -Tpdf -o #1.pdf #1.dot}%
 \lstinputlisting{#1.dot}%
 \includegraphics{#1.pdf}%
}
\makeatother

\definecolor{hellgelb}{rgb}{1,1,0.8}

\lstset{%
    frame=single, %
    numbers=left, %
    backgroundcolor=\color{hellgelb}, %
}

\begin{document}

Test!

\begin{colenv}{abc}
digraph G {
 node [shape=box,style=filled,
  color=".6 .3 1.0"];
 edge[arrowhead="none"];
 a [label = "12344445"];
 b [label = "67890"];
 a -> b;
}
\end{colenv}

% Here it works...
%\immediate\write18{dot -Tpdf -o abc.pdf abc.dot}%
%\lstinputlisting{abc.dot}%
%\includegraphics{abc.pdf}%

\end{document}

结果是

Style option: `fancyvrb' v2.7a, with DG/SPQR fixes, and firstline=lastline fix 
<2008/02/07> (tvz))
! Illegal parameter number in definition of \endcolenv.
<to be read again> 
                   1
l.17 }

? 

答案1

在此处输入图片描述

文件的名称和要运行的命令用和全局保存 \xdef\d@tn@me\xdef\r@ncmd并且使用两个令牌寄存器 +\edef\d@r@ncmd来减少\expandafter命令的数量。

\documentclass{article}
\usepackage{graphicx}
\usepackage{xcolor}

\RequirePackage{listings}
\usepackage{fancyvrb}

\makeatletter
\newenvironment{colenv}[1]%
  {\xdef\d@tn@me{#1}%
  \xdef\r@ncmd{dot -Tpdf -o #1.pdf #1.dot}%
  \typeout{Writing file #1}\VerbatimOut{#1.dot}% 
  }
  {\endVerbatimOut %
 \toks0{\immediate\write18}%
 \expandafter\toks\expandafter1\expandafter{\r@ncmd}%
 \edef\d@r@ncmd{\the\toks0{\the\toks1}}\d@r@ncmd %
 \lstinputlisting{\d@[email protected]}%
 \includegraphics{\d@[email protected]}%
}
\makeatother

\definecolor{hellgelb}{rgb}{1,1,0.8}

\lstset{%
    frame=single, %
    numbers=left, %
    backgroundcolor=\color{hellgelb}, %
}

\begin{document}
Test!
\begin{colenv}{abc}
digraph G {
 node [shape=box,style=filled,
  color=".6 .3 1.0"];
 edge[arrowhead="none"];
 a [label = "12344445"];
 b [label = "67890"];
 a -> b;
}
\end{colenv}
\end{document}

相关内容