andorsk / d2-mode

emacs major mode for d2 graphs
GNU General Public License v3.0
73 stars 8 forks source link

Add watch support #9

Open andorsk opened 1 year ago

andorsk commented 1 year ago

add watch support for d2 diagrams. spins up server which you can go to the browser for

andorsk commented 1 year ago

Realized that while watch mode would be cool, it's not required for alpha. more important is just fixing the svg issue.

shelper commented 1 year ago

do you mean real time recompile and refeshing if the content of the source file chagnes by this watch mode? that would be awesome.

andorsk commented 1 year ago

yea....that was the idea. d2 already supports some server implementation, but I would need to write a bit to manage those processes. it's definitely a cool idea, but could easily get messy if handled incorrectly.

baturkey commented 7 months ago

I was able to get watch functionality working by adding a function to after-save-hook that runs d2

(use-package d2-mode
  :init
  (add-to-list 'auto-mode-alist '("\\.d2\\'" . d2-mode))
  :config
  (defun d2-update ()
    (if (string-suffix-p ".d2" (buffer-name))
    (start-process "d2-png" "*d2-png*" "d2" (buffer-name) (concat (substring (buffer-name) 0 -3)) ".png")))
  :hook
  (after-save . d2-update))

And then turning on auto-revert-mode for images

(use-package image-mode
  :config
  (defun image-mode-hook ()
    (auto-revert-mode))
  :hook
  (image-mode . image-mode-hook))
terlar commented 3 months ago

I did a similar approach with auto-revert-mode but instead went via the compile-command and then a generic mode to auto-recompile.

(defun compile-on-save-start ()
    (let ((compile-buffer (compilation-find-buffer)))
      (unless (get-buffer-process compile-buffer)
        (let ((display-buffer-alist '(("^*compilation*" . (display-buffer-no-window)))))
          (recompile)))))

(define-minor-mode compile-on-save-mode
    "Minor mode to automatically call `recompile' whenever the
current buffer is saved. When there is ongoing compilation,
nothing happens."
    :lighter " CoS"
    (if compile-on-save-mode
        (progn  (make-local-variable 'after-save-hook)
                (add-hook 'after-save-hook 'compile-on-save-start nil t))
      (remove-hook 'after-save-hook 'compile-on-save-start t)))

(defun d2-mode-set-compile-command ()
    "Configure compile command for d2-mode."
    (set (make-local-variable 'compile-command)
         (mapconcat #'shell-quote-argument (append (list d2-location buffer-file-name) d2-flags)
                    " ")))

(add-hook 'd2-mode-hook '#d2-mode-set-compile-command)
(add-hook 'd2-mode-hook '#compile-on-save-mode)
(add-hook 'image-mode-hook '#auto-revert-mode)