LaTeX实战经验:如何插入程序代码

小咪咪 2022-07-16 03:13 186阅读 0赞

>> 点击此处查看 【 LaTeX实战经验:新手须知 】

插入程序代码

传统一点, \usepackage{listings}, 详情可以使用texdoc listings查看。

  1. \lstset{language=C}
  2. \begin{lstlisting}
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. cout<<"hello"<<endl;
  8. return 0;
  9. }
  10. \end{lstlisting}

对效果进行一些定制:

  1. \usepackage{ listings}
  2. \usepackage{ xcolor}
  3. \lstset{
  4. numbers=left,
  5. numberstyle= \tiny,
  6. keywordstyle= \color{ blue!70},
  7. commentstyle= \color{ red!50!green!50!blue!50},
  8. frame=shadowbox, % 阴影效果
  9. rulesepcolor= \color{ red!20!green!20!blue!20} ,
  10. escapeinside=``, % 英文分号中可写入中文
  11. xleftmargin=2em,xrightmargin=2em, aboveskip=1em,
  12. framexleftmargin=2em
  13. }

效果:

这里写图片描述

mac 定制代码字体

  1. %!TEX program = xelatex
  2. \documentclass{ article}
  3. \usepackage{ listings}
  4. \usepackage{ fontspec} % 定制字体
  5. \newfontfamily\menlo{ Menlo}
  6. \usepackage{ xcolor} % 定制颜色
  7. \definecolor{ mygreen}{ rgb}{ 0,0.6,0}
  8. \definecolor{ mygray}{ rgb}{ 0.5,0.5,0.5}
  9. \definecolor{ mymauve}{ rgb}{ 0.58,0,0.82}
  10. \lstset{ %
  11. backgroundcolor=\color{ white}, % choose the background color
  12. basicstyle=\footnotesize\ttfamily, % size of fonts used for the code
  13. columns=fullflexible,
  14. tabsize=4,
  15. breaklines=true, % automatic line breaking only at whitespace
  16. captionpos=b, % sets the caption-position to bottom
  17. commentstyle=\color{ mygreen}, % comment style
  18. escapeinside={ \%*}{ *)}, % if you want to add LaTeX within your code
  19. keywordstyle=\color{ blue}, % keyword style
  20. stringstyle=\color{ mymauve}\ttfamily, % string literal style
  21. frame=single,
  22. rulesepcolor=\color{ red!20!green!20!blue!20},
  23. % identifierstyle=\color{red},
  24. language=c++,
  25. }
  26. \begin{ document}
  27. \begin{ lstlisting}[language={ [ANSI]C},
  28. numbers=left,
  29. numberstyle=\tiny\menlo,
  30. basicstyle=\small\menlo]
  31. #include <stdio.h>
  32. #include <stdbool.h>
  33. #include <ctype.h>
  34. #define SIZE 26
  35. int
  36. main (int argc, char *argv[])
  37. {
  38. int array[SIZE];
  39. int i;
  40. char c;
  41. for (i = 0; i < SIZE; i++)
  42. array[i] = 0;
  43. while ((c = getchar ()) != EOF)
  44. {
  45. if (isupper (c))
  46. {
  47. array[c - 'A']++;
  48. }
  49. }
  50. for (i = 0; i < 26; i++)
  51. printf ("%c:%5d\n", (char) ('A' + i), array[i]);
  52. return 0;
  53. }
  54. \end{ lstlisting}
  55. \end{ document}
  56. % Local Variables:
  57. % TeX-engine: xetex
  58. % End:

效果图:
这里写图片描述

参考:https://www.zhihu.com/question/30957600

发表评论

表情:
评论列表 (有 0 条评论,186人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LaTeX 实战经验:新手须知

    前言: 以下内容皆为一个“用家”的经验之谈。资历尚浅,能力有限,您如果有更好的方案选择,期待您的分享!每个功能或是实现的每个效果,在这里可能只是一个起点,更多内容的实现想