d2-mode icon indicating copy to clipboard operation
d2-mode copied to clipboard

Add watch support

Open andorsk opened this issue 3 years ago • 5 comments

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

andorsk avatar Nov 22 '22 18:11 andorsk

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

andorsk avatar Nov 29 '22 10:11 andorsk

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

shelper avatar Dec 05 '22 17:12 shelper

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.

andorsk avatar Dec 05 '22 18:12 andorsk

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))

baturkey avatar Mar 13 '24 20:03 baturkey

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)

terlar avatar Jul 29 '24 15:07 terlar