1

I'm using TeXstudio for pretty much all my LaTeX needs.

I sometimes have to include small code snippets in a document where employing the listings package would be overkill. Since I'd like for these to have a colored background (which is not supported by the standard verbatim environment of course), I'm defining a new environment using the tcolorbox and fancyvrb packages, as suggested by @egreg in this excellent answer:

\usepackage{fancyvrb}
\usepackage{tcolorbox}
% ...
\newenvironment{BGVerbatim}
 {\VerbatimEnvironment
  \begin{tcolorbox}[breakable, colback = Dandelion!10!white, spartan, frame hidden, boxrule = 0pt, left = 1ex]%
  \begin{Verbatim}}
 {\end{Verbatim}\end{tcolorbox}}

This works fine, but if you include e.g. R code that includes $ characters, TeXstudio's syntax highlighting gets confused, which is especially problematic in large documents where thousands of subsequent lines may get wrongly highlighted as if in math mode.

chsk
  • 3,667

1 Answers1

1

The solution for this is to define a custom syntax highlighting hints (.cwl) file for TeXstudio. The TeXstudio manual has more information about the format of these files; all that is needed here is the following:

\begin{BGVerbatim}#V
\end{BGVerbatim}#V

which declares the BGVerbatim environment to be of verbatim-type (#V).

This should be put into a filed called e.g. CUSTOM.cwl, which in turn should be placed in the appropriate user directory: %APPDATA%\texstudio\completion\user on Windows, .config/texstudio/completion/user on Linux and other Unix-like OSes (I presume this includes MacOS X).

Afterward, enable this syntax highlighting file by selecting Options > Configure TeXstudio ... and navigating to the Completion tab:

enter image description here

Click on OK; you may have to restart TeXstudio for your document to be correctly highlighted (I did).

The downside to this approach is that this highlighting will always be active even when the BGVerbatim environment is not defined in a document, but I do not consider this to be relevant in practice.

A more substantial downside is that this solution is specific to the computer the document is being edited on; if the document is shared, every computer used will have to be configured accordingly. Regrettably, there appears to be no way to embed TeXstudio syntax highlighting hints in .tex files themselves (using magic comments of some sort).

chsk
  • 3,667