When editing TeX files, programming, upgrading packages, etc. we often need to perform tasks - such as compiling code or downloading files from internet - that take a long time to achieve. We can do all of them in Emacs, however executing such commands freezes the session: is there a way to execute heavy commands in the background, for example using another thread ?
You need to use process sentinels. Try for example this:
(require 'tex-site) (defun build-view () "Build LaTeX and view if file is dirty. View only otherwise." (interactive) (if (buffer-modified-p) (let (build-proc (TeX-save-query nil) (LaTeX-command-style '(("" "%(PDF)%(latex) -shell-escape -file-line-error %S%(PDFout)")))) (TeX-save-document (TeX-master-file)) (setq build-proc (TeX-command "LaTeX" 'TeX-master-file -1)) (set-process-sentinel build-proc 'build-sentinel)) (TeX-view))) (defun build-sentinel (process event) "Sentinel to run viewer after successful LaTeXing" (if (string= event "finished\n") (TeX-view) (message "Errors! Check with C-c `")))
In this case, when the LaTeX buffer has been modified,
(set-process-sentinel build-proc 'build-sentinel)
runs the build process
(TeX-command "LaTeX" 'TeX-master-file -1) in the background.
Sentinel functions, here
build-sentinel, monitor a process running in the background without blocking Emacs. In this case, when
build-sentinel detects the build process is finished, it starts the PDF viewer.
There are other functions involved, for example
LaTeX-command-style defines what flavour of LaTeX command you will actually run; but the main point to craft an asynchronous process is in the function setting the sentinel.