Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display file while still in find-file-hook

Tags:

emacs

Currently, I use find-file-hook to invoke a lengthy compilation/checking of that file. I have therefore to wait for some time to actually see the file. What I would like to do instead is to be able to view (not edit) the file already while the checker is running, thus creating the illusion of instantaneous compilation. How can I do this?

like image 251
false Avatar asked Oct 28 '16 23:10

false


2 Answers

Using find-file-hook means your code will run on every file you open; are you sure you want this? It may make more sense to create a new major or minor mode for the type of file you want to run your validation on and then use the corresponding mode hook. For instance, if you wanted to check all .chk files (with your new major mode inheriting from prog-mode):

(define-derived-mode check-mode prog-mode "Checker")
(add-to-list 'auto-mode-alist '("\\.chk\\'" . check-mode))
(add-hook 'check-mode-hook 'check-mode-computation-hook)

As for the actual hook, this code (going off phils' comment) works for me:

;;; -*- lexical-binding: t -*-
(defun slow-computation ()
  (dotimes (i 10000000)
    (+ i 1)))

(defun check-mode-computation-hook ()
  (let ((cb (current-buffer))
        (ro buffer-read-only))
    (setq-local buffer-read-only t)
    (run-at-time .1 nil
                 (lambda ()
                   (with-current-buffer cb
                     (message "Loading...")
                     (slow-computation)
                     (setq-local buffer-read-only ro)
                     (message "Loaded!"))))))

Note, though, that though this will display the file, emacs will still be frozen until it finishes its processing, as emacs doesn't actually support multithreading. To get around this, you may have to use a library like async, deferred, or concurrent.

like image 195
charliegreen Avatar answered Oct 20 '22 03:10

charliegreen


You should considered using Flycheck which provides async syntax checking for most programming languages and provides a nice API for implementing new/custom checkers.

like image 41
Jürgen Hötzel Avatar answered Oct 20 '22 05:10

Jürgen Hötzel