![如果将 courier 字体更改为其他字体,则左侧规则会受到影响](https://linux22.com/image/378285/%E5%A6%82%E6%9E%9C%E5%B0%86%20courier%20%E5%AD%97%E4%BD%93%E6%9B%B4%E6%94%B9%E4%B8%BA%E5%85%B6%E4%BB%96%E5%AD%97%E4%BD%93%EF%BC%8C%E5%88%99%E5%B7%A6%E4%BE%A7%E8%A7%84%E5%88%99%E4%BC%9A%E5%8F%97%E5%88%B0%E5%BD%B1%E5%93%8D.png)
我的代码如下:
\documentclass{book}
\usepackage{fontspec}
\defaultfontfeatures{Ligatures=TeX}
\usepackage{unicode-math}%
\setmonofont[Path = ./Fonts/ ,
UprightFont= Iosevka ,]{Iosevka}
\usepackage{textcomp,xcolor,MNsymbol}
\usepackage{listings}
\lstdefinestyle{mypyscriptstyle}{%
upquote=true,
language=Python,
% Basic style
basicstyle=\ttfamily\small,
commentstyle=\tt\footnotesize, %\rmfamily
stringstyle=\ttfamily\slshape\small,%amd remove \slshape, add upquote=true
% Line numbers
%numbers=left,
%numberstyle=\footnotesize,
%numbersep=1em,
%stepnumber=3,
% Margins and box
framextopmargin=2em,
framexbottommargin=2em,
frame=l,
backgroundcolor=\color{black!10},
xleftmargin=1em,
tabsize=4,
% Show spaces
showspaces=false,
showtabs=false,
showstringspaces=false,
columns=fullflexible,
breaklines=true,
postbreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rcurvearrowse\space}},
% Comments
morecomment=[s]{"""}{"""},
morecomment=[s]{'''}{'''},
morecomment=[l]{\#},
% Keywords
keywordstyle=\bfseries,
keywords={},
sensitive=true,
string=[b]',
morestring=[b]",
escapechar={§},
alsoletter={_, .},
% Built-in
emphstyle=\color{black!15}\bfseries,
emph={assert, break, class, continue, def, del, elif, else, except, finally, for, global, help, in, lambda, not, or, pass, raise, return, try, while, with, yield, exec, Ellipsis, None, NotImplemented, ArithmeticError, AssertionError, AttributeError, EnvironmentError, EOFError, Exception, FloatingPointError, ImportError, IndentationError, IndexError, IOError, KeyboardInterrupt, KeyError, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, StandardError, StopIteration, SyntaxError, SystemError, SystemExit, TabError, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, ValueError, WindowsError, ZeroDivisionError, Warning, UserWarning, DeprecationWarning, PendingDeprecationWarning, SyntaxWarning, OverflowWarning, RuntimeWarning, FutureWarning, abs, any, bin, bool, callable, chr, classmethod, compile, complex, delattr, dict, dir, divmod, enumerate, eval, filter, float, format, frozenset, getattr, globals, hasattr, hash, hex, id, input, int, isinstance, issubclass, iter, len, list, locals, map, max, min, object, oct, open, ord, pow, property, range, repr, reversed, round, setattr, set, slice, sorted, staticmethod, str, sum, super, tuple, type, vars, zip, apply, basestring, buffer, cmp, coerce, execfile, file, intern, long, , reduce, reload, unichr, unicode, xrange, import, __import__, print, match, search, readline, rstrip, group, VERBOSE, finditer, findall,
join, upper, lower, replace, find, count, strip, split, append, copy, clear, index, pop, sort, reverse, get, items, keys, values, update, intersection, union, symmetric_difference, difference, issubset, issuperset, if, name, mode, encoding, write, writelines, close, as, seek, whos, deepcopy, start, end, dimension, shape, ndim, size, mean, std, sqrt, exp, array, zeros, ones, arange, reshape, random, loadtxt, re, who, from, imread, imshow, loc, iloc, drop, median, hist, email, esearch, efetch, parse, description, id, seq, alignments, read }
}
\lstnewenvironment{testermcode}{\lstset{style=mypyscriptstyle}}{}
\begin{document}
\begin{testermcode}
In [1]: 2 + 2 # addition of integers
Out[1]: 4
In [2]: 2 * 2 # multiplication
Out[2]: 4
In [3]: 3 / 2 # division (returns floating-point real value)
Out[3]: 1.5
In [4]: 3 // 2 # integer division
Out[4]: 1
In [5]: 2 > 3 # logical operators return a Boolean value
Out[5]: False
In [6]: 2 == 2 # equals
Out[6]: True
In [7]: 2 != 2 # is different
Out[7]: False
In [8]: "my string" # quotes define strings
Out[8]: 'my string'
\end{testermcode}
\end{document}
输出如下:
我之前发的帖子也遇到同样的问题如果我们使用其他字体而不是 courier,则会产生不必要的空白
我已经尝试了 Ulrike 的建议,但我得到了框架框,但我只需要左侧规则,
请建议...
答案1
我已经解决了我的问题,下面是更新后的代码:
\documentclass{book}
\usepackage{fontspec}
\defaultfontfeatures{Ligatures=TeX}
\usepackage{unicode-math}%
\setmonofont[Path = ./Fonts/ ,
UprightFont= Iosevka ,]{Iosevka}
\usepackage{textcomp,xcolor,MNsymbol}
\usepackage{listings}
\lstdefinestyle{mypyscriptstyle}{%
upquote=true,
language=Python,
% Basic style
basicstyle=\ttfamily\small,
commentstyle=\tt\footnotesize, %\rmfamily
stringstyle=\ttfamily\slshape\small,%amd remove \slshape, add upquote=true
% Line numbers
%numbers=left,
%numberstyle=\footnotesize,
%numbersep=1em,
%stepnumber=3,
% Margins and box
%framextopmargin=2em,
%framexbottommargin=2em,
%frame=l,
%backgroundcolor=\color{black!10},
%xleftmargin=1em,
%tabsize=4,
% Show spaces
showspaces=false,
showtabs=false,
showstringspaces=false,
columns=fullflexible,
breaklines=true,
postbreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rcurvearrowse\space}},
% Comments
morecomment=[s]{"""}{"""},
morecomment=[s]{'''}{'''},
morecomment=[l]{\#},
% Keywords
keywordstyle=\bfseries,
keywords={},
sensitive=true,
string=[b]',
morestring=[b]",
escapechar={§},
alsoletter={_, .},
% Built-in
emphstyle=\color{black!15}\bfseries,
emph={assert, break, class, continue, def, del, elif, else, except, finally, for, global, help, in, lambda, not, or, pass, raise, return, try, while, with, yield, exec, Ellipsis, None, NotImplemented, ArithmeticError, AssertionError, AttributeError, EnvironmentError, EOFError, Exception, FloatingPointError, ImportError, IndentationError, IndexError, IOError, KeyboardInterrupt, KeyError, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, StandardError, StopIteration, SyntaxError, SystemError, SystemExit, TabError, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, ValueError, WindowsError, ZeroDivisionError, Warning, UserWarning, DeprecationWarning, PendingDeprecationWarning, SyntaxWarning, OverflowWarning, RuntimeWarning, FutureWarning, abs, any, bin, bool, callable, chr, classmethod, compile, complex, delattr, dict, dir, divmod, enumerate, eval, filter, float, format, frozenset, getattr, globals, hasattr, hash, hex, id, input, int, isinstance, issubclass, iter, len, list, locals, map, max, min, object, oct, open, ord, pow, property, range, repr, reversed, round, setattr, set, slice, sorted, staticmethod, str, sum, super, tuple, type, vars, zip, apply, basestring, buffer, cmp, coerce, execfile, file, intern, long, , reduce, reload, unichr, unicode, xrange, import, __import__, print, match, search, readline, rstrip, group, VERBOSE, finditer, findall,
join, upper, lower, replace, find, count, strip, split, append, copy, clear, index, pop, sort, reverse, get, items, keys, values, update, intersection, union, symmetric_difference, difference, issubset, issuperset, if, name, mode, encoding, write, writelines, close, as, seek, whos, deepcopy, start, end, dimension, shape, ndim, size, mean, std, sqrt, exp, array, zeros, ones, arange, reshape, random, loadtxt, re, who, from, imread, imshow, loc, iloc, drop, median, hist, email, esearch, efetch, parse, description, id, seq, alignments, read }
}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}
%\lstnewenvironment{testermcode}{\lstset{style=mypyscriptstyle}}{}
\newtcblisting{testermcode}{colback=black!16,left=4pt,right=4pt,arc=0pt,leftrule=2pt,rightrule=0pt,toprule=0pt,bottomrule=0pt,listing
options={style=mypyscriptstyle,xleftmargin=4pt},listing only }
\begin{document}
\begin{testermcode}
In [1]: 2 + 2 # addition of integers
Out[1]: 4
In [2]: 2 * 2 # multiplication
Out[2]: 4
In [3]: 3 / 2 # division (returns floating-point real value)
Out[3]: 1.5
In [4]: 3 // 2 # integer division
Out[4]: 1
In [5]: 2 > 3 # logical operators return a Boolean value
Out[5]: False
In [6]: 2 == 2 # equals
Out[6]: True
In [7]: 2 != 2 # is different
Out[7]: False
In [8]: "my string" # quotes define strings
Out[8]: 'my string'
\end{testermcode}
\end{document}