Проблемы на границах страницы при попытке выделить `\lstinline`

Проблемы на границах страницы при попытке выделить `\lstinline`

Я пробовал код, указанный вЦветной фон в строковых списках, что на самом деле то же самое, что и вКак переопределить \lstinline, чтобы автоматически выделять или рисовать рамки вокруг всех встроенных фрагментов кода?, и я столкнулся со следующей проблемой.

Когда абзац, в котором появляется, \lstinlineразрывается между страницами, выделение переходит на неправильную страницу (не всегда). Это также происходит, даже если абзац не разрывается, когда латексные сноски или плавающий механизм вмешиваются и отправляют этот абзац на следующую страницу.

Следующий MWE показывает обе проблемы. Это тот же код, что и в цитируемых ответах, с некоторым дополнительным текстом перед примером, который вызывает проблему в первом случае (разрыв страницы в абзаце). Вы можете раскомментировать строку со сноской, рядом \begin{document}, чтобы увидеть также вторую проблему (весь абзац переходит на следующую страницу, но выделение остается на первой странице).

\documentclass[a4paper]{article}
\usepackage{etoolbox}
\usepackage{atbegshi,ifthen,listings,tikz}
\usepackage{lipsum}

% change this to customize the appearance of the highlight
\tikzstyle{highlighter} = [
  yellow,% set the color for inline listings here.
  line width = \baselineskip,
]

% enable these two lines for a more human-looking highlight
%\usetikzlibrary{decorations.pathmorphing}
%\tikzstyle{highlighter} += [decorate, decoration = random steps]

% implementation of the core highlighting logic; do not change!
\newcounter{highlight}[page]
\newcommand{\tikzhighlightanchor}[1]{\ensuremath{\vcenter{\hbox{\tikz[remember picture, overlay]{\coordinate (#1 highlight \arabic{highlight});}}}}}
\newcommand{\bh}[0]{\stepcounter{highlight}\tikzhighlightanchor{begin}}
\newcommand{\eh}[0]{\tikzhighlightanchor{end}}
\AtBeginShipout{\AtBeginShipoutUpperLeft{\ifthenelse{\value{highlight} > 0}{\tikz[remember picture, overlay]{\foreach \stroke in {1,...,\arabic{highlight}} \draw[highlighter] (begin highlight \stroke) -- (end highlight \stroke);}}{}}}
%--------------------------


\makeatletter %   Redefine macros from listings package:
\newtoggle{@InInlineListing}%
\togglefalse{@InInlineListing}%

\renewcommand\lstinline[1][]{%
    \leavevmode\bgroup\toggletrue{@InInlineListing}\bh % \hbox\bgroup --> \bgroup
      \def\lst@boxpos{b}%
      \lsthk@PreSet\lstset{flexiblecolumns,#1}%
      \lsthk@TextStyle
      \@ifnextchar\bgroup{\afterassignment\lst@InlineG \let\@let@token}%
                         \lstinline@}%

\def\lst@LeaveAllModes{%
    \ifnum\lst@mode=\lst@nomode
        \expandafter\lsthk@EndGroup\iftoggle{@InInlineListing}{\eh{}}{}%
    \else
        \expandafter\egroup\expandafter\lst@LeaveAllModes
    \fi%
    }
\makeatother

\lstset{backgroundcolor=\color{green!10}}%

\begin{document}
\lipsum[1-5]
% Foo\footnote{\lipsum[6]}

This is a somewhat large paragraph which latex perhaps will break among two
pages. Hopefully this will show the intended problem, that is, that the
highligthed yellow box is shown in the page in which the paragraph started,
instead of the page in which the code actually landed. Some more sentences to
fill the required space will do. Blah, blah, lorem ipsum or whatever.
This is a test where \lstinline{A=1} should have a yellow background.

This, on the other hand, actually works:
  \begin{lstlisting}[backgroundcolor=\color{green}]
    A = 1
  \end{lstlisting}
\end{document}

Это результат (после двойной компиляции). Желтый квадрат рядом с "ipsum" должен быть на A=1встроенном коде второй страницы.

Первая страницаВторая страница

Можно ли это исправить?

решение1

Я могу предложить решение, основанное на tcolorbox version 2.80 (2014/03/31)выпущенном только сегодня, где \lstinlineобертывание обеспечивается с помощью xparse. Вместо использования нового макроса \RenewTotalTCBoxиз версии 2.80вы также можете использовать некоторые вариации моего ответа наКак создать поле ввода с помощью \newtcbinputlisting?с версией 2.72.

Чтобы адаптировать ваш пример, я выбрал специальный символ °для разграничения \lstline:

\documentclass[a4paper]{article}
\usepackage{etoolbox}
\usepackage{atbegshi,ifthen,listings,tikz}
\usepackage{lipsum}
\usepackage[most]{tcolorbox}% version 2.80 (2014/03/31)

\let\lstinlineoriginal=\lstinline

% change this to customize the appearance of the highlight
\tikzstyle{highlighter} = [
  yellow,% set the color for inline listings here.
  line width = \baselineskip,
]

\RenewTotalTCBox{\lstinline}{ O{} v }
  {blank,boxsep=1pt,nobeforeafter,tcbox raise base,interior style={fill,highlighter}}
  {\lstinlineoriginal[flexiblecolumns,#1]°#2°}

\lstset{backgroundcolor=\color{green!10}}%

\begin{document}
\lipsum[1-5]
% Foo\footnote{\lipsum[6]}

This is a somewhat large paragraph which latex perhaps will break among two
pages. Hopefully this will show the intended problem, that is, that the
highligthed yellow box is shown in the page in which the paragraph started,
instead of the page in which the code actually landed. Some more sentences to
fill the required space will do. Blah, blah, lorem ipsum or whatever.
This is a test where \lstinline{A=1} should have a yellow background.

This, on the other hand, actually works:
  \begin{lstlisting}[backgroundcolor=\color{green}]
    A = 1
  \end{lstlisting}
\end{document}

введите описание изображения здесь введите описание изображения здесь

Связанный контент