Sublime Forum

Lightweight workflow to edit/preview latex docs in ST3


Usually I’ve always edited all my latex documents with WYSIWYG tools but I’d really love to switch to ST3.

After googling for a bit as well as checking I’ve seen the smartest move would be using this package called LatexTools. Unfortunately I haven’t been able to make it work yet (already opened an issue here).

That said and assuming I’ve already got both miktex/sumatra in %path% and updated, could you please recommend me a lightweight workflow to edit & preview my docs in “realtime”? If not realtime, one lightweight sublime-build to do the job would be also really convenient.

Thanks in advance :slight_smile:



I haven’t touch LaTeX for a long time but I did setup the env once with LatextTools.

It seems that you didn’t have texlive installed?
I was using the “Downloading one huge ISO file” way and probably installed it with the default settings.

Variable   Value
--------   -----

Program      Location                                          Status     Version
-------      --------                                          ------     -------
sublime      C:\Program Files\Sublime Text 3\sublime_text.exe  available  Sublime Text Build 3211
latexmk      C:\texlive\2019\bin\win32\latexmk.exe             available  Latexmk, John Collins, 17 March 2019. Version 4.63b
pdflatex     C:\texlive\2019\bin\win32\pdflatex.exe            available  pdfTeX 3.14159265-2.6-1.40.20 (TeX Live 2019/W32TeX)
xelatex      C:\texlive\2019\bin\win32\xelatex.exe             available  XeTeX 3.14159265-2.6-0.999991 (TeX Live 2019/W32TeX)
lualatex     C:\texlive\2019\bin\win32\lualatex.exe            available  This is LuaTeX, Version 1.10.0 (TeX Live 2019/W32TeX)
biber        C:\texlive\2019\bin\win32\biber.exe               available  biber version: 2.12
bibtex       C:\texlive\2019\bin\win32\bibtex.exe              available  BibTeX 0.99d (TeX Live 2019/W32TeX)
bibtex8      C:\texlive\2019\bin\win32\bibtex8.exe             available  This is 8-bit Big BibTeX version 0.99d
kpsewhich    C:\texlive\2019\bin\win32\kpsewhich.exe           available  kpathsea version 6.3.1
magick                                                         missing    unavailable
ghostscript  C:\texlive\2019\tlpkg\tlgs\bin\gswin32c.exe       available  GPL Ghostscript 9.26 (2018-11-20)

Packages for equation preview  Status
-----------------------------  ------
standalone                     available
preview                        available
xcolor                         available
amsmath                        available
amssymb                        available
latexsym                       available
mathtools                      available

Builder      Status
-------      ------
traditional  available

Builder Setting  Value
---------------  -----
display_log      False
linux            {}   
osx              {}   
windows          {}   

TeX Root

LaTeX Engine

Viewer   Status     Location
------   ------     --------
sumatra  available  C:\Users\Clover\AppData\Local\SumatraPDF\SumatraPDF.exe
1 Like


I generally use TeXstudio for all my LaTeX work & I have never considered using Sublime for it so take the following solution with a grain of salt. I am also by no means an expert in LaTeX or Sublime.
I have MiKTeX installed in my system & set it’s path in PATH. I just googled a bit about how to compile a .tex file into a .pdf file from the command line (the command is pdflatex tex_file_name) & using that knowledge, the following is a rudimentary build system I have come up with :-

	"name": "LaTeX build system",
	"target": "latex_build",
	"selector": "text.tex.latex",

The custom target for this build system (which is latex_build) comes from the following plugin :-

import os
import sublime
import sublime_plugin

class LatexBuildCommand(sublime_plugin.WindowCommand):
	""" A simple custom target for a LaTeX build system.

	def run(self, **kwargs):
		""" Invoked when the command is executed.

			kwargs (dict) : Arguments passed on to run.

		current_tex_file = self.window.active_view().file_name()
		pdf_file_name = os.path.splitext(self.window.active_view().file_name())[0] + ".pdf"
		kwargs["shell_cmd"] = "pdflatex {} && start {}".format(current_tex_file, pdf_file_name)
		self.window.run_command("exec", kwargs)

With this in place, I was able to compile a .tex file into it’s pdf counterpart & view it in Adobe Reader. Now this build system is by no means a real time build system (since you have to close the pdf file every time you compile the tex file as pdflatex asks you for a new file name for a pdf output if the previous pdf output is currently open because of which the build becomes inactive as builds cannot take inputs) and also I have tested it on Windows 7 x64 but I guess this can serve as a starting point for you.

1 Like


@jfcherng First of all, thanks for the feedback about my posted issue… yeah, I’ve been aware about texlive for years although I’ve been a happy user of the more lightweight miktex for a while and I’d prefer using that backend instead :wink: … Maybe it’s just me being stubborn but I was forced to use texlive for the sake of LatexTools hapiness I wouldn’t be using that package in the first place :slight_smile:

That said, right now I was debugging a bit the package and looking at the whole function wrappers
built on top of subprocess and they’re really ugly/messy… on the other hand, ST3 still forcing to use the good archaic python 3.3.6 so I don’t blame them for having such an overcomplex suite of functions on top of it. It’d be awesome if someday ST3 would upgrade python version (already asked for it over the last years so I’m not very optimistic this will happen anytime soon though :slight_smile: )

Anyway, the error is this:

Error finding Ghostscript version for d:\software\miktex\miktex29\miktex\bin\x64\mgs.EXE
Traceback (most recent call last):
File “D:\sources\personal\sublimetext3\Data\Packages\LaTeXTools\st_preview\”, line 100, in _update_gs_version
raw_version = check_output([_GS_COMMAND, ‘-version’], shell=True)
File “D:\sources\personal\sublimetext3\Data\Packages\LaTeXTools\latextools_utils\”, line 362, in check_output
File “D:\sources\personal\sublimetext3\Data\Packages\LaTeXTools\latextools_utils\”, line 281, in execute_command
File “D:\sources\personal\sublimetext3\Data\Packages\LaTeXTools\latextools_utils\”, line 232, in external_command
File “./python3.3/”, line 784, in init
File “./python3.3/”, line 980, in _get_handles
File “./python3.3/”, line 1030, in _make_inheritable
OSError: [WinError 6] The handle is invalid

It happens when trying to capture the output of mgs -version, which runs ok in my shell.

The trackeback happens here… which will end calling Popen here , I’ve seen that error in the past and usually was because stdin wasn’t None, in this case is None so I’m still trying to figure out what’s wrong :slight_smile: . Anyway, maybe this is the underlying reason why the check_system command is failing

@UltraInstinct05 Yeah, I’ve used Texstudio quite a lot and it’s quite nice… but I’d really love to start using ST3 so I don’t need context switching while coding&editing anymore… That snippet of yours is a good starting point, I’ll give it a shot… I’ve downloaded the lightweight sumatra pdf viewer which may be a better viewer than AcrobatReader… Actually, my first idea was using TexWorks’s pdf viewer but maybe that’s just a builtin that can’t be used as a external tool.

Anyway guys, thanks for the feedback/ideas… If you’ve got other ideas please let me know, let’s debug a bit more :slight_smile:



I have never used Sumatra PDF viewer before but if it has an executable, then I guess the only change would be in the following line :-

kwargs["shell_cmd"] = "pdflatex {} && start {}".format(current_tex_file, pdf_file_name)

to this :-

kwargs["shell_cmd"] = "pdflatex {} && path_to_sumatra_exe {}".format(current_tex_file, pdf_file_name)

where instead of start you would replace it with the path to the executable.



If you get the compilation work, the inverse search feature in sumatra pdf can help your preview experience.



I’ve given up with LatexTools (at least for now, I’ll wait till the maintainers take a look to my issue)… I think I’ll go with a slightly modified version of @UltraInstinct05’s snippet, ie:

class SimpleBuildLatexCommand(sublime_plugin.WindowCommand):

    def run(self, **kwargs):
        from pathlib import Path
        src = Path(self.window.active_view().file_name())
        dst = "{}.pdf".format(src.parent / src.stem)
        viewer = kwargs.pop("viewer", "sumatrapdf")
        kwargs["cmd"] = "pdflatex {} && {} {}".format(src, viewer, dst)
        kwargs["shell"] = True
        self.window.run_command("exec", kwargs)

About the inverse search feature… that sounds interesting, not sure if we can add it easily to the above command (or different) somehow to improve the workflow?



Finally I’ve been able to run succesfully LatexTools (posted the results of my research in the above issue)… But to make things short, when using subprocess python submodule you need to consider the fact that ST can be spawned from the desktop manager, terminal or any other process… So the handles may become invalid ones in certain cases.



I’ve been testing for a while LatexTools package with fairly complex .tex files and while I think it’s quite nice overall package I can’t say I’m fully sold tbh… In fact, I think the experience using TexStudio is much nicer :confused:

That said, I think having a simple lightweight command like the posted by @UltraInstinct05 above could be really handy in order to create small pdf stuff (ie: mathy stuff) so I’ve been trying to tweak the commanda to make forward-search in sumatra as well as providing change focus back to sublime after the pdf displayed in the viewer but it’s not working, here’s what I’ve got so far:

class SimpleBuildLatexCommand(sublime_plugin.WindowCommand):

def run(self, **kwargs):
    view = self.window.active_view()
    src = Path(view.file_name())
    dst = "{}.pdf".format(src.parent / src.stem)
    viewer = kwargs.pop("viewer", "sumatrapdf")

    if viewer=="sumatrapdf" and view.sel():
        line,col = view.rowcol(view.sel()[0].a)
        viewer = "sumatrapdf -forward-search {} {}".format(src, line)

    cmd = "pdflatex {} && {} {}".format(src, viewer, dst)
    kwargs["cmd"] = cmd
    kwargs["shell"] = True
    self.window.run_command("exec", kwargs)

Would you know how to fix the above? I guess focus_group not working it’s probably because run_command is async so you’d need some sort of timeout or figure out when the render in the viewer has finished… but what about the forward-search, do you know how to make it work?

For those interested to give it a shot, here’s the sumatra command line arguments



Here’s my latest attempt:

Build system

		"name": "Build & View LaTeX",
		"selector": "text.tex.latex",
		"target": "simple_build_latex",
		"viewer": "sumatrapdf"


class SimpleBuildLatexCommand(sublime_plugin.WindowCommand):

def run(self, **kwargs):
    view = self.window.active_view()
    src = view.file_name()
    dst = os.path.splitext(src)[0] + ".pdf"
    viewer = kwargs.pop("viewer", "sumatrapdf")

    if viewer == "sumatrapdf" and view.sel():
        line, col = view.rowcol(view.sel()[0].a)
        viewer = "sumatrapdf -reuse-instance -forward-search {} {}".format(src, line)

    cmd = "pdflatex {} && {} {}".format(src, viewer, dst)
    kwargs["cmd"] = cmd
    kwargs["shell"] = True
    self.window.run_command("exec", kwargs)

    def change_focus_back():
        print('Changing focus back...')

    sublime.set_timeout(change_focus_back, 1000)

Sumatra settings

Inverse-search: "D:\sources\personal\sublimetext3\sublime_text.exe" "%f:%l"


  1. Change focus to Sublime not working
  2. Forward search not working when pdf rendered in sumatra
  3. Inverse search not working when double clicking in sumatra

Could anyone advice about the issues? Thx!



Adding --synctex=1 to the pdflatex solved issues 2 & 3. Now the only remaining thing is fixing 1 and I can consider this thread closed … :slight_smile:



My hunch is that since the exec command is running an external pdf viewer executable, it changes focus to the Sumatra Viewer thus the Sublime application itself loses focus, thus the focus_group command is of no use because Sublime itself doesn’t have the focus after running the build system.



Yeah, that sounds correct… unfortunately I haven’t been able to figure out yet a good way to solve this problem.

It seems sumatra already does automatic reload by default so another idea was having 2 commands, one would spawn sumatra with forward-search and then the other would regenerate the pdf… problem with this approach is you just do it like this you’re not using forward-search which is extremely valuable feature while editing latex.

Anyway, if anyone knows a proper way to keep the focus in St it’d be awesome… In fact, even LatexTools is not doing 100% correctly… it seems they also use some sort of timeout… so if you regenerate the pdf and then immediately press any of the arrow keys before the focus is back to ST you’ll set the “permanent focus” in Sumatra :slight_smile:

The only I can think of would be using the win32API to capture the sumatrapdf window and send it some messages to make the forward-search but maybe this is difficult to achieve… Another idea was spawning sumatra as a foreground task (ie: start /b ... or ... & in win/unix) but on windows the focus is changed.

Anyway, if you’ve got some ideas/solution to the given problem just let me know.




Hi thread!

miktex-texworks supports live updating. You just have to open it:
miktex-texworks mydocument.pdf

Now you can continuously build the .pdf file from a build command in ST3 and see the changes live in TeXworks.



That’s a pretty cool answer… by any chance, does miktex-texworks support forward/reverse search? If that was the case this would rock hard as it’d mean you wouldn’t need to install any additional tool such as sumatrapdf.

Speaking of which, at this point the only problem I’m having when using ST+sumatra is when I spawn sumatra with forward search using my sublime command to be able to keep the focus… other than that, I’d say this workflow would be pretty ideal.



This was quite refreshing as I always have headaches with MS Word Equation Editor. Mostly, I just wanted to write a quick post to share some of the tools I found useful while doing this.



Thanks to join to the Sublime community… sure, don’t hesitate to share with us all the tools you’ve found useful. And yeah, I share the pain… the MS Word Equation Editor can be really frustrating and latex just rocks.

I still dunno how to do forward/reverse search without losing focus with Sublime/sumatra powerful combo though so if anyone figures out pls share :slight_smile: