SublimeText / LaTeXTools

LaTeX plugin for Sublime Text
https://latextools.readthedocs.io/
2.01k stars 365 forks source link

How can I delete all temporary files automatically after build? #323

Open richard1017 opened 10 years ago

richard1017 commented 10 years ago

I'm on Windows 7 and uses the XeLaTeX engine, as in #294.

I tried to use a "-c" option for texify as follows, but without any luck. The build command won't work any more.

"cmd": ["texify", "--engine=xetex",
                "-b", "-c", "-p",
                "--tex-option=\"--synctex=1\""
        ],

I also noticed that there is a delete-temp-files command provided with the package. I don't know how to execute this command automatically after each build.

Any help would be appreciated. Thanks.

chid commented 10 years ago

Can you verify that the delete-temp-files command works as you require? I could add a setting for clean files after build if that's necessary.

richard1017 commented 10 years ago

Hi Charley,

Yes, the delete-temp-files works very well.

chid commented 10 years ago

Just make your CmdThread in makePDF.py look like this


class CmdThread ( threading.Thread ):

    # Use __init__ to pass things we need
    # in particular, we pass the caller in teh main thread, so we can display stuff!
    def __init__ (self, caller):
        self.caller = caller
        threading.Thread.__init__ ( self )

    def run ( self ):
        print ("Welcome to thread " + self.getName())
        cmd = self.caller.make_cmd + [self.caller.file_name]
        self.caller.output("[Compiling " + self.caller.file_name + "]")
        if DEBUG:
            print (cmd.encode('UTF-8'))

        # Handle path; copied from exec.py
        if self.caller.path:
            old_path = os.environ["PATH"]
            # The user decides in the build system  whether he wants to append $PATH
            # or tuck it at the front: "$PATH;C:\\new\\path", "C:\\new\\path;$PATH"
            # Handle differently in Python 2 and 3, to be safe:
            if not _ST3:
                os.environ["PATH"] = os.path.expandvars(self.caller.path).encode(sys.getfilesystemencoding())
            else:
                os.environ["PATH"] = os.path.expandvars(self.caller.path)

        try:
            if platform.system() == "Windows":
                # make sure console does not come up
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                proc = subprocess.Popen(cmd, startupinfo=startupinfo)
            else:
                proc = subprocess.Popen(cmd)
        except:
            self.caller.output("\n\nCOULD NOT COMPILE!\n\n")
            self.caller.output("Attempted command:")
            self.caller.output(" ".join(cmd))
            self.caller.proc = None
            return

        # restore path if needed
        if self.caller.path:
            os.environ["PATH"] = old_path

        # Handle killing
        # First, save process handle into caller; then communicate (which blocks)
        self.caller.proc = proc
        # out, err = proc.communicate()
        proc.wait() # TODO: if needed, must use tempfiles instead of stdout/err

        # if DEBUG:
        #   self.caller.output(out)

        # Here the process terminated, but it may have been killed. If so, do not process log file.
        # Since we set self.caller.proc above, if it is None, the process must have been killed.
        # TODO: clean up?
        if not self.caller.proc:
            print (proc.returncode)
            self.caller.output("\n\n[User terminated compilation process]\n")
            self.caller.finish(False)   # We kill, so won't switch to PDF anyway
            return
        # Here we are done cleanly:
        self.caller.proc = None
        print ("Finished normally")
        print (proc.returncode)

        # this is a conundrum. We used (ST1) to open in binary mode ('rb') to avoid
        # issues, but maybe we just need to decode?
        # 12-10-27 NO! We actually do need rb, because MikTeX on Windows injects Ctrl-Z's in the
        # log file, and this just causes Python to stop reading the file.

        # OK, this seems solid: first we decode using the self.caller.encoding, 
        # then we reencode using the default locale's encoding.
        # Note: we get this using ST2's own getdefaultencoding(), not the locale module
        # We ignore bad chars in both cases.

        # CHANGED 12/10/19: use platform encoding (self.caller.encoding), then
        # keep it that way!

        # CHANGED 12-10-27. OK, here's the deal. We must open in binary mode on Windows
        # because silly MiKTeX inserts ASCII control characters in over/underfull warnings.
        # In particular it inserts EOFs, which stop reading altogether; reading in binary
        # prevents that. However, that's not the whole story: if a FS character is encountered,
        # AND if we invoke splitlines on a STRING, it sadly breaks the line in two. This messes up
        # line numbers in error reports. If, on the other hand, we invoke splitlines on a
        # byte array (? whatever read() returns), this does not happen---we only break at \n, etc.
        # However, we must still decode the resulting lines using the relevant encoding.
        # 121101 -- moved splitting and decoding logic to parseTeXlog, where it belongs.

        # Note to self: need to think whether we don't want to codecs.open this, too...
        data = open(self.caller.tex_base + ".log", 'rb').read()     

        errors = []
        warnings = []

        try:
            (errors, warnings) = parseTeXlog.parse_tex_log(data)
            content = ["",""]
            if errors:
                content.append("There were errors in your LaTeX source") 
                content.append("")
                content.extend(errors)
            else:
                content.append("Texification succeeded: no errors!")
                content.append("") 
            if warnings:
                if errors:
                    content.append("")
                    content.append("There were also warnings.") 
                else:
                    content.append("However, there were warnings in your LaTeX source") 
                content.append("")
                content.extend(warnings)
        except Exception as e:
            content=["",""]
            content.append("LaTeXtools could not parse the TeX log file")
            content.append("(actually, we never should have gotten here)")
            content.append("")
            content.append("Python exception: " + repr(e))
            content.append("")
            content.append("Please let me know on GitHub. Thanks!")

        self.caller.output(content)
        self.caller.output("\n\n[Done!]\n")
        view = sublime.active_window().active_view()
        self.file_name = getTeXRoot.get_tex_root(view)
        if not os.path.isfile(self.file_name):
            sublime.error_message(self.file_name + ": file not found.")
            return

        self.tex_base, self.tex_ext = os.path.splitext(self.file_name)

        # Delete the files.
        temp_exts = ['.blg','.bbl','.aux','.log','.brf','.nlo','.out','.dvi','.ps',
            '.lof','.toc','.fls','.fdb_latexmk','.pdfsync','.synctex.gz','.ind','.ilg','.idx']

        for temp_ext in temp_exts:
            file_name_to_del = self.tex_base + temp_ext
            #print file_name_to_del
            if os.path.exists(file_name_to_del):
                #print ' deleted '
                os.remove(file_name_to_del)

        sublime.status_message("Deleted the temp files")
        self.caller.finish(len(errors) == 0)
richard1017 commented 10 years ago

Works like a charm! Thank you so much!

logavanc commented 10 years ago

Awesome! Thank you for that, I was trying to get this working FOREVER! IT would be really, REALLY nice to have a setting to automatically clean after build.

gannebamm commented 8 years ago

For me this is still a feature i would love to have. I am unable to use the delete_temp action and I dont know why. The Key-Binding should work but it wont. -- EDIT -- Nevermind, stupid me. Cant read instructions: Keybinding: C-l,backspace Means: Ctrl+L then backspace

Ufos92 commented 8 years ago

Ok, I definitely have the option working, I just want it to be a default behavior: i.e. On the build command I get build+clean up. What's my best option?

huangh12 commented 5 years ago

@chid 's solution is of great help. but I find deleting all temp files cause sumatrapdf not support inverse search anymore. So I only delete .aux file.