Search code examples
latexsublimetext3xelatex

Sublime text build system - how to auto open pdfs


I followed instructions provided here(How to create a shortcut for user's build system in Sublime Text?) to compile latex documents in xelatex, and on top of that I would also like it to automatically open pdf after compiling just like with latexmk, how can I achieve that? The document is built just fine, but I have to open it each time manually.


Solution

  • Here's an extension to the CompileWithXelatexCommand implementation that successfully opens the PDF in my default PDF viewer.

    import sublime, sublime_plugin
    import os
    import time
    
    class CompileWithXelatexCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            if '/usr/texbin' not in os.environ['PATH']:
                os.environ['PATH'] += ':/usr/texbin'
    
            base_fname = self.view.file_name()[:-4]
            pdf_fname = base_fname + ".pdf"
            self.view.window().run_command('exec',{'cmd': ['xelatex','-synctex=1','-interaction=nonstopmode',base_fname]})
    
            tries = 5
            seconds_to_wait = 1
            while tries > 0:
                if os.path.isfile(pdf_fname):
                    break
                time.sleep(seconds_to_wait)
                seconds_to_wait *= 2
                tries -= 1
    
            os.system("open " + pdf_fname)
    

    The polling loop is required; otherwise, the open call may happen before the PDF has been generated. There may be a cleaner way to synchronously exec a sequence of commands via run_command.

    I don't have access to Windows now, but from this post you'll probably just need to change "open " to "start ". The PATH initialization logic will either need to be eliminated or adjusted.