VS Code as LaTeX editor



Welcome to the most popular page on this blog. No joke, this one is a perennial favourite. I have not updated the content overmuch recently; your feedback is welcome if something is outdated; and you will help hundreds of people.

Texlab

The disruptive approach is texlab for vs code.

A Visual Studio Code extension that provides rich editing support for the LaTeX typesetting system powered by the TexLab language server. It aims to produce high quality code completion results by indexing your used packages as you type.

Recommended matching syntax highlighter: latex-syntax.

Neat feature: supported configuration uses the modernised and streamlined tectonic distribution instead of classic LaTeX.

This extensions makes some radical design choices in the name of simplicity and elegance, which hopefully means that the experience will be smooth. On the other hand it probably means that some edge cases and misfeatures in classic TeX sill not be supported. For an extension which can handle those, see below.

ext install efoerster.texlab

The build/preview workflow is janky; you need to start your own previewer then maintain sync, which requires custom setup depending on which unsatisfactory PDF viewer you use. Which means different settings on each OS. After that… TBH I cannot work out how to invoke the build step from inside VS code. Or invoke the PDF viewer. I cannot work out how to invoke the PDF viewer except via synctex. This means that, unintuitively, the viewer is invoked by the command LaTeX: Forward Search.

For GNOME desktops, evince-synctex works.

{
  "texlab.forwardSearch.executable": "evince-synctex",
  "texlab.forwardSearch.args": ["-f", "%l", "%p", "\"code -g %f:%l\""]
}

Installation by one of the following:

pip3 install --user https://github.com/efoerster/evince-synctex/archive/master.zip
pipx install https://github.com/efoerster/evince-synctex/archive/master.zip

On macOS we need Skim apparently. Skim must be in Check for file changes mode (see app settings).

{
  "texlab.forwardSearch.executable": "/Applications/Skim.app/Contents/SharedSupport/displayline",
  "texlab.forwardSearch.args": ["%l", "%p", "%f"]
}

If you work on multiple OSes, you need to disable sync for these machine-specific settings, or it will constantly be running evince on macos or some such.

LaTeX-Workshop

LaTeX-Workshop has been the most common VS Code LaTeX editing extension. Originally I was skeptical, despite having many features, because it ended up being confusing when things went wrong (Where WAS that syntax error?) which meant it was not good at its main job because syntactically invalid is what the document usually is.

However, the new version is much better; I just need to make sure that little TeX sidebar is active and everything becomes apparent. Some things are still fiddly, but it provides nearly as good a LaTeX preview experience as, say, TeXShop, and greatly superior text editing and integration with the rest of my workflow because VS Code is rather good. As such, it is what I use, because VS Code is better at editing non-LaTeX than TeXShop is and otherwise I would be switching constantly and never getting the keyboard shortcuts right.

VS Code supposedly can preview individual equations via javascript. This does not work for me on substantial documents, and I cannot work out why, because there is no error dumped anywhere I can see it. For simple equations in simple documents it often works; Javascript mathematics are blind to the loaded packages however, so we need to set that globally: Only simple equations in trivial test documents have preview for me.

"latex-workshop.hover.preview.mathjax.extensions": [
    "boldsymbol"
]

Snippets

LaTeX workshop supports smart snippets with autocomplete.

Reproduced here for my offline reference are the most useful ones.

PrefixEnvironment name
BEQequation
BSEQequation*
BALalign
BSALalign*
BITitemize
BENenumerate
BSPLsplit
BCAScases
BFRframe
BFIfigure
PrefixSectioning level
SPApart
SCHchapter
SSEsection
SSSsubsection
SS2subsubsection
SPGparagraph
SSPsubparagraph
PrefixCommand
@(\left( $1 \right)
@{\left\{ $1 \right\}
@[\left[ $1 \right]
___{$1}
**^{$1}
@8\infty
@6\partial
@/\frac{$1}{$2}
@%\frac{$1}{$2}
@_\bar{$1}
@I\int_{$1}^{$2}
@||
@\\setminus
@,\nonumber

Build recipes

Building using something modern or fancy? The default build workflow is some pdflatex+BibTeX system that is ok but outdated. I would prefer a simpler more modern workflow that supports e.g. XeTeX. Out of the box, neither XeTeX or latexmk were default workflows for me. There are two ways to do set these up.

Firstly, the old school way that the developers of LaTeX workshop seem to dislike, but which was far and away the easiest for me: Use the Latex Workshop-style TeX magic This looks like, e.g.

% !TEX program = latexmk
% !TEX options = -synctex=1 -file-line-error -halt-on-error -xelatex -outdir="%OUTDIR%" "%DOC%"

I put that at the start of the master document and things behave as expected. Good. For this particular one to actually be a useful build method, one would want to disable auto-clean (a.k.a. delete everything and rebuild from scratch all the time) so that latexmk can be smart about rebuilds. The price one pays for this is needing to manually clean up the detritus from time to time, which looks like the following setting:

"latex-workshop.latex.autoBuild.cleanAndRetry.enabled": false,

The developer-preferred way of configuring the build is difficult, verbose and error-prone but supposedly ineffably better. In this one, we make new “recipes”. The result is 😴.

    "latex-workshop.latex.recipes": [
        {
            "name": "latexmk 🔃",
            "tools": [
                "latexmk"
            ]
        },
        {
            "name": "xelatexmk 🔃",
            "tools": [
                "xelatexmk"
            ]
        },
        {
            "name": "platexmk 🔃",
            "tools": [
                "platexmk"
            ]
        },
        {
            "name": "pdflatex ➞ bibtex ➞ pdflatex`×2",
            "tools": [
                "pdflatex",
                "bibtex",
                "pdflatex",
                "pdflatex"
            ]
        },
        {
            "name": "xelatex ➞ biber ➞ xelatex",
            "tools": [
                "xelatex",
                "biber",
                "xelatex"
            ]
        }
    ],
    "latex-workshop.latex.tools": [
        {
            "name": "latexmk",
            "command": "latexmk",
            "args": [
                "-synctex=1",
                "-file-line-error",
                "-outdir=%OUTDIR%",
                "%DOC%"
            ],
            "env": {}
        },
        {
            "name": "platexmk",
            "command": "latexmk",
            "args": [
                "-synctex=1",
                "-file-line-error",
                "-pdf",
                "-outdir=%OUTDIR%",
                "%DOC%"
            ],
            "env": {}
        },
        {
            "name": "xelatexmk",
            "command": "latexmk",
            "args": [
                "-synctex=1",
                "-file-line-error",
                "-xelatex",
                "-outdir=%OUTDIR%",
                "-interaction=nonstopmode",
                "-halt-on-error",
                "%DOC%"
            ],
            "env": {}
        },
        {
            "name": "pdflatex",
            "command": "pdflatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-halt-on-error",
                "-file-line-error",
                "%DOC%"
            ],
            "env": {}
        },
        {
            "name": "xelatex",
            "command": "xelatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-halt-on-error",
                "-file-line-error",
                "%DOC%"
            ],
            "env": {}
        },
        {
            "name": "bibtex",
            "command": "bibtex",
            "args": [
                "%DOCFILE%"
            ],
            "env": {}
        },
        {
            "name": "biber",
            "command": "biber",
            "args": [
                "%DOCFILE%"
            ],
            "env": {}
        }
    ]

For the disruptive new tectonic build system, try this

"latex-workshop.latex.tools": [
    {
        "name": "tectonic",
        "command": "tectonic",
        "args": [ "%DOC%"  ],
        "env": {}
    }
],
"latex-workshop.latex.recipes": [
    {
        "name": "tectonic",
        "tools": [
            "tectonic"
        ]
    }
]

Those are all the build workflows I have needed in my life so far.

SyncTeX

SyncTeX makes working out what I am typing somewhat easier, by connecting the cursor location in the source code to the viewing location in the pdf (and, on some systems, vice versa). The built-in implementation is OK; we are somewhat hamstrung because everything is constrained to a single window by VS Code. (Although see VS Code’s dual window hack). External PDF viewers are not officially supported but more-or-less work for me and ideal for dual monitor setup.

Minuses:

  • Documentation is perfunctory.
  • Sync works in AFAICT one direction only — I can sync from VS Code to the PDF viewer, but not the reverse.

Since they are unsupported, one needs to guess the config to make them go. A good example of reverse engineering the config for kubuntu’s PDF viewer okular is given by Heiko/@miteron.

{
    "latex-workshop.view.pdf.viewer": "external",
    // @sync host=work-pc
    "latex-workshop.view.pdf.external.viewer.command": "okular",
    // @sync host=work-pc
    "latex-workshop.view.pdf.external.viewer.args": [
            "--unique",
            "%PDF%"
    ],
    // @sync host=work-pc
    "latex-workshop.view.pdf.external.synctex.command": "okular",
    // @sync host=work-pc
    "latex-workshop.view.pdf.external.synctex.args": [
        "--unique",
        "%PDF%#src:%LINE%%TEX%"
    ],
}

For GNOME doc viewer evince things are more complicated. Specifically, I needed a bridging script and special config:

{
    // @sync host=home-pc
    "latex-workshop.view.pdf.external.viewer.command": "evince2",
    // @sync host=home-pc
    "latex-workshop.view.pdf.external.viewer.args": [
        "%PDF%"
    ],
    // @sync host=home-pc
    "latex-workshop.view.pdf.external.synctex.command": "evince_forward_search",
    // @sync host=home-pc
    "latex-workshop.view.pdf.external.synctex.args": [
        "%PDF%",
        "%LINE%",
        "%TEX%"
    ],
}

Gotchas

Gotcha: If there are weird “provider errors” in the vscode exthost log, the problem might be that latexindent must be installed, and possibly it was not for me because I installed a minimalist TeX distribution.

tlmgr install latexindent

If I want to switch TeX installations, I can do so by environment variables, so I whack the following in my settings.json:

  {
    "name": "latexmk",
    "command": "latexmk",
    "args": [
      "-synctex=1",
      "-interaction=nonstopmode",
      "-file-line-error",
      "-pdf",
      "-outdir=%OUTDIR%",
      "%DOC%"
    ],
    "env": {"TEXMFHOME": "c:/texlive/2019"}
  }

Spell checking

Contra my prior VS Code spell checking advice, SpellRight is unsupported.

If I persevere in using spellright, the following exclusions make things tidier:

    "spellright.ignoreRegExpsByClass": {
        "latex": [
            "/\\\\begin\\\\{{equation,align}\\\\}(.*?)\\\\end\\\\{{equation,align}\\\\}/mg",
            "/\\\\{autoref,autocites?,cites?}\\\\{(.*?)\\\\}/g",
        ],
    },

But probably better is to disable spellright for .tex files in favour of cspell instead. Supposedly LanguageTool is good for more diverse languages, but I have not tried it.

Alternatively, here is a new entrant in the field:

LTEX:

LTEX — Grammar/Spell Checker Using LanguageTool with Support for LATEX, Markdown, and Others

LTEX provides offline grammar checking of various markup languages using LanguageTool (LT). LTEX can be used standalone as a command-line tool, as a language server using the Language Server Protocol (LSP), or directly in various editors using extensions.

LTEX currently supports BibTEX, ConTEXt, LATEX, Markdown, Org, reStructuredText, R Sweave, and XHTML documents.

The difference to regular spell checkers is that LTEX not only detects spelling errors, but also many grammar and stylistic errors…

A classic use case of LTEX is checking scientific LATEX papers, but why not check your next blog post, book chapter, or long e-mail before you send it to someone else?


No comments yet. Why not leave one?

GitHub-flavored Markdown & a sane subset of HTML is supported.