如何像 StackOverflow 或 Github 一样显示代码列表?

如何像 StackOverflow 或 Github 一样显示代码列表?

我每天都会查看 StackOverflow 代码或 Github readmes,我真的很喜欢代码的显示方式。

我想在乳胶中实现类似的结果,即在浅灰色框内显示等宽文本,该文本可以跨越多行。

我怎样才能实现这个目标?

迄今为止:此解决方案非常适合使用糖语法显示内联文本,但我无法将其扩展到多行而不会得到丑陋的结果,如下面的最小工作示例中所示。

% !TeX program = lualatex
\documentclass{article}
\usepackage{xcolor,listings,realboxes,fancyvrb} % fancyvrb for '\Verb' macro
\definecolor{mygray}{rgb}{0.8,0.8,0.8}
\lstset{basicstyle=\ttfamily, breaklines = true, backgroundcolor=\color{mygray}}
\usepackage[doublespacing]{setspace} % just for this example

\usepackage{luacode} % for 'luacode' environment
\begin{luacode}
-- the following code employs Lua's powerful "string.gsub" function
function color_lstinline ( s )
   s = string.gsub ( s , "\\lstinline%b||", "\\Colorbox{mygray}{%0}" ) 
   s = string.gsub ( s , "\\[vV]erb%b||", "\\Colorbox{mygray}{%0}" ) 
   return s
end
\end{luacode}
%% Define 2 LaTeX macros to switch operation of Lua function on and off
\newcommand{\ColorLstinlineOn}{\directlua{
   luatexbase.add_to_callback ( "process_input_buffer" , 
   color_lstinline, "color_lstinline" )}}
\newcommand{\ColorLstinlineOff}{\directlua{
   luatexbase.remove_from_callback ( "process_input_buffer" , 
   "color_lstinline" )}}
\AtBeginDocument{\ColorLstinlineOn} % Default: activate the Lua function 

\begin{document}
\obeylines % just for this example
This is my \lstinline|amazing| code.
This is my \verb|@#$%^&*()\%| code.
This is my \Verb!amazing! code. 
This is my \Colorbox{mygray}{\lstinline!amazing!} code.

This is part of the code I used for displaying this document:
\begin{lstlisting}
\begin{luacode}
-- the following code employs Lua's powerful "string.gsub" function
function color_lstinline ( s )
   s = string.gsub ( s , "\\lstinline%b||", "\\Colorbox{mygray}{%0}" ) 
   s = string.gsub ( s , "\\[vV]erb%b||", "\\Colorbox{mygray}{%0}" ) 
   return s
end
\end{luacode}
\end{lstlisting}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% TeX-engine: luatex
%%% End:

输出:

在此处输入图片描述

相关内容