本文展示如何利用minted来显示代码。
① 代码准备
使用minted包,还是需要额外引用:
\usepackage{minted}
插入的代码如上所示,编译报错:
You must invoke LaTeX with the -shell-escape flag
② 添加-shell-escape编译参数
通过查阅资料,自己尝试在settings.json中的添加这个编译参数。
// Latex workshop
"latex-workshop.latex.tools": [
{
"name": "latexmk",
"command": "latexmk",
"args": [
"-shell-escape",//添加参数
...
]
},
{
"name": "xelatex",
"command": "xelatex",
"args": [
"-shell-escape", //添加参数
...
]
},
{
"name": "pdflatex",
"command": "pdflatex",
"args": [
"-shell-escape",//添加参数
...
]
},
再次编译,仍然报错:
You must have `pygmentize' installed to use this package.
③ 安装Pygments
py开头的,一看就知道跟python有关。
因此,首先需要安装python,我的win10之前就已经安装过python3.7了。
python的安装方法请自己百度,网上应该很多的,而且在windows上安装python完全就是next、next,最后系统环境别人都可以自动配好。
以管理员身份运行命令提示符,输入以下命令安装Pygments:
pip install Pygments
但是在编译.tex的时候报错:
查找路径:
C:\Users\Liujiawang.conda\envs\env_torch\Scripts\pygmentize.exe
将其添加到环境变量中:
在cmd中输入如下命令,如果可以显示版本则说明成功:
修改完配置后记得重启电脑。
\usepackage{minted}
\begin{minted}[linenos,
numbersep=5pt,
frame=lines]{python}
def preprocess_image(batch_inputs):
pixel_mean = [103.530, 116.280, 123.675]
pixel_std = (57.375, 57.120, 58.395)
pixel_mean = torch.tensor(pixel_mean).view(-1, 1, 1).cuda()
pixel_std = torch.tensor(pixel_std).view(-1, 1, 1).cuda()
list_img=[]
for i in range(batch_inputs.shape[0]):
list_img.append(batch_inputs[i])
images = [(x - pixel_mean) / pixel_std for x in list_img]
images=[x.unsqueeze(0) for x in images]
return torch.cat(images,0)
\end{minted}
最终的显示效果如下:
在每一行会出现I^^的字符。经过查阅资料,需要添加编译参数类似如下:
上述是命令行参数,那么在vscode中修改方法同样是settings.json中的添加这个编译参数。具体如下
正文代码:
\begin{minted}[linenos,
numbersep=5pt,
frame=lines,
framesep=2mm,
rulecolor=purple!50!black]{python}
def preprocess_image(batch_inputs):
pixel_mean = [103.530, 116.280, 123.675]
pixel_std = (57.375, 57.120, 58.395)
pixel_mean = torch.tensor(pixel_mean).view(-1, 1, 1).cuda()
pixel_std = torch.tensor(pixel_std).view(-1, 1, 1).cuda()
list_img=[]
for i in range(batch_inputs.shape[0]):
list_img.append(batch_inputs[i])
images = [(x - pixel_mean) / pixel_std for x in list_img]
images=[x.unsqueeze(0) for x in images]
return torch.cat(images,0)
\end{minted}
对应的效果:
[1]:https://superuser.com/questions/816340/minted-cannot-find-pygmentize-in-texstudio-on-windows-7
[2]:https://blog.csdn.net/u014454538/article/details/104283898
[3]:https://tex.stackexchange.com/questions/264461/xelatex-minted-code-block-represents-tabs-as-i