- 颜色设置
- 字体设置
- 行号显示
如果要制作彩色的文档,里面引用的代码就得用彩色进行语法高亮了,这个功能是原始LaTex和fancyvrb不支持的。Listings的语法高亮主要分为关键字、注释、id、基本字符、字符串。在listset中分别使用keywordstyle、commentstyle、identifierstyle、basicstyle、stringstyle来配置。
要设置颜色,必须用到color或xcolor包,这样才可以使用color命令。仿照开发工具的语法高亮,我写了一个例子:
documentclass[utf8]{paper}
usepackage{ctex}
usepackage{listingsutf8}
usepackage{lstautogobble}
usepackage{xcolor}
lstset{
tabsize=4
}
begin{document}
title{Heap算法}
author{醒过来摸鱼}
maketitle
abstract{Heap算法的Python实现}
lstset{
basicstyle=color{white},
keywordstyle=color{yellow},
identifierstyle=color{white},
stringstyle=color{green},
backgroundcolor=color{black!70},
commentstyle=color{gray}
}
begin{lstlisting}[language=python,autogobble]
def recursive(array, last, result):
if last == 0:
result.append(array[:])
return
for i in range(0, last + 1):
recursive(array, last - 1, result)
before = array[:]
if last & 1 == 0:
array[0], array[last] = array[last], array[0]
else:
array[i], array[last] = array[last], array[i]
# all permutations
def permutations(array):
result = []
recursive(array, len(array) - 1, result)
return result
if __name__ == '__main__':
result = permutations(['A', 'B', 'C', 'D'])
for x in result:
print(x)
end{lstlisting}
end{document}
编译效果如图:
字体设置和颜色设置一样,不过需要注意的是字体设置分命令和定义。什么意思呢?以text开头的,比如textit是命令,而对应的itshape这种就是定义。最好是用定义不要用命令。我举个例子:
documentclass[UTF8,a4paper]{article}
usepackage{ctex}
usepackage{listings}
usepackage{lstautogobble}
usepackage{xcolor}
lstset{
basicstyle=color{white}rmfamily,
keywordstyle=color{yellow}slshape,
identifierstyle=color{white},
stringstyle=color{green}bfseries,
backgroundcolor=color{black!70},
numberstyle=color{green!50},
commentstyle=color{gray}itshape
}
begin{document}
begin{lstlisting}[language=Python,autogobble]
def combinations(input):
# 队列元素是集合加上索引的元组
queue = [([], 0)]
result = []
while len(queue) > 0:
e = queue.pop(0)
result.append(e[0])
# 计算children
subarray = input[e[1]:]
for i, child in enumerate(subarray):
x = (e[0] + [child], e[1] + i + 1)
queue.append(x)
return result
if __name__ == '__main__':
print(combinations(['A', 'B', 'C']))
end{lstlisting}
end{document}
编译效果如下,从图中可以看到斜体加粗等均生效了:
用numbers=left来在左边显示行号,使用numberstyle来指定行号的样式,如下例:
documentclass[UTF8,a4paper]{article}
usepackage{ctex}
usepackage{listings}
usepackage{lstautogobble}
usepackage{xcolor}
lstset{
basicstyle=color{white}rmfamily,
keywordstyle=color{yellow}slshape,
identifierstyle=color{white},
stringstyle=color{green}bfseries,
backgroundcolor=color{black!70},
numberstyle=color{black!50},
commentstyle=color{gray}itshape
}
begin{document}
begin{lstlisting}[language=Python,autogobble,numbers=left]
def combinations(input):
# 队列元素是集合加上索引的元组
queue = [([], 0)]
result = []
while len(queue) > 0:
e = queue.pop(0)
result.append(e[0])
# 计算children
subarray = input[e[1]:]
for i, child in enumerate(subarray):
x = (e[0] + [child], e[1] + i + 1)
queue.append(x)
return result
if __name__ == '__main__':
print(combinations(['A', 'B', 'C']))
end{lstlisting}
end{document}
编译效果,在左边以灰色显示了行号:



