code.sty宏包
该宏包定义了Latex插入代码的风格,在导言区包含该宏包
\usepackage{code}
该宏包的代码如下
% Code style package
% writen by Liangjin Song on 20191224
\ProvidesPackage{code}
% add package
\usepackage{fontspec}
\usepackage{color,xcolor}
\usepackage{listings}
% define color
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codemauve}{rgb}{0.58,0,0.82}
\definecolor{codemauve}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
% code style
\lstset{%
backgroundcolor=\color{backcolour}, % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
basicstyle=\scriptsize\fontspec{Monaco}, % the size of the fonts that are used for the code
breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
breaklines=true, % sets automatic line breaking
captionpos=t, % sets the caption-position to bottom
columns=fullflexible,
commentstyle=\color{codegreen}\fontspec{Monaco}, % comment style
extendedchars=true, % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
keepspaces=true, % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue}\fontspec{Monaco}, % keyword style
% morekeywords={*,...}, % if you want to add more keywords to the set
numbers=left, % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt, % how far the line-numbers are from the code
numberstyle=\tiny\color{codegray}, % the style that is used for the line-numbers
showspaces=false, % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false, % underline spaces within strings only
showtabs=false, % show tabs within strings adding particular underscores
stepnumber=1, % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{codemauve}\fontspec{Monaco}, % string literal style
tabsize=4 % sets default tabsize to 4 spaces
}
该宏包使用的是Monaco字体,Linux和Windows在使用前需安装这个字体。
Latex中插入代码有两种方式
- 直接在tex文件中输入代码
\documentclass{article}
\usepackage{ctex}
\usepackage{code}
\begin{document}
\begin{lstlisting}[language=C++]
#include <iostream>
using namespace std;
int main(){
cout << "Hello world!" << endl;
}
\end{lstlisting}
\end{document}
- 从源文件中读取代码
\documentclass{article}
\usepackage{ctex}
\usepackage{code}
\begin{document}
\lstinputlisting[language=C++, title=test.cpp]{test.cpp} % 从test.cpp源文件中读取代码
\end{document}