我尝试实现一个简单的环境来突出显示 LaTeX 中的源代码。我的解决方案是:
- 用于
VerbatimOut
在文件中写入文本 - 使用
\write18
执行 source-hightlight 来处理保存的文件 \input
结果\shadowbox
并且成功了。代码如下:
%%%
%%% A simple environment used to highlight source code
%%% Only usable in linux with source-highlight installed
%%% [email protected]
%%% 2012-07-05 Thu 16:00 PM CST+0800
%%%
\usepackage[usenames, dvipsnames]{color}
\usepackage{fancybox} % must placed before "fancyvrb"
\usepackage{fancyvrb}
\newcommand{\SourceTabWidth}{4}
\makeatletter
%% USAGE:
%% \HandleCode{input}{output}{tabwidth}{source language}
\newcommand\HandleCode[4] {
\immediate\write18{source-highlight --tab=#3 --src-lang=#4 --out-format=latexcolor -i #1 -o #2}
}
%%
%% USAGE:
%% \begin{SourceCode}{language}
%% ...code...
%% \end{SourceCode}
%%
\newenvironment{SourceCode}[1] %
{ %
\def\mySourceCodeLanguage{#1}
\def\mySourceCodeInput{\jobname.code.#1}%
\def\mySourceCodeOutput{\jobname.hcode.tex}%
\VerbatimEnvironment%
%% codes option to make sure TAB intact
\begin{VerbatimOut}[codes={\catcode`\^^I=12}]{\mySourceCodeInput}}%
{\end{VerbatimOut}%
\HandleCode{\mySourceCodeInput}{\mySourceCodeOutput}{\SourceTabWidth}{\mySourceCodeLanguage} %
\shadowbox{%
\parbox{0.8\textwidth}{%
\input{\mySourceCodeOutput} %
}%
}%
%% delete temp files
\immediate\write18{rm \mySourceCodeInput; rm \mySourceCodeOutput}%
}
\makeatother
但是,有一个问题。当我将其放在包fancyvrb
之前时fancybox
。
[codes={\catcode`\^^I=12}]
选项不起作用,并且[.tex
将创建一个文件。
所以我猜想fancybox
已经改变了一些内部状态。但我搞不懂。
任何建议将被认真考虑!
将代码保存为source-highlight.sty。示例代码(sample.tex)为:
\documentclass{article}
\usepackage{source-highlight}
\begin{document}
\begin{SourceCode}{cpp}
int main(int argc, char* argv[]) {
return 0;
}
\end{SourceCode}
\end{document}
编译命令为:
pdflatex --shell-escape sample.tex
答案1
使用当前的 TeXLive 2011 我得到输出:
我使用了以下代码:
\RequirePackage{filecontents}
\begin{filecontents*}{source-highlight.sty}
\RequirePackage{xcolor}
\usepackage{fancybox}
\usepackage{fancyvrb}
\newcommand{\SourceTabWidth}{4}
\newcommand\HandleCode[4] {
\immediate\write18{source-highlight --tab=#3 --src-lang=#4 --out-format=latexcolor -i #1 -o #2}
}
\newenvironment{SourceCode}[1] %
{ \VerbatimEnvironment
\def\mySourceCodeLanguage{#1}
\def\mySourceCodeInput{\jobname.code.#1}%
\def\mySourceCodeOutput{\jobname.hcode.tex}%
\VerbatimEnvironment%0
\begin{VerbatimOut}[codes={\catcode`\^^I=12}]{\jobname.code.#1}}%
{\end{VerbatimOut}
\HandleCode{\mySourceCodeInput}{\mySourceCodeOutput}{\SourceTabWidth}{\mySourceCodeLanguage} %
\shadowbox{%
\parbox{0.8\textwidth}{%
\input{\mySourceCodeOutput} %
}%
}%
\immediate\write18{rm \mySourceCodeInput; rm \mySourceCodeOutput}%
}
\endinput
\end{filecontents*}
\PassOptionsToPackage{dvipsnames,svgnames}{xcolor}
\documentclass{beamer}
\usepackage{source-highlight}
\begin{document}
\begin{frame}[fragile]{Hihlight demo}
foo
\begin{SourceCode}{cpp}
int main(int argc, char* argv[]) {
return 0;
}
\end{SourceCode}
bar
\end{frame}
\end{document}