4

I want to make a gray box with some code inside but it should already appear a centered tilde followed by a dollar sign. Or how can I use a command inside the environment to obtain certain text like \newcommand{\prompt}{user@linux:\~\$}

\documentclass{book}
\usepackage{fontspec,listings,color}
\definecolor{verbgray}{gray}{0.9}
\newfontfamily\ubuntumono{Ubuntu Mono}
\lstnewenvironment{sh}{
  \lstset{backgroundcolor=\color{verbgray},
  frame=single,
  framerule=1pt,
  basicstyle=\ubuntumono,
  columns=fullflexible}}{}
\begin{document}
\begin{sh}
user@linux:(centered tilde)$
\end{sh}
\end{document}

This must be built with XeLaTeX for the fontspec package.

1 Answers1

4

Using the etoolbox package you can patch \lst@NewLine similar to my example below. (I removed the dependency on fontspec for my tests…):

\documentclass{article}

\usepackage{listings,xcolor,etoolbox}
\definecolor{verbgray}{gray}{0.9}

\newcommand*\prompt{}% empty default
\lstnewenvironment{sh}{%
  % redefine bash prompt:
  \renewcommand*\prompt{user@linux:\textasciitilde>\space}%
  \lstset{backgroundcolor=\color{verbgray},
    frame=single,
    framerule=1pt,
    basicstyle=\ttfamily,
    columns=fullflexible
  }%
}{}

% patch \lst@NewLine:
\makeatletter
\patchcmd\lst@NewLine
  {\hbox{}}% search
  {\hbox{}\prompt}% replace
  {}% success
  {}% failure
\makeatother

\begin{document}

\begin{sh}
foo

baz
\end{sh}

% other listings behave as they should:   
\begin{lstlisting}
foo
\end{lstlisting}

\end{document}

enter image description here

listings actually has a hook OnNewLine but code added with \lst@AddToHook{OnNewLine}{<code>} seems to be placed before the \par\noindent in \lst@NewLine which means its contents appear at the end of the preceding line which may or may not be a bug (it looks like one to me…).

cgnieder
  • 66,645