我想排版一些朱莉娅代码、语法高亮等,listings
软件包。有关信息,Julia 语言是 MATLAB 的有力竞争者,而且免费且开源。
然而,listings
没有附带 Julia 的语言定义。我找到了一个调色师语言规范这里。我该如何调整它才能用包正确地突出显示 Julia 代码listings
?
为了便于说明,下面是一个 MWE 和一些 Julia 代码示例(改编自http://julialang.org)嵌入在lstlisting
环境中:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage{listings}
\lstset{basicstyle=\ttfamily}
\begin{document}
\begin{lstlisting}
#= This is a code sample for the Julia language
(adapted from http://julialang.org) =#
function mandel(z)
c = z
maxiter = 80
for n = 1:maxiter
if abs(z) > 2
return n-1
end
z = z^2 + c
end
return maxiter
end
function helloworld()
println("Hello, World!") # Bye bye, MATLAB!
end
function randmatstat(t)
n = 5
v = zeros(t)
w = zeros(t)
for i = 1:t
a = randn(n,n)
b = randn(n,n)
c = randn(n,n)
d = randn(n,n)
P = [a b c d]
Q = [a b; c d]
v[i] = trace((P.'*P)^4)
w[i] = trace((Q.'*Q)^4)
end
std(v)/mean(v), std(w)/mean(w)
end
\end{lstlisting}
\end{document}
答案1
listings
您将在下面的代码中找到Julia 语言的语言定义。
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage{listings}
\usepackage[usenames,dvipsnames]{xcolor}
%%
%% Julia definition (c) 2014 Jubobs
%%
\lstdefinelanguage{Julia}%
{morekeywords={abstract,break,case,catch,const,continue,do,else,elseif,%
end,export,false,for,function,immutable,import,importall,if,in,%
macro,module,otherwise,quote,return,switch,true,try,type,typealias,%
using,while},%
sensitive=true,%
alsoother={$},%
morecomment=[l]\#,%
morecomment=[n]{\#=}{=\#},%
morestring=[s]{"}{"},%
morestring=[m]{'}{'},%
}[keywords,comments,strings]%
\lstset{%
language = Julia,
basicstyle = \ttfamily,
keywordstyle = \bfseries\color{blue},
stringstyle = \color{magenta},
commentstyle = \color{ForestGreen},
showstringspaces = false,
}
\begin{document}
\begin{lstlisting}
#= This is a code sample for the Julia language
(adapted from http://julialang.org) =#
function mandel(z)
c = z
maxiter = 80
for n = 1:maxiter
if abs(z) > 2
return n-1
end
z = z^2 + c
end
return maxiter
end
function helloworld()
println("Hello, World!") # Bye bye, MATLAB!
end
function randmatstat(t)
n = 5
v = zeros(t)
w = zeros(t)
for i = 1:t
a = randn(n,n)
b = randn(n,n)
c = randn(n,n)
d = randn(n,n)
P = [a b c d]
Q = [a b; c d]
v[i] = trace((P.'*P)^4)
w[i] = trace((Q.'*Q)^4)
end
std(v)/mean(v), std(w)/mean(w)
end
\end{lstlisting}
\end{document}
答案2
对于那些从 Google 找到这个页面的人来说:
受到 Jubobs 三年前的帖子的启发,我最近为 listings 包创建了一个 julia 语言定义,尝试以与官方在线文档相同的方式显示 julia 代码:https://docs.julialang.org/en/stable/
所以如果你有兴趣,可以去看看:https://github.com/wg030/jlcode