dotfiles

My personal shell configs and stuff
git clone git://git.alex.balgavy.eu/dotfiles.git
Log | Files | Refs | Submodules | README | LICENSE

config.org (144058B)


      1 * macOS installation info
      2 On macOS, I use Homebrew to install Emacs from daviderestivo/emacs-head/emacs-head@28.
      3 I install with ~--HEAD --with-dbus --with-cocoa --with-xwidgets --with-native-comp~.
      4 
      5 * Why I choose use-package
      6 - provides bind-key by default
      7 - is mostly just macros that wrap the needed stuff from package.el. can check that with ~macroexpand~.
      8 - adds a bunch of performance improvements
      9 * Let me know when we're at a certain version
     10 #+begin_src emacs-lisp
     11   (when (version<= "30" emacs-version)
     12     (message "Check out C-x w d to make windows dedicated."))
     13 #+end_src
     14 * Install from source
     15 Emacs 29 ships with a way to install packages from source, here's a small wrapper around it.
     16 
     17 #+begin_src emacs-lisp
     18   (cl-defun za/package-vc-install (&key (fetcher "github") repo name rev backend load)
     19     "Install a package from a remote if it's not already installed.
     20   This is a thin wrapper around `package-vc-install' in order to
     21   make non-interactive usage more ergonomic.  Takes the following
     22   named arguments:
     23 
     24   - FETCHER the remote where to get the package (e.g., \"gitlab\").
     25     If omitted, this defaults to \"github\".
     26 
     27   - REPO should be the name of the repository (e.g.,
     28   \"slotThe/arXiv-citation\".
     29 
     30   - NAME, REV, and BACKEND are as in `package-vc-install' (which
     31     see).
     32 
     33   - LOAD is optionally a subdirectory that should be added to `load-path'."
     34     (let* ((url (cond ((string-match-p (rx bos "http" (? ?s) "://") repo)
     35                        repo)
     36                       (t (format "https://www.%s.com/%s" fetcher repo))))
     37            (iname (when name (intern name)))
     38            (pac-name (or iname (intern (file-name-base repo))))
     39            (to-load (when load
     40                       (format "%s/%s"
     41                               (package-desc-dir (package-get-descriptor pac-name))
     42                               load))))
     43       (unless (package-installed-p pac-name)
     44         (package-vc-install url rev backend iname))
     45       (when load
     46         (unless (file-directory-p to-load)
     47           (user-error "Not a readable dir: %s" to-load))
     48         (add-to-list 'load-path to-load))
     49       (message "%s" pac-name)))
     50 #+end_src
     51 
     52 You can use this in use-package with an ~:init~ clause.
     53 
     54 * exec-path-from-shell (macOS)
     55 In macOS, the path is not set correctly (i.e. as it is in the terminal) in the GUI app. This fixes it.
     56 Not needed when using emacs-plus, because it has a custom patch for it. It also defines a [[https://github.com/d12frosted/homebrew-emacs-plus?tab=readme-ov-file#system-appearance-change][custom variable]] which hopefully should be enough to detect if we're running emacs-plus.
     57 
     58 #+begin_src emacs-lisp
     59   (when (and (string-equal system-type "darwin")
     60              (not (boundp 'ns-system-appearance-change-functions)))
     61     (use-package exec-path-from-shell
     62       :config
     63       (add-to-list 'exec-path-from-shell-variables "NOTMUCH_CONFIG")
     64       (exec-path-from-shell-initialize)))
     65 #+end_src
     66 
     67 * Emacs file locations
     68 ** Auto-Save files
     69 By default, auto-save files ("#file#") are placed in the same directory as the file itself.
     70 I want to put this all in some unified place:
     71 
     72 #+begin_src emacs-lisp
     73   (let ((saves-directory "~/.local/share/emacs/saves/"))
     74     (unless (file-directory-p saves-directory)
     75       (make-directory saves-directory))
     76     (setq auto-save-file-name-transforms
     77           `((".*" ,saves-directory t))))
     78 #+end_src
     79 
     80 ** Backup files
     81 By default, backup files (those with a tilde) are saved in the same directory as the currently edited file.
     82 This setting puts them in ~/.local/share/emacs/backups.
     83 
     84 #+begin_src emacs-lisp
     85   (let ((backups-directory "~/.local/share/emacs/backups"))
     86     (unless (file-directory-p backups-directory)
     87       (make-directory backups-directory))
     88     (setq backup-directory-alist `(("." . ,backups-directory)))
     89     (setq backup-by-copying t))
     90 #+end_src
     91 
     92 ** Custom settings file
     93 Both commands are necessary.
     94 First one tells Emacs where to save customizations.
     95 The second one actually loads them.
     96 
     97 #+begin_src emacs-lisp
     98   (setq custom-file (expand-file-name (concat user-emacs-directory "custom.el")))
     99   (load custom-file)
    100 #+end_src
    101 ** Delete by trash
    102 #+begin_src emacs-lisp
    103   (setq delete-by-moving-to-trash t)
    104   (unless (fboundp 'system-move-file-to-trash)
    105     (setq trash-directory "~/.Trash"))
    106 #+end_src
    107 * Daemon
    108 I want to have a way to kill the Emacs daemon.
    109 So, define a function that kills the frame, and with a prefix kills emacs.
    110 
    111 #+begin_src emacs-lisp
    112   (defun za/emacsclient-c-x-c-c (&optional arg)
    113     "If running in emacsclient, make C-x C-c exit frame, and C-u C-x C-c exit Emacs."
    114     (interactive "P") ; prefix arg in raw form
    115     (if arg
    116         (save-buffers-kill-emacs)
    117       (save-buffers-kill-terminal)))
    118 #+end_src
    119 
    120 Then, if I'm in an emacsclient, I want to bind C-x C-c to that function (if not, I just want the default keybinding):
    121 
    122 #+begin_src emacs-lisp
    123   ;; If not running in emacsclient, use the default bindings
    124   (if (daemonp)
    125       (bind-key "C-x C-c" #'za/emacsclient-c-x-c-c))
    126 #+end_src
    127 
    128 Furthermore, I want to set the theme correctly whenever I connect with 'emacsclient':
    129 
    130 #+begin_src emacs-lisp
    131   (if (daemonp)
    132       (add-hook 'after-make-frame-functions #'za/auto-select-theme))
    133 #+end_src
    134 * Sound support
    135 On macOS, you can use afplay:
    136 
    137 #+begin_src emacs-lisp
    138   (defun za/play-sound-file-macos (file &optional volume device)
    139     "Play sound using `afplay` on macOS"
    140     (unless (file-readable-p file)
    141       (user-error "File %s not readable." file))
    142 
    143     ;; the `apply` is required here because I need to build a list of arguments
    144     (apply 'start-process `("afplay" nil
    145                             "afplay"
    146                             ,@(if volume (list "-v" (int-to-string volume)))
    147                             ,file)))
    148 #+end_src
    149 
    150 Then redefine the play-sound-file function where needed:
    151 
    152 #+begin_src emacs-lisp
    153   (cond ((and (not (fboundp 'play-sound-internal))
    154               (eq system-type 'darwin))
    155          (advice-add 'play-sound-file :override #'za/play-sound-file-macos)))
    156 #+end_src
    157 * DISABLED Fix non-dbus macOS notification
    158 macOS version might not be compiled with dbus support; in that case you can use e.g. terminal-notifier.
    159 If you use the ~sender~ option, notifications don't show
    160 unless the app is in the background. [[https://github.com/julienXX/terminal-notifier/issues/68][See this Github issue.]]
    161 
    162 #+begin_src emacs-lisp :tangle no
    163   ;; on mac without dbus:
    164   (org-show-notification-handler
    165    (lambda (str) (start-process "terminal-notifier" nil (executable-find "terminal-notifier")
    166                                 "-title" "Timer done"
    167                                 "-message" str
    168                                 "-group" "org.gnu.Emacs"
    169                                 "-ignoreDnD"
    170                                 "-activate" "org.gnu.Emacs")))
    171 #+end_src
    172 * Custom notification functions
    173 #+begin_src emacs-lisp
    174   (defun za/notify (title message)
    175     "Show notification with TITLE and MESSAGE."
    176     (ignore-errors (require 'notifications))
    177     (cond ((fboundp 'ns-do-applescript)
    178            (ns-do-applescript
    179             (format "display notification \"%s\" with title \"%s\""
    180                     (replace-regexp-in-string "\"" "#" message)
    181                     (replace-regexp-in-string "\"" "#" title))))
    182           ((string= system-type "gnu/linux")
    183            (require 'notifications)
    184            (notifications-notify :title title :body message))
    185           (t (error "No notification handler defined!"))))
    186 
    187   (defun za/send-notification-interactivity-required (&rest _)
    188     "Notify that a function needs action."
    189     (za/notify "Interactivity required" "A function requires interactivity."))
    190 
    191   (defun za/notify-on-interactivity (func &rest r)
    192     "Send a notification whenever FUNC requires interactivity.
    193   Used as :around advice, calling FUNC with arguments R."
    194     (advice-add #'y-or-n-p :before #'za/send-notification-interactivity-required)
    195     (advice-add #'yes-or-no-p :before #'za/send-notification-interactivity-required)
    196     (advice-add #'user-error :before #'za/send-notification-interactivity-required)
    197     (with-demoted-errors "Error in %s" (apply func r))
    198     (advice-remove #'y-or-n-p #'za/send-notification-interactivity-required)
    199     (advice-remove #'yes-or-no-p #'za/send-notification-interactivity-required)
    200     (advice-remove #'user-error #'za/send-notification-interactivity-required))
    201 #+end_src
    202 
    203 * URLs
    204 #+begin_src emacs-lisp
    205   (defun za/browse-url-quicksilver (url &rest args)
    206     (call-process-shell-command (format "printf '%s' | qs -" url)))
    207   (setopt browse-url-handlers `((,(rx "http" (? ?s) "://") . za/browse-url-quicksilver)))
    208 #+end_src
    209 * Editing
    210 ** Everything is UTF-8
    211 #+begin_src emacs-lisp
    212   (set-language-environment 'utf-8)
    213   (setq locale-coding-system 'utf-8)
    214   (setq buffer-file-coding-system 'utf-8-unix)
    215   (set-terminal-coding-system 'utf-8)
    216   (set-keyboard-coding-system 'utf-8)
    217   (set-selection-coding-system 'utf-8)
    218   (prefer-coding-system 'utf-8)
    219 #+end_src
    220 ** Overwrite selection on typing
    221 Normally, when I select something and start typing, Emacs clears the selection, i.e. it deselects and inserts text after the cursor.
    222 I want to replace the selection.
    223 
    224 #+begin_src emacs-lisp
    225   (delete-selection-mode t)
    226 #+end_src
    227 
    228 ** Strip trailing whitespace
    229 You can show trailing whitespace by setting show-trailing-whitespace to 't'.
    230 But I want to automatically strip trailing whitespace.
    231 Luckily there's already a function for that, I just need to call it in a hook:
    232 
    233 #+begin_src emacs-lisp
    234   (add-hook 'before-save-hook #'delete-trailing-whitespace)
    235 #+end_src
    236 
    237 ** Formatting & indentation
    238 
    239 Show a tab as 8 spaces:
    240 
    241 #+begin_src emacs-lisp
    242   (setq-default tab-width 8)
    243 #+end_src
    244 
    245 Never insert tabs with indentation by default:
    246 
    247 #+begin_src emacs-lisp
    248   (setq-default indent-tabs-mode nil)
    249 #+end_src
    250 
    251 Allow switching between the two easily:
    252 
    253 #+begin_src emacs-lisp
    254   (defun indent-tabs ()
    255     (interactive)
    256     (setq indent-tabs-mode t))
    257   (defun indent-spaces ()
    258     (interactive)
    259     (setq indent-tabs-mode nil))
    260 #+end_src
    261 
    262 Indentation for various modes:
    263 
    264 #+begin_src emacs-lisp
    265   (setq-default sh-basic-offset 2
    266                 c-basic-offset 4)
    267 #+end_src
    268 
    269 ** Wrapping
    270 A function to toggle wrapping:
    271 
    272 #+begin_src emacs-lisp
    273   (defvar-local za/wrapping nil "Wrapping changes per buffer.")
    274 
    275   (defun za/toggle-wrap (&optional enable)
    276     "Toggle line wrapping settings. With ENABLE a positive number, enable wrapping. If ENABLE is negative or zero, disable wrapping."
    277     (interactive "P") ; prefix arg in raw form
    278 
    279     ;; If an argument is provided, prefix or otherwise
    280     (if enable
    281         (let ((enable (cond ((numberp enable)
    282                              enable)
    283                             ((booleanp enable)
    284                              (if enable 1 0))
    285                             ((or (listp enable) (string= "-" enable))
    286                              (prefix-numeric-value enable)))))
    287           ;; If zero or negative, we want to disable wrapping, so pretend it's currently enabled.
    288           ;; And vice versa.
    289           (cond ((<= enable 0) (setq za/wrapping t))
    290                 ((> enable 0) (setq za/wrapping nil)))))
    291 
    292 
    293     (let ((disable-wrapping (lambda ()
    294                               (visual-line-mode -1)
    295                               (toggle-truncate-lines t)))
    296           (enable-wrapping (lambda ()
    297                              (toggle-truncate-lines -1)
    298                              (visual-line-mode))))
    299 
    300       ;; If za/wrapping is not locally set, infer its values from the enabled modes
    301       (unless (boundp 'za/wrapping)
    302         (setq za/wrapping (and visual-line-mode
    303                                (not truncate-lines))))
    304 
    305       ;; Toggle wrapping based on current value
    306       (cond (za/wrapping
    307              (funcall disable-wrapping)
    308              (setq za/wrapping nil)
    309              (message "Wrapping disabled."))
    310             (t
    311              (funcall enable-wrapping)
    312              (setq za/wrapping t)
    313              (message "Wrapping enabled.")))))
    314 #+end_src
    315 
    316 And a keybinding to toggle wrapping:
    317 
    318 #+begin_src emacs-lisp
    319   (bind-key "C-c q w" #'za/toggle-wrap)
    320 #+end_src
    321 
    322 And fringe indicators:
    323 
    324 #+begin_src emacs-lisp
    325   (setopt visual-line-fringe-indicators '(left-curly-arrow right-curly-arrow))
    326 #+end_src
    327 ** Pager toggle
    328 M-x view-mode enables pager behavior.
    329 I want read-only files to automatically use pager mode:
    330 
    331 #+begin_src emacs-lisp
    332   (setq view-read-only t)
    333 #+end_src
    334 ** Prefer newer file loading
    335 #+begin_src emacs-lisp
    336   (setq load-prefer-newer t)
    337 #+end_src
    338 
    339 ** Automatically find tags file
    340 When opening a file in a git repo, try to discover the etags file:
    341 
    342 #+begin_src emacs-lisp
    343   (defun current-tags-file ()
    344     "Get current tags file"
    345     (let* ((tagspath ".git/etags")
    346            (git-root (locate-dominating-file (buffer-file-name) tagspath)))
    347       (if git-root
    348           (expand-file-name tagspath git-root))))
    349 
    350   (setq default-tags-table-function #'current-tags-file)
    351 #+end_src
    352 
    353 There's probably a better way to write this. I need to ask Reddit for feedback at some point.
    354 
    355 ** End sentences with one space
    356 Emacs uses the rather old-fashioned convention of treating a period followed by double spaces as end of sentence. However, it is more common these days to end sentences with a period followed by a single space.
    357 
    358 Let a period followed by a single space be treated as end of sentence:
    359 
    360 #+begin_src emacs-lisp
    361   (setopt sentence-end-double-space nil)
    362 #+end_src
    363 * Keybindings
    364 ** Expansion/completion
    365 Use hippie expand instead of dabbrev-expand:
    366 
    367 #+begin_src emacs-lisp
    368   (bind-key "M-/" #'hippie-expand)
    369 #+end_src
    370 
    371 ** Zap up to char
    372 It's more useful for me to be able to delete up to a character instead of to and including a character:
    373 
    374 #+begin_src emacs-lisp
    375   (defun za/zap-up-to-char-icase ()
    376     "Ignore case for zap-up-to-char"
    377     (interactive)
    378     (let ((case-fold-search nil))
    379       (call-interactively #'zap-up-to-char)))
    380   (bind-key "M-z" #'za/zap-up-to-char-icase)
    381 #+end_src
    382 
    383 ** Forward-word and forward-to-word
    384 Change M-f to stop at the start of the word:
    385 
    386 #+begin_src emacs-lisp
    387   (bind-key "M-f" #'forward-to-word)
    388 #+end_src
    389 
    390 Bind ESC M-f to the old functionality of M-f (stop at end of word)
    391 
    392 #+begin_src emacs-lisp
    393   (bind-key "ESC M-f" #'forward-word)
    394 #+end_src
    395 
    396 ** Rectangle insert string
    397 #+begin_src emacs-lisp
    398   (bind-key "C-x r I" #'string-insert-rectangle)
    399   (bind-key "C-x r R" #'replace-rectangle)
    400 #+end_src
    401 
    402 ** Toggle auto-revert-mode
    403 Sometimes I want to toggle auto reverting (or autoread) of buffer:
    404 
    405 #+begin_src emacs-lisp
    406   (bind-key "C-c q a" #'auto-revert-mode)
    407 #+end_src
    408 ** Fast access to view-mode (pager)
    409 I want to bind view-mode to a key for easy access:
    410 
    411 #+begin_src emacs-lisp
    412   (bind-key "C-c q r" 'view-mode)
    413 #+end_src
    414 
    415 ** Kill this buffer
    416 I like to be able to kill a buffer instantly:
    417 
    418 #+begin_src emacs-lisp
    419   (bind-key "s-<backspace>" 'kill-current-buffer)
    420 #+end_src
    421 
    422 ** Delete this file (and kill the buffer)
    423 #+begin_src emacs-lisp
    424   (defun za/delete-this-file ()
    425     "Kill the current buffer and delete its associated file."
    426     (interactive)
    427     (let ((fname (buffer-file-name))
    428           (buf (current-buffer)))
    429       (unless (and fname (file-exists-p fname))
    430         (user-error "Buffer has no associated file."))
    431 
    432       (unless (yes-or-no-p (format "Really delete %s and its buffer?" fname))
    433         (user-error "User cancelled."))
    434 
    435       (delete-file fname 'trash-if-enabled)
    436       (kill-buffer buf)
    437       (message "Deleted %s and killed its buffer." fname)))
    438 
    439   (bind-key "C-c s-<backspace>" #'za/delete-this-file)
    440 #+end_src
    441 
    442 ** Toggle fullscreen
    443 I'll use the keybinding that's standard on macOS:
    444 
    445 #+begin_src emacs-lisp
    446   (bind-key "C-s-f" #'toggle-frame-fullscreen)
    447 #+end_src
    448 
    449 ** Sexp manipulation
    450 When I write lisp, sometimes I want to switch two sexps (e.g. ~(one) (two)~ → ~(two) (one)~), so a key binding is nice for that:
    451 
    452 #+begin_src emacs-lisp
    453   (bind-key "C-S-t" #'transpose-sexps)
    454 #+end_src
    455 
    456 Also, to raise a sexp (e.g. ~(one (two))~ → ~(two)~):
    457 
    458 #+begin_src emacs-lisp
    459   (bind-key "C-S-u" #'raise-sexp)
    460 #+end_src
    461 
    462 ** Dedicated windows
    463 Sometimes I want to avoid Emacs overriding a window's contents.
    464 So I create a keybinding to toggle dedicated on a window:
    465 
    466 #+begin_src emacs-lisp
    467   (defun za/toggle-window-dedicated-p ()
    468     "Toggle set-window-dedicated-p on current window"
    469     (interactive)
    470     (cond ((window-dedicated-p (selected-window))
    471            (set-window-dedicated-p (selected-window) nil)
    472            (message "Window no longer dedicated"))
    473           (t
    474            (set-window-dedicated-p (selected-window) t)
    475            (message "Window marked as dedicated"))))
    476 
    477   (bind-key "C-x 9" #'za/toggle-window-dedicated-p)
    478 
    479 #+end_src
    480 
    481 ** Rotate windows horizontal ↔ vertical
    482 #+begin_src emacs-lisp
    483   (defun za/rotate-windows ()
    484     (interactive)
    485     (if (= (count-windows) 2)
    486         (let* ((this-win-buffer (window-buffer))
    487                (next-win-buffer (window-buffer (next-window)))
    488                (this-win-edges (window-edges (selected-window)))
    489                (next-win-edges (window-edges (next-window)))
    490                (this-win-2nd (not (and (<= (car this-win-edges)
    491                                            (car next-win-edges))
    492                                        (<= (cadr this-win-edges)
    493                                            (cadr next-win-edges)))))
    494                (splitter
    495                 (if (= (car this-win-edges)
    496                        (car (window-edges (next-window))))
    497                     'split-window-horizontally
    498                   'split-window-vertically)))
    499           (delete-other-windows)
    500           (let ((first-win (selected-window)))
    501             (funcall splitter)
    502             (if this-win-2nd (other-window 1))
    503             (set-window-buffer (selected-window) this-win-buffer)
    504             (set-window-buffer (next-window) next-win-buffer)
    505             (select-window first-win)
    506             (if this-win-2nd (other-window 1))))))
    507 #+end_src
    508 
    509 #+begin_src emacs-lisp
    510   (bind-key "C-x 7" #'za/rotate-windows)
    511 #+end_src
    512 
    513 ** Open line like in Vim
    514 I prefer to open-line the way o/O works in Vim:
    515 
    516 #+begin_src emacs-lisp
    517   ;; Autoindent open-*-lines
    518   (defvar za/open-line-newline-and-indent t
    519     "Modify the behavior of the open-*-line functions to cause them to autoindent.")
    520 
    521   (defun za/open-line (prefix)
    522     "Open line like `o`/`O` in Vim. Negative prefix for line above, positive for below."
    523     (interactive "p")
    524     (cond ((< prefix 0)
    525            (beginning-of-line)
    526            (open-line (abs prefix)))
    527           (t
    528            (end-of-line)
    529            (open-line prefix)
    530            (forward-line 1)))
    531     (when za/open-line-newline-and-indent
    532       (indent-according-to-mode)))
    533 
    534   (defun za/open-line-keep-point (prefix)
    535     "Open line like `o`/`O` in Vim but don't move point. Negative prefix for line above, positive for below."
    536     (interactive "p")
    537     (save-mark-and-excursion (za/open-line prefix)))
    538 #+end_src
    539 
    540 And keybindings:
    541 
    542 #+begin_src emacs-lisp
    543   (bind-key "C-o" #'za/open-line)
    544   (bind-key "C-M-o" #'za/open-line-keep-point)
    545 #+end_src
    546 
    547 ** Unfill region/paragraph
    548 Taken from here: https://www.emacswiki.org/emacs/UnfillParagraph
    549 
    550 #+begin_src emacs-lisp
    551   (defun za/unfill-paragraph (&optional region)
    552     "Takes a multi-line paragraph and makes it into a single line of text."
    553     (interactive (progn (barf-if-buffer-read-only) '(t)))
    554     (let ((fill-column (point-max))
    555           ;; This would override `fill-column' if it's an integer.
    556           (emacs-lisp-docstring-fill-column t))
    557       (fill-paragraph nil region)))
    558 
    559   (bind-key "M-Q" #'za/unfill-paragraph)
    560 #+end_src
    561 ** Easily edit my config
    562 Bind a keyboard shortcut to open my config.
    563 The "(interactive)" means that it can be called from a keybinding or from M-x.
    564 
    565 #+begin_src emacs-lisp
    566   (defun za/edit-config-org ()
    567     "Edit my config.org file"
    568     (interactive)
    569     (find-file (expand-file-name "config.org" user-emacs-directory)))
    570 #+end_src
    571 
    572 #+begin_src emacs-lisp
    573   (bind-key "C-c E" 'za/edit-config-org)
    574 #+end_src
    575 ** Visible mode
    576 #+begin_src emacs-lisp
    577   (bind-key (kbd "C-c q v") #'visible-mode)
    578 #+end_src
    579 ** Clone buffer indirectly by default
    580 #+begin_src emacs-lisp
    581   (bind-key (kbd "C-x x n") #'clone-indirect-buffer)
    582 #+end_src
    583 * Custom functions
    584 ** Make region readonly or writable
    585 #+begin_src emacs-lisp
    586   (defun za/set-region-read-only (begin end)
    587     "Sets the read-only text property on the marked region.
    588   Use `set-region-writeable' to remove this property."
    589     ;; See https://stackoverflow.com/questions/7410125
    590     (interactive "r")
    591     (with-silent-modifications
    592       (put-text-property begin end 'read-only t)))
    593 
    594   (defun za/set-region-writeable (begin end)
    595     "Removes the read-only text property from the marked region.
    596   Use `set-region-read-only' to set this property."
    597     ;; See https://stackoverflow.com/questions/7410125
    598     (interactive "r")
    599     (with-silent-modifications
    600       (remove-text-properties begin end '(read-only t))))
    601 #+end_src
    602 ** Insert macro as Lisp
    603 From here: https://www.masteringemacs.org/article/keyboard-macros-are-misunderstood
    604 
    605 #+begin_src emacs-lisp
    606   (use-package kmacro
    607     :ensure nil ; included with Emacs
    608     :bind (:map kmacro-keymap
    609                 ("I" . kmacro-insert-macro))
    610     :config
    611     (defalias 'kmacro-insert-macro 'insert-kbd-macro)
    612 
    613     ;; Add advice to ignore errors on `kmacro-keyboard-macro-p`, it was
    614     ;; messing up because of some entry in `obarray`
    615     (advice-add #'kmacro-keyboard-macro-p :around (lambda (fun sym) "Ignore errors." (ignore-errors (funcall fun sym)))))
    616 #+end_src
    617 ** Show local help at point when idling
    618 #+begin_src emacs-lisp
    619   (defun za/echo-area-tooltips ()
    620     "Show tooltips in the echo area automatically for current buffer."
    621     (setq-local help-at-pt-display-when-idle t
    622                 help-at-pt-timer-delay 0)
    623     (help-at-pt-cancel-timer)
    624     (help-at-pt-set-timer))
    625 #+end_src
    626 
    627 ** Info manual functions
    628 For some reason, these things don't show up in the index:
    629 
    630 #+begin_src emacs-lisp
    631   (defun elisp-info (&optional node)
    632     "Read documentation for Elisp in the info system.
    633   With optional NODE, go directly to that node."
    634     (interactive)
    635     (info (format "(elisp)%s" (or node ""))))
    636 #+end_src
    637 
    638 Though I can also just use ~info-display-manual~.
    639 
    640 ** Radio
    641 Just a wrapper function to my radio script:
    642 
    643 #+begin_src emacs-lisp
    644   (defun radio ()
    645     "Play an internet radio"
    646     (interactive)
    647     (ansi-term "radio" "*radio*"))
    648 #+end_src
    649 
    650 ** no-op
    651 #+begin_src emacs-lisp
    652   (defun za/no-op (&rest args))
    653 #+end_src
    654 
    655 ** Syncthing
    656 Some functions to start/stop syncthing.
    657 #+begin_src emacs-lisp
    658   (defconst za/st-buffer-name "*syncthing*" "Buffer name for the syncthing process.")
    659   (defun za/st ()
    660     "Start syncthing"
    661     (interactive)
    662     (if (get-buffer-process za/st-buffer-name)
    663         (user-error "Syncthing is already running."))
    664     (async-shell-command "syncthing serve --no-browser" za/st-buffer-name))
    665 
    666   (defun za/st-kill ()
    667     "Stop syncthing"
    668     (interactive)
    669     (unless (get-buffer-process za/st-buffer-name)
    670       (user-error "Syncthing is not running."))
    671     (async-shell-command "syncthing cli operations shutdown"))
    672 #+end_src
    673 ** Replace typographic quotes
    674 #+begin_src emacs-lisp
    675   (defun za/replace-typographic-quotes ()
    676     "Replace typographic quotes with plain quotes"
    677     (interactive)
    678     (save-mark-and-excursion
    679       (goto-char (point-min))
    680       (while (re-search-forward (rx (any ?“ ?”)) nil 'noerror)
    681         (replace-match "\""))
    682       (goto-char (point-min))
    683       (while (re-search-forward (rx (any "‘" "’")) nil 'noerror)
    684         (replace-match "'"))))
    685 #+end_src
    686 ** Distraction-free on current buffer
    687 #+begin_src emacs-lisp
    688   (defun za/buffer-focus-no-distractions ()
    689     "Focus on this buffer"
    690     (interactive)
    691     (cond ((or (not (boundp 'za/no-distractions))
    692                (not za/no-distractions))
    693            (olivetti-mode 1)
    694            (line-number-mode 0)
    695            (display-line-numbers-mode 0)
    696            (window-configuration-to-register ?w)
    697            (delete-other-windows)
    698            (setq-local za/tmp/mode-line-format mode-line-format)
    699            (setq-local mode-line-format nil)
    700            (setq-local za/tmp/internal-border-width (frame-parameter nil 'internal-border-width))
    701            (set-frame-parameter nil 'internal-border-width 20)
    702            (setq-local za/no-distractions t)
    703            (message "Window configuration stored in register W"))
    704           (za/no-distractions
    705            (set-frame-parameter nil 'internal-border-width za/tmp/internal-border-width)
    706            (line-number-mode 0)
    707            (display-line-numbers-mode 1)
    708            (setq-local mode-line-format za/tmp/mode-line-format)
    709            (jump-to-register ?w)
    710            (olivetti-mode 0)
    711            (setq-local za/no-distractions nil))))
    712 #+end_src
    713 * Interface
    714 ** Theme
    715 Icons required for some parts of the doom theme:
    716 
    717 #+begin_src emacs-lisp
    718   (use-package all-the-icons)
    719 #+end_src
    720 
    721 Load Doom Emacs themes:
    722 
    723 #+begin_src emacs-lisp
    724   (use-package doom-themes
    725     :config
    726     ;; Global settings (defaults)
    727     (setq doom-themes-enable-bold t    ; if nil, bold is universally disabled
    728           doom-themes-enable-italic t) ; if nil, italics is universally disabled
    729 
    730     ;; Enable flashing mode-line on errors
    731     (doom-themes-visual-bell-config)
    732 
    733     ;; Corrects (and improves) org-mode's native fontification.
    734     (doom-themes-org-config))
    735 #+end_src
    736 
    737 Define the themes I want:
    738 
    739 #+begin_src emacs-lisp
    740   (defconst za/dark-theme-name 'doom-one "A symbol representing the name of the dark theme I use.")
    741   (defconst za/light-theme-name 'jokull "A symbol representing the name of the light theme I use.")
    742   ;; I used to use doom-acario-light before writing my own theme
    743 
    744   (defun za/dark-theme ()
    745     "Switch to dark theme"
    746     (interactive)
    747     (mapc #'disable-theme custom-enabled-themes)
    748     (load-theme za/dark-theme-name t)
    749     (add-hook 'pdf-view-mode-hook #'pdf-view-midnight-minor-mode))
    750 
    751   (defun za/light-theme ()
    752     "Switch to light theme"
    753     (interactive)
    754     (mapc #'disable-theme custom-enabled-themes)
    755     (load-theme za/light-theme-name t)
    756     (remove-hook 'pdf-view-mode-hook #'pdf-view-midnight-minor-mode))
    757 #+end_src
    758 
    759 Change theme depending on the current system theme.
    760 The way I check for dark mode is defined in 'dark-mode-p'; currently I use the presence of the ~/.config/dark-theme file to indicate when dark theme is set.
    761 I quote the call to ~file-exists-p~ because I want to evaluate it on-demand, not immediately.
    762 A function ending in '-p' is a predicate, i.e. returns true or false.
    763 If calling a function that's in a variable, you have to use 'funcall'.
    764 To evaluate a quoted form, use 'eval'.
    765 
    766 #+begin_src emacs-lisp
    767   (defun za/auto-select-theme (&rest _)
    768     "Automatically select dark/light theme based on presence of ~/.config/dark-theme"
    769     (let ((dark-mode-p '(file-exists-p "~/.config/dark-theme")))
    770       (if (eval dark-mode-p)
    771           (za/dark-theme)
    772         (za/light-theme))))
    773 
    774   (za/auto-select-theme)
    775 #+end_src
    776 
    777 ** Font
    778 I want Menlo, size 12:
    779 
    780 #+begin_src emacs-lisp
    781   (add-to-list 'default-frame-alist '(font . "Menlo-13"))
    782   (custom-set-faces
    783    ; height = pt * 10
    784    '(fixed-pitch ((t (:family "Menlo" :height 130))))
    785    '(variable-pitch ((t (:family "ETBembo" :height 140))))
    786    '(org-block ((t (:inherit fixed-pitch))))
    787    '(org-table ((t (:foreground "#0087af" :inherit fixed-pitch))))
    788    '(org-indent ((t (:inherit (org-hide fixed-pitch))))))
    789 
    790   (set-face-font 'fixed-pitch "Menlo-13")
    791   (set-face-font 'variable-pitch "ETBembo-14")
    792 #+end_src
    793 
    794 I like nicer list bullets:
    795 
    796 #+begin_src emacs-lisp
    797   (font-lock-add-keywords
    798    'org-mode
    799    `((,(rx bol (* blank) (group ?-) " ")  ; list regexp
    800       1                                   ; first match
    801       '(face nil display "•"))))          ; replace with bullet point, keep same face
    802 #+end_src
    803 ** Cursor
    804 The default box cursor isn't really accurate, because the cursor is actually between letters, not on a letter.
    805 So, I want a bar instead of a box:
    806 
    807 #+begin_src emacs-lisp
    808   (setq-default cursor-type '(bar . 4)
    809                 cursor-in-non-selected-windows 'hollow)
    810 #+end_src
    811 
    812 (I use ~setq-default~ here because cursor-type is automatically buffer-local when it's set)
    813 
    814 And enable cursorline:
    815 
    816 #+begin_src emacs-lisp
    817   (global-hl-line-mode)
    818 #+end_src
    819 
    820 And visualize tab characters by stretching the cursor:
    821 
    822 #+begin_src emacs-lisp
    823   (setq-default x-stretch-cursor t)
    824 #+end_src
    825 ** Matching parentheses
    826 Don't add a delay to show matching parenthesis.
    827 Must come before show-paren-mode enable.
    828 
    829 #+begin_src emacs-lisp
    830   (setq show-paren-delay 0)
    831 #+end_src
    832 
    833 Show matching parentheses:
    834 
    835 #+begin_src emacs-lisp
    836   (show-paren-mode t)
    837 #+end_src
    838 ** Line numbers
    839 Relative line numbers:
    840 
    841 #+begin_src emacs-lisp
    842   (setq display-line-numbers-type 'relative)
    843   (global-display-line-numbers-mode)
    844 #+end_src
    845 
    846 Function to hide them:
    847 
    848 #+begin_src emacs-lisp
    849   (defun za/hide-line-numbers ()
    850     "Hide line numbers"
    851     (display-line-numbers-mode 0))
    852 #+end_src
    853 Don't display them in specific modes.  For each of the modes in
    854 'mode-hooks', add a function to hide line numbers when the mode
    855 activates (which triggers the 'mode'-hook).
    856 
    857 #+begin_src emacs-lisp
    858   (let ((mode-hooks '(doc-view-mode-hook vterm-mode-hook mpc-status-mode-hook mpc-tagbrowser-mode-hook)))
    859     (mapc
    860      (lambda (mode-name)
    861        (add-hook mode-name #'za/hide-line-numbers))
    862      mode-hooks))
    863 #+end_src
    864 ** Modeline
    865 I want to show the time and date in the modeline:
    866 
    867 #+begin_src emacs-lisp
    868   (setq display-time-day-and-date t           ; also the date
    869         display-time-default-load-average nil ; don't show load average
    870         display-time-format "%I:%M%p %e %b (%a)")   ; "HR:MIN(AM/PM) day-of-month Month (Day)"
    871   (display-time-mode 1)                  ; enable time mode
    872 #+end_src
    873 
    874 And to set the modeline format:
    875 
    876 #+begin_src emacs-lisp
    877   (setq-default mode-line-format '("%e" mode-line-front-space mode-line-mule-info mode-line-client mode-line-modified mode-line-remote mode-line-frame-identification mode-line-buffer-identification "   " mode-line-position
    878                                    (vc-mode vc-mode)
    879                                    "  " mode-line-modes mode-line-misc-info mode-line-end-spaces))
    880 #+end_src
    881 
    882 I want to hide certain modes from the modeline.
    883 For that, ~delight~ is a useful package; unlike ~diminish~, it can also change the display of /major/ modes (~diminish~ only does minor modes).
    884 
    885 #+begin_src emacs-lisp
    886     (use-package delight
    887       :config
    888       (delight 'visual-line-mode " ↩" 'simple)
    889       (delight 'auto-revert-mode " AR" 'autorevert)
    890       (delight 'abbrev-mode " Abv" 'abbrev))
    891 #+end_src
    892 ** Transparent title bar
    893 #+begin_src emacs-lisp
    894   (add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
    895 #+end_src
    896 ** Frame title
    897 #+begin_src emacs-lisp
    898   (setopt frame-title-format "%F--%b-[%f]--%Z")
    899 #+end_src
    900 
    901 ** Tab bar
    902 Only show tab bar if there's more than 1 tab:
    903 
    904 #+begin_src emacs-lisp
    905   (setq tab-bar-show 1)
    906 #+end_src
    907 ** Buffer displaying
    908 
    909 So, this is a bit hard to grok. But basically the alist contains a
    910 regular expression to match a buffer name, then a list of functions to
    911 use in order for displaying the list, and then options for those functions (each of which is an alist).
    912 
    913 #+begin_src emacs-lisp
    914   (setq
    915    ;; Maximum number of side-windows to create on (left top right bottom)
    916    window-sides-slots '(0   ;; left
    917                         1   ;; top
    918                         3   ;; right
    919                         1 ) ;; bottom
    920 
    921    display-buffer-alist `(
    922                           ;; Right side
    923                           (,(rx (or "*Help*" (seq "*helpful " (* anything) "*")))
    924                            (display-buffer-reuse-window display-buffer-in-side-window)
    925                            (side . right)
    926                            (slot . -1)
    927                            (inhibit-same-window . t))
    928                           (,(rx "*Async Shell " (* anything) "*")
    929                            (display-buffer-reuse-window display-buffer-in-side-window)
    930                            (side . right)
    931                            (slot . 0)
    932                            (inhibit-same-window . t))
    933                           (,(rx "magit-process: " (* anything))
    934                            (display-buffer-reuse-window display-buffer-in-side-window)
    935                            (side . right)
    936                            (slot . 0)
    937                            (inhibit-same-window . t))
    938 
    939                           ;; Top side
    940                           (,(rx "*Info*")
    941                            (display-buffer-reuse-window display-buffer-in-side-window)
    942                            (side . top)
    943                            (slot . 0))
    944                           (,(rx "*Man " (* anything) "*")
    945                            (display-buffer-reuse-window display-buffer-in-side-window)
    946                            (side . top)
    947                            (slot . 0))
    948 
    949                           ;; Bottom
    950                           (,(rx "*Flycheck errors*")
    951                            (display-buffer-reuse-window display-buffer-in-side-window)
    952                            (side . bottom)
    953                            (slot . 0))))
    954 #+end_src
    955 
    956 And a way to toggle those side windows:
    957 
    958 #+begin_src emacs-lisp
    959   (bind-key "C-c W" #'window-toggle-side-windows)
    960 #+end_src
    961 
    962 ** Eldoc
    963 When editing Elisp and other supported major-modes, Eldoc will display useful information about the construct at point in the echo area.
    964 
    965 #+begin_src emacs-lisp
    966   (use-package eldoc
    967     :ensure nil ; installed with Emacs
    968     :delight
    969     :config
    970     (global-eldoc-mode 1))
    971 #+end_src
    972 
    973 ** Pulse line
    974 When you switch windows, Emacs can flash the cursor briefly to guide your eyes; I like that.
    975 Set some options for pulsing:
    976 
    977 #+begin_src emacs-lisp
    978   (setq pulse-iterations 10)
    979   (setq pulse-delay 0.05)
    980 #+end_src
    981 
    982 Define the pulse function:
    983 
    984 #+begin_src emacs-lisp
    985   (defun pulse-line (&rest _)
    986     "Pulse the current line."
    987     (pulse-momentary-highlight-one-line (point)))
    988 #+end_src
    989 
    990 Run it in certain cases: scrolling up/down, recentering, switching windows.
    991 'dolist' binds 'command' to each value in the list in turn, and runs the body.
    992 'advice-add' makes the pulse-line function run after 'command'.
    993 
    994 #+begin_src emacs-lisp
    995   (dolist (command '(scroll-up-command scroll-down-command recenter-top-bottom other-window))
    996     (advice-add command :after #'pulse-line))
    997 #+end_src
    998 
    999 And set the pulse color:
   1000 
   1001 #+begin_src emacs-lisp
   1002   (custom-set-faces '(pulse-highlight-start-face ((t (:background "CadetBlue2")))))
   1003 #+end_src
   1004 
   1005 ** Enable all commands
   1006 By default, Emacs disables some commands.
   1007 I want to have these enabled so I don't get a prompt whenever I try to use a disabled command.
   1008 
   1009 #+begin_src emacs-lisp
   1010   (setq disabled-command-function nil)
   1011 #+end_src
   1012 ** More extensive apropos
   1013 #+begin_src emacs-lisp
   1014   (setq apropos-do-all t)
   1015 #+end_src
   1016 ** Enable recursive minibuffers
   1017 #+begin_src emacs-lisp
   1018   (setq enable-recursive-minibuffers t
   1019         minibuffer-depth-indicate-mode t)
   1020 #+end_src
   1021 ** View webp and other formats
   1022 Emacs handles common image formats internally, but for stuff like webp, you need an external converter:
   1023 
   1024 #+begin_src emacs-lisp
   1025   (setq image-use-external-converter t)
   1026 #+end_src
   1027 
   1028 You also need imagemagick installed.
   1029 
   1030 ** Repeat mode: easy repeating of commands
   1031 #+begin_src emacs-lisp
   1032   (repeat-mode 1)
   1033 #+end_src
   1034 
   1035 ** Messages
   1036 Hide some messages I don't need.
   1037 
   1038 #+begin_src emacs-lisp
   1039   (recentf-mode)
   1040   (setq inhibit-startup-message t)
   1041 #+end_src
   1042 
   1043 ** Start buffer (dashboard)
   1044 #+begin_src emacs-lisp
   1045   (use-package dashboard
   1046     :custom
   1047     (dashboard-startup-banner 'logo)
   1048     (dashboard-items '((gtd-inbox-counts . 3)
   1049                        (syncthing-status . 3)
   1050                        (recents . 5)
   1051                        (bookmarks . 5)))
   1052 
   1053 
   1054     :bind (:map dashboard-mode-map
   1055                 ("ss" . za/st)
   1056                 ("sk" . za/st-kill)
   1057                 ("J" . org-clock-goto))
   1058     :config
   1059     (add-to-list 'dashboard-item-generators '(gtd-inbox-counts . dashboard-insert-gtd-inbox-counts))
   1060     (add-to-list 'dashboard-item-generators '(syncthing-status . dashboard-insert-syncthing-status))
   1061 
   1062     (defun za/quotes-from-my-site ()
   1063       (let* ((quotes-file (concat za/my-website-dir "content/quotes.md"))
   1064              ;; Reformat quotes for display in dashboard
   1065              (file-contents (with-temp-buffer
   1066                               (insert-file-contents quotes-file)
   1067                               (re-search-forward (rx bol "> "))
   1068                               (delete-region (point-min) (pos-bol))
   1069                               (goto-char (point-min))
   1070                               (save-excursion (replace-regexp (rx bol ">" (* " ") (? "\n")) ""))
   1071                               (save-excursion (replace-regexp (rx eol "\n") "  "))
   1072                               (buffer-substring-no-properties (point-min) (point-max)))))
   1073         ;; Split file into individual quotes
   1074         (split-string file-contents "  ---  ")))
   1075 
   1076     (defun za/quotes-manual ()
   1077       '("The Universe is under no obligation to make sense to you."
   1078         "I would like to die on Mars. Just not on impact."
   1079         "That's one small step for a man, one giant leap for mankind."
   1080         "We choose to go to the moon in this decade and do the other things, not because they are easy, but because they are hard, because that goal will serve to organize and measure the best of our energies and skills, because that challenge is one that we are willing to accept, one we are unwilling to postpone, and one which we intend to win."
   1081         "Space is for everybody. It’s not just for a few people in science or math, or for a select group of astronauts. That’s our new frontier out there, and it’s everybody’s business to know about space."
   1082         "On one side are those who believe space travel is difficult work, but who go for it anyway. On the other are those who believe caring for a goldfish is, and who don’t go after much of anything. Where we choose to seed ourselves on the spectrum of what’s possible is what will ultimately define the size of our lives."))
   1083 
   1084     ;; Have to redefine this, original one has wrong type
   1085     (defcustom dashboard-footer-messages
   1086     '("The one true editor, Emacs!"
   1087       "Who the hell uses VIM anyway? Go Evil!"
   1088       "Free as free speech, free as free Beer"
   1089       "Happy coding!"
   1090       "Vi Vi Vi, the editor of the beast"
   1091       "Welcome to the church of Emacs"
   1092       "While any text editor can save your files, only Emacs can save your soul"
   1093       "I showed you my source code, pls respond")
   1094     "A list of messages, one of which dashboard chooses to display."
   1095     :type '(repeat string)
   1096     :group 'dashboard)
   1097 
   1098     ;; Use my saved quotes in the dashboard (https://alex.balgavy.eu/quotes/)
   1099     (setopt dashboard-footer-messages
   1100           (let* ((quotes (if (boundp 'za/my-website-dir) (za/quotes-from-my-site) (za/quotes-manual))))
   1101             ;; Run each quote through fill-region for better display
   1102             (require 's)
   1103             (mapcar (lambda (quote-line)
   1104                       (with-temp-buffer
   1105                         (insert (s-trim quote-line))
   1106                         (fill-region (point-min) (point-max))
   1107                         (buffer-substring-no-properties (point-min) (point-max))))
   1108                     quotes))))
   1109 
   1110   (defun dashboard-insert-gtd-inbox-counts (list-size)
   1111     (require 'org-roam)
   1112     (let* ((lines-inbox (za/org-count-headlines-in-file 1 za/org-life-inbox))
   1113            (lines-mobile (if (boundp 'za/org-life-inbox-mobile) (za/org-count-headlines-in-file 1 za/org-life-inbox-mobile) 0))
   1114            (count-docs (length (directory-files za/org-life-doc-inbox nil (rx bos (not ?.)))))
   1115            (item-list))
   1116 
   1117       (when (> lines-inbox 0)
   1118         (push (list :name "Inbox" :count lines-inbox :file za/org-life-inbox) item-list))
   1119       (when (> lines-mobile 0)
   1120         (push (list :name "Mobile" :count lines-mobile :file za/org-life-inbox-mobile) item-list))
   1121       (when (> count-docs 0)
   1122         (push (list :name "Docs" :count count-docs :file za/org-life-doc-inbox) item-list))
   1123 
   1124       (dashboard-insert-section
   1125        ;; Widget title
   1126        "GTD:"
   1127        ;; list generated for dashboard
   1128        item-list
   1129        list-size
   1130        'gtd
   1131        "t"
   1132        ;; decide what to do when clicked ("el" is automatically assigned)
   1133        `(lambda (&rest _)
   1134           (message "%s" (find-file (plist-get ',el :file))))
   1135        ;; show how list is shown in dashboard ("el" is automatically assigned)
   1136        (format "%s: %s" (plist-get el :name) (plist-get el :count)))))
   1137 
   1138   (defun dashboard-insert-syncthing-status (list-size)
   1139     (when (and (get-buffer-process za/st-buffer-name)
   1140                (boundp 'za/syncthing-api-key))
   1141       (let* ((syncstatus (json-parse-string
   1142                           (shell-command-to-string
   1143                            (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/db/completion'" za/syncthing-api-key))))
   1144              (completion (gethash "completion" syncstatus))
   1145              (folders (json-parse-string
   1146                        (shell-command-to-string
   1147                         (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/stats/folder'" za/syncthing-api-key))
   1148                        :false-object nil
   1149                        :null-object nil))
   1150              (org-lastsync (format-time-string "%H:%M:%S (%F)" (date-to-time (gethash "lastScan" (gethash "lifeorg" folders)))))
   1151              (devices (json-parse-string
   1152                        (shell-command-to-string
   1153                         (format "curl -sH 'Authorization: Bearer %s' 'http://localhost:8384/rest/system/connections'" za/syncthing-api-key))
   1154                        :object-type 'alist
   1155                        :false-object nil
   1156                        :null-object nil))
   1157              (connected-devices (length (seq-filter
   1158                                          (lambda (a)
   1159                                            (alist-get 'connected (cdr a))) (alist-get 'connections devices))))
   1160              (item-list `(,(format "Completion: %s%%" completion)
   1161                           ,(format "Connected devices: %s" connected-devices)
   1162                           ,(format "Org last sync: %s" org-lastsync))))
   1163 
   1164         (dashboard-insert-section
   1165          ;; Widget title
   1166          "Syncthing:"
   1167          ;; list generated for dashboard
   1168          item-list
   1169          list-size
   1170          'syncthing-status
   1171          ;; shortcut key for section
   1172          nil
   1173          ;; when clicked
   1174          (lambda (&rest _) ())
   1175          ;; show how list is shown in dashboard ("el" is automatically assigned)
   1176          (format "%s" el)))))
   1177 
   1178   (dashboard-setup-startup-hook)
   1179   (setq initial-buffer-choice (lambda () (get-buffer-create "*dashboard*")))
   1180 #+end_src
   1181 
   1182 ** Scrolling
   1183 #+begin_src emacs-lisp
   1184   (setopt scroll-step 1)
   1185   ;; Marker distance from center
   1186   (setopt scroll-conservatively 100000)
   1187   ;; Keep screen position on scroll
   1188   (setopt scroll-preserve-screen-position 1)
   1189   ;; Start scrolling when marker at top/bottom
   1190   (setopt scroll-margin 0)
   1191 
   1192   ;; Mouse scrolls 1 line at a time
   1193   (setopt mouse-wheel-scroll-amount '(1))
   1194 
   1195   ;; On a long mouse scroll keep scrolling by 1 line
   1196   (setq mouse-wheel-progressive-speed nil)
   1197 
   1198   ;; Enable pixel scroll precision mode
   1199   (unless (version< emacs-version "29")
   1200     (pixel-scroll-precision-mode))
   1201 
   1202   ;; Speed up cursor movement.
   1203   ;; https://emacs.stackexchange.com/questions/28736/emacs-pointcursor-movement-lag/28746
   1204   (setopt auto-window-vscroll nil)
   1205 #+end_src
   1206 * General packages
   1207 ** hyperbole
   1208 #+begin_src emacs-lisp
   1209   (use-package hyperbole
   1210     :config
   1211     (defib za/ib-cdmidev ()
   1212       "CDMIDEV links"
   1213       (if (or (looking-at "CDMI\\(?:DEV\\|OPS\\)-[0-9]+")
   1214               (save-excursion
   1215                 (backward-word-strictly)
   1216                 (looking-at "CDMI\\(?:DEV\\|OPS\\)-[0-9]+"))
   1217               (save-excursion
   1218                 (backward-word-strictly 2)
   1219                 (looking-at "CDMI\\(?:DEV\\|OPS\\)-[0-9]+")))
   1220           (let ((work-item (apply #'buffer-substring-no-properties (seq-take (match-data) 2))))
   1221             (ibut:label-set work-item)
   1222             (hact 'www-url (concat "https://csde.esa.int/jira/browse/" work-item))))))
   1223   (hyperbole-mode 1)
   1224   (hkey-ace-window-setup)
   1225 #+end_src
   1226 ** which-key
   1227 Minor mode for Emacs that displays the key bindings following your currently entered incomplete command (a prefix) in a popup.
   1228 
   1229 #+BEGIN_SRC emacs-lisp
   1230   (use-package which-key
   1231     :delight
   1232     :config
   1233     (which-key-mode))
   1234 #+end_src
   1235 
   1236 ** counsel + ivy + swiper + prescient
   1237 Better incremental completion and selection narrowing.
   1238 And a bunch more.
   1239 Generally makes for nicer interactivity, like ido mode on steroids.
   1240 Switched to this from Helm, it's more lightweight.
   1241 
   1242 *** ivy: generic completion mechanism
   1243 #+begin_src emacs-lisp
   1244   (use-package ivy
   1245     :delight
   1246     :custom
   1247     (ivy-use-virtual-buffers t "extend searching to bookmarks")
   1248     (ivy-height 20 "set height of the ivy window")
   1249     (ivy-count-format "(%d/%d) " "count format, from the ivy help page")
   1250     (ivy-display-style 'fancy)
   1251     (ivy-format-function 'ivy-format-function-line)
   1252     (ivy-use-selectable-prompt t "to let me select exactly what I'm typing as a candidate")
   1253 
   1254     :bind (("C-x b" . ivy-switch-buffer)
   1255            ("C-c v" . ivy-push-view)
   1256            ("C-c V" . ivy-pop-view)
   1257 
   1258            ;; accidentally pressing shift-space deletes input, because
   1259            ;; by default, shift-space is bound to
   1260            ;; ~ivy-restrict-to-matches~ in the ivy minibuffer.
   1261            :map ivy-minibuffer-map
   1262            ("S-SPC" . (lambda () (interactive) (insert ?\s)))
   1263            ("<backtab>" . ivy-restrict-to-matches))
   1264     :config
   1265     (ivy-add-actions
   1266      'counsel-dired
   1267      '(("f" (lambda (dir) (counsel-fzf nil dir)) "Fzf in directory")
   1268        ("g" (lambda (dir) (counsel-ag nil dir)) "Ag in directory")))
   1269     (ivy-add-actions
   1270      'dired
   1271      '(("f" (lambda (dir) (ivy-exit-with-action (counsel-fzf nil dir))) "Fzf in directory")
   1272        ("g" (lambda (dir) (ivy-exit-with-action (counsel-ag nil dir))) "Ag in directory")))
   1273     (ivy-add-actions
   1274      'counsel-describe-function
   1275      '(("d" (lambda (fun) (ivy-exit-with-action (edebug-instrument-function (intern fun)))) "Edebug instrument function")))
   1276     (ivy-mode)
   1277 
   1278     (defun edit-script ()
   1279       "Edit a file in ~/.scripts/"
   1280       (interactive)
   1281       (let ((input (ivy--input)))
   1282         (ivy-quit-and-run (counsel-file-jump nil "~/.scripts/"))))
   1283 
   1284     (defun edit-config ()
   1285       "Edit a file in ~/.dotfiles/"
   1286       (interactive)
   1287       (let ((input (ivy--input)))
   1288         (ivy-quit-and-run (counsel-file-jump nil "~/.dotfiles/")))))
   1289 #+end_src
   1290 
   1291 *** counsel: collection of common Emacs commands enhanced using ivy
   1292 #+begin_src emacs-lisp
   1293   (use-package counsel
   1294     :demand
   1295     :delight
   1296     :config
   1297     (counsel-mode)
   1298     :bind (("M-x" . counsel-M-x)
   1299            ("C-x C-f" . counsel-find-file)
   1300            ("M-y" . counsel-yank-pop)
   1301            ("C-c c" . counsel-compile)
   1302            ("M-s g" . counsel-rg)
   1303            ("M-s f" . counsel-fzf)
   1304            ("C-c b" . counsel-bookmark)
   1305            ("C-c p" . counsel-recentf)
   1306            ("C-c o" . counsel-outline)
   1307            ("C-h f" . counsel-describe-function)
   1308            ("C-h v" . counsel-describe-variable)
   1309            ("C-h o" . counsel-describe-symbol)
   1310            ("C-c g j" . counsel-org-agenda-headlines)))
   1311 #+end_src
   1312 *** swiper: search enhanced using ivy
   1313 #+begin_src emacs-lisp
   1314   (use-package swiper
   1315     :bind (("C-s" . swiper-isearch)
   1316            ("C-r" . swiper-isearch-backward)))
   1317 #+end_src
   1318 *** prescient: scoring system for M-x
   1319 #+begin_src emacs-lisp
   1320   (use-package prescient
   1321     :config (prescient-persist-mode))
   1322 
   1323   (use-package ivy-prescient
   1324     :after counsel
   1325     :custom (ivy-prescient-retain-classic-highlighting t)
   1326     :config (ivy-prescient-mode))
   1327 #+end_src
   1328 
   1329 *** ivy-posframe: ivy in a popup
   1330 I like having ivy in a popup.
   1331 Problem: posframe does not work if emacs is too old and on macos.
   1332 See here: https://github.com/tumashu/posframe/issues/30
   1333 On Mac, ~brew install --HEAD emacs~ doesn't work either.
   1334 Solution: ~brew tap daviderestivo/emacs-head && brew install emacs-head@28 --with-cocoa~
   1335 
   1336 #+begin_src emacs-lisp
   1337   (if (and (version< emacs-version "28") (equal system-type 'darwin))
   1338       (message "ivy-posframe won't work properly, run `brew install daviderestivo/emacs-head/emacs-head@28 --with-cocoa`")
   1339     (use-package ivy-posframe
   1340       :delight
   1341       :custom
   1342       (ivy-posframe-display-functions-alist '((t . ivy-posframe-display-at-frame-center)))
   1343       (ivy-posframe-parameters
   1344        '((left-fringe . 8)
   1345          (right-fringe . 8)))
   1346       (ivy-posframe-border-width 3)
   1347       (ivy-truncate-lines nil) ;; otherwise the cursor gets hidden by long lines in posframe
   1348       :custom-face
   1349       (ivy-posframe-border ((t (:inherit mode-line-inactive))))
   1350       :config
   1351       (ivy-posframe-mode 1)))
   1352 #+end_src
   1353 
   1354 [[https://github.com/tumashu/ivy-posframe/issues/123][See here]] for cursor going offscreen in the posframe. Currently 'solved' with ~ivy-truncate-lines~ nil.
   1355 
   1356 ** DISABLED vertico + consult + marginalia + embark + posframe + prescient
   1357 Alternative to counsel/ivy/swiper, will probably switch to this at some point.
   1358 [[https://old.reddit.com/r/emacs/comments/qfrxgb/using_emacs_episode_80_vertico_marginalia_consult/hi6mfh7/][Here]] is a good comparison.
   1359 
   1360 A [[https://old.reddit.com/r/emacs/comments/11lqkbo/weekly_tips_tricks_c_thread/jbe06qv/][comment here to follow]] when I switch to vertico.
   1361 #+begin_src emacs-lisp :tangle no
   1362   (dolist (pack '(vertico consult marginalia embark vertico-posframe vertico-prescient))
   1363     (unless (package-installed-p pack)
   1364       (package-install pack))
   1365     (require pack))
   1366 
   1367   (vertico-mode 1)
   1368   (vertico-posframe-mode 1)
   1369   (marginalia-mode 1)
   1370   (vertico-prescient-mode 1)
   1371   (setq completion-styles '(basic substring partial-completion flex))
   1372 
   1373   (global-set-key (kbd "M-o") #'embark-act)
   1374   (global-set-key (kbd "C-s") #'consult-line)
   1375 
   1376 #+end_src
   1377 ** company: completion mechanism
   1378 #+begin_src emacs-lisp
   1379   (use-package company)
   1380 #+end_src
   1381 
   1382 ** wgrep: writable grep
   1383 #+begin_src emacs-lisp
   1384   (use-package wgrep)
   1385 #+end_src
   1386 ** avy: jump to any position
   1387 This lets me jump to any position in Emacs rather quickly, sometimes it's useful.
   1388 ~avy-goto-char-timer~ lets me type a part of the text before avy kicks in.
   1389 
   1390 #+begin_src emacs-lisp
   1391   (use-package avy
   1392     :custom
   1393     (avy-single-candidate-jump nil "Often I want to perform an action, never jump automatically")
   1394     :bind
   1395     (("C-:" . avy-goto-char-timer)))
   1396 #+end_src
   1397 
   1398 ** calendar
   1399 #+begin_src emacs-lisp
   1400   (use-package calendar
   1401     :ensure nil ; comes with Emacs
   1402     :custom
   1403     (calendar-week-start-day 1))
   1404 #+end_src
   1405 ** calfw: graphical calendar
   1406 Basically provides a way to show the org agenda as a standard GUI calendar app would.
   1407 
   1408 #+begin_src emacs-lisp
   1409   (use-package calfw
   1410     :config
   1411     (use-package calfw-org)
   1412     :custom
   1413     (cfw:org-overwrite-default-keybinding t))
   1414 #+end_src
   1415 
   1416 ** vanish: hide parts of the file
   1417 #+begin_src emacs-lisp
   1418   (use-package vanish
   1419     :init
   1420     (za/package-vc-install :repo "thezeroalpha/vanish.el" :rev "develop")
   1421     (require 'vanish)
   1422     :ensure nil
   1423     :bind (:map vanish-mode-map
   1424                 ("C-c q h h" . vanish-hide-dwim)
   1425                 ("C-c q h u r" . vanish-show-all-regions)
   1426                 ("C-c q h u e" . vanish-elt-unhide)
   1427                 ("C-c q h u u" . vanish-show-all)))
   1428 #+end_src
   1429 ** magit
   1430 #+begin_src emacs-lisp
   1431   (use-package magit)
   1432 #+end_src
   1433 ** vterm
   1434 Emacs has a bunch of built-in terminal emulators.
   1435 And they all suck.
   1436 (OK not really, eshell is alright, but not for interactive terminal programs like newsboat/neomutt)
   1437 
   1438 Also use emacsclient inside vterm as an editor, because that'll open documents in the existing Emacs session.
   1439 And I'm not gonna be a heretic and open Vim inside of Emacs.
   1440 
   1441 #+begin_src emacs-lisp
   1442   (use-package vterm
   1443     :hook
   1444     (vterm-mode . (lambda () (unless server-process (server-start))))
   1445     :bind (("C-c t" . switch-to-vterm))
   1446     :config
   1447     (defun switch-to-vterm ()
   1448       "Switch to a running vterm, or start one and switch to it."
   1449       (interactive)
   1450       (if (get-buffer vterm-buffer-name)
   1451           (switch-to-buffer vterm-buffer-name)
   1452         (vterm))))
   1453 #+end_src
   1454 ** sr-speedbar
   1455 Make speed bar show in the current frame.
   1456 
   1457 #+begin_src emacs-lisp
   1458   (use-package sr-speedbar
   1459     :bind (("C-c F" . za/jump-to-speedbar-or-open)
   1460            :map speedbar-mode-map
   1461            ("q" . sr-speedbar-close))
   1462     :custom
   1463     (sr-speedbar-right-side nil)
   1464 
   1465     :config
   1466     (defun za/jump-to-speedbar-or-open ()
   1467       "Open a speedbar or jump to it if already open."
   1468       (interactive)
   1469       (if (or (not (boundp 'sr-speedbar-exist-p))
   1470               (not (sr-speedbar-exist-p)))
   1471           (sr-speedbar-open))
   1472       (sr-speedbar-select-window)))
   1473 #+end_src
   1474 ** expand-region
   1475 Expand the selected region semantically.
   1476 
   1477 #+begin_src emacs-lisp
   1478   (use-package expand-region
   1479     :bind ("C-=" . er/expand-region))
   1480 #+end_src
   1481 ** flycheck
   1482 Install flycheck:
   1483 
   1484 #+begin_src emacs-lisp
   1485   (use-package flycheck)
   1486 #+end_src
   1487 ** rainbow-mode: visualise hex colors
   1488 'rainbow-mode' lets you visualise hex colors:
   1489 
   1490 #+begin_src emacs-lisp
   1491   (use-package rainbow-mode)
   1492 #+end_src
   1493 ** hl-todo: highlight TODO keywords
   1494 I want to highlight TODO keywords in comments:
   1495 
   1496 #+begin_src emacs-lisp
   1497   (use-package hl-todo
   1498     :custom-face
   1499     (hl-todo ((t (:inherit hl-todo :underline t))))
   1500     :custom
   1501     (hl-todo-keyword-faces '(("TODO"   . "#ff7060")
   1502                              ("FIXME"  . "#caa000")))
   1503     :config
   1504     (global-hl-todo-mode t))
   1505 #+end_src
   1506 ** undo-tree
   1507 Sometimes it's better to look at undo history as a tree:
   1508 
   1509 #+begin_src emacs-lisp
   1510   (use-package undo-tree
   1511     :delight
   1512     :custom
   1513     (undo-tree-history-directory-alist
   1514      (progn (let ((undo-tree-dir (concat user-emacs-directory "undo-tree/")))
   1515               (unless (file-directory-p undo-tree-dir) (make-directory undo-tree-dir))
   1516               `(("." . ,undo-tree-dir)))))
   1517 
   1518     :config
   1519     (global-undo-tree-mode))
   1520 #+end_src
   1521 
   1522 *** TODO undo tree dir should be configurable
   1523 ** eglot
   1524 A good LSP plugin.
   1525 
   1526 #+begin_src emacs-lisp
   1527   (use-package eglot)
   1528 #+end_src
   1529 ** crdt
   1530 Collaborative editing in Emacs:
   1531 
   1532 #+begin_src emacs-lisp
   1533   (use-package crdt)
   1534 #+end_src
   1535 ** git gutter
   1536 General git gutter:
   1537 
   1538 #+begin_src emacs-lisp
   1539   (use-package git-gutter
   1540     :bind (("C-c d n" . git-gutter:next-hunk)
   1541            ("C-c d p" . git-gutter:previous-hunk))
   1542     :config
   1543     (global-git-gutter-mode 1))
   1544 #+end_src
   1545 ** keycast
   1546 In case I want to show what keys I'm pressing.
   1547 
   1548 #+begin_src emacs-lisp
   1549   (use-package keycast)
   1550 #+end_src
   1551 ** ace-window: better window switching
   1552 Window switching with ~other-window~ sucks when I have more than 2 windows open. Too much cognitive load.
   1553 This lets me select a window to jump to using a single key, sort of like ~avy~.
   1554 
   1555 #+begin_src emacs-lisp
   1556   (use-package ace-window
   1557     :custom
   1558     (aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l) "I prefer using home-row keys instead of numbers")
   1559 
   1560     :custom-face
   1561     ;; I want something a little more contrasty
   1562     (aw-leading-char-face ((t (:inherit font-lock-keyword-face :height 2.0))))
   1563 
   1564     :bind ("M-O" . ace-window))
   1565 #+end_src
   1566 ** decide-mode for dice rolling
   1567 #+begin_src emacs-lisp :tangle no
   1568   (use-package decide
   1569     :init (za/package-vc-install :repo "lifelike/decide-mode" :name "decide")
   1570     :ensure nil
   1571     :bind ("C-c q ?" . decide-mode))
   1572 #+end_src
   1573 
   1574 ** try: try out different packages
   1575 #+begin_src emacs-lisp
   1576   (use-package try)
   1577 #+end_src
   1578 ** dumb-jump
   1579 "jump to definition" package, minimal configuration with no stored indexes.
   1580 Uses The Silver Searcher ag, ripgrep rg, or grep to find potential definitions of a function or variable under point.
   1581 
   1582 #+begin_src emacs-lisp
   1583   (use-package dumb-jump)
   1584 #+end_src
   1585 
   1586 Enable xref backend:
   1587 
   1588 #+begin_src emacs-lisp
   1589   (add-hook 'xref-backend-functions #'dumb-jump-xref-activate)
   1590   (setq xref-show-definitions-function #'xref-show-definitions-completing-read)
   1591 #+end_src
   1592 ** DISABLED command-log-mode
   1593 Simple real-time logger of commands.
   1594 
   1595 #+begin_src emacs-lisp :tangle no
   1596   (use-package command-log-mode)
   1597 #+end_src
   1598 ** package-lint
   1599 Linter for the metadata in Emacs Lisp files which are intended to be packages.
   1600 
   1601 #+begin_src emacs-lisp
   1602   (use-package package-lint)
   1603   (use-package flycheck-package)
   1604   (eval-after-load 'flycheck
   1605     '(flycheck-package-setup))
   1606 #+end_src
   1607 ** prism: change color of text depending on depth
   1608 Prism changes the color of text depending on their depth. Makes it easier to see where something is at a glance.
   1609 
   1610 #+begin_src emacs-lisp
   1611   (use-package prism)
   1612 #+end_src
   1613 ** olivetti: distraction-free writing
   1614 #+begin_src emacs-lisp
   1615   (use-package olivetti
   1616     :diminish)
   1617 #+end_src
   1618 ** nov.el: EPUB support
   1619 #+begin_src emacs-lisp
   1620   (use-package nov)
   1621   (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode))
   1622 #+end_src
   1623 ** god-mode: reduce the need to hold down modifier keys
   1624 - All commands are assumed to use the control modifier (C-) unless otherwise indicated.
   1625 - g is used to indicate the meta modifier
   1626 - G is used to indicate both the control and meta modifiers
   1627 #+begin_src emacs-lisp
   1628   (use-package god-mode
   1629     :bind
   1630     (("s-<escape>" . god-mode-all)
   1631      :map god-local-mode-map
   1632      ("z" . repeat)
   1633      ("i" . god-local-mode))
   1634     :hook    (post-command . za/god-mode-update-mode-line)
   1635     :config
   1636     (defun za/god-mode-update-mode-line ()
   1637       "Update the color of the modeline depending on god-mode."
   1638       (cond (god-local-mode
   1639              (set-face-attribute 'mode-line nil :background "#770085"))
   1640             (t
   1641              (let* ((current-theme (car custom-enabled-themes))
   1642                      (theme-settings (get current-theme 'theme-settings)))
   1643                 (dolist (theme-setting theme-settings)
   1644                   (if (and (eq (car theme-setting) 'theme-face)
   1645                            (eq (cadr theme-setting) 'mode-line))
   1646                       (let* ((face-def (caar (last theme-setting)))
   1647                              (properties (car (last face-def)))
   1648                              (bg (plist-get properties :background)))
   1649                         (set-face-attribute 'mode-line nil :background bg)))))))))
   1650 #+end_src
   1651 ** devil: alternative to god-mode that uses a comma
   1652 #+begin_src emacs-lisp
   1653   (use-package devil
   1654     :init
   1655     (za/package-vc-install :repo "susam/devil")
   1656     (require 'devil)
   1657     :custom
   1658     (devil-lighter " \u272A")
   1659     (devil-prompt "\u272A %t")
   1660     :config (global-devil-mode)
   1661     :bind ("C-," . global-devil-mode))
   1662 #+end_src
   1663 ** academic-phrases
   1664 Gives ideas for phrases to use in academic writing.
   1665 #+begin_src emacs-lisp
   1666   (use-package academic-phrases)
   1667 #+end_src
   1668 ** ediff
   1669 #+begin_src emacs-lisp
   1670   (use-package ediff
   1671     :custom
   1672     ((ediff-keep-variants nil "Prompt to remove unmodifid buffers after session")
   1673      (ediff-make-buffers-readonly-at-startup nil "Don't make all buffers read-only at startup")
   1674      (ediff-show-clashes-only t "Only show diff regions where both buffers disagree with ancestor")
   1675      (ediff-split-window-function 'split-window-horizontally "I want long vertical side-by-side windows")
   1676      (ediff-window-setup-function 'ediff-setup-windows-plain "Everything in one frame please")))
   1677 #+end_src
   1678 ** highlight-indent-guides
   1679 #+begin_src emacs-lisp
   1680   (use-package highlight-indent-guides
   1681     :hook (yaml-mode . highlight-indent-guides-mode)
   1682     :custom
   1683     ((highlight-indent-guides-method 'character))
   1684     :custom-face
   1685     (highlight-indent-guides-character-face ((t (:foreground "#adadad")))))
   1686 #+end_src
   1687 ** cc-avy
   1688 #+begin_src emacs-lisp
   1689   (use-package cc-avy
   1690     :ensure nil ; local
   1691     :bind ("C-M-:" . cc/avy-menu))
   1692 #+end_src
   1693 ** annotate
   1694 #+begin_src emacs-lisp
   1695   (use-package annotate
   1696     :custom (annotate-annotation-position-policy :margin)
   1697     :config
   1698     (defun za/annotate-initialize-extra-hooks ()
   1699       (add-hook 'after-save-hook #'annotate-save-annotations t t))
   1700     (defun za/annotate-shutdown-extra-hooks ()
   1701       (remove-hook 'after-save-hook #'annotate-save-annotations t))
   1702     (advice-add 'annotate-initialize :after #'za/annotate-initialize-extra-hooks)
   1703     (advice-add 'annotate-shutdown :after #'za/annotate-shutdown-extra-hooks))
   1704 
   1705 #+end_src
   1706 ** org-remark
   1707 #+begin_src emacs-lisp
   1708   (use-package org-remark
   1709     :bind (;; :bind keyword also implicitly defers org-remark itself.
   1710            ;; Keybindings before :map is set for global-map. Adjust the keybinds
   1711            ;; as you see fit.
   1712            :map org-mode-map
   1713            ("C-c C-/ m" . org-remark-mark-strong-yellow)
   1714            ("C-c C-/ l" . org-remark-mark-line)
   1715            :map org-remark-mode-map
   1716            ("C-c C-/ o" . org-remark-open)
   1717            ("C-c C-/ ]" . org-remark-view-next)
   1718            ("C-c C-/ [" . org-remark-view-prev)
   1719            ("C-c C-/ r" . org-remark-remove)
   1720            ("C-c C-/ d" . org-remark-delete)))
   1721 
   1722   (use-package org-remark-global-tracking
   1723     ;; It is recommended that `org-remark-global-tracking-mode' be
   1724     ;; enabled when Emacs initializes. You can set it in
   1725     ;; `after-init-hook'.
   1726     :hook after-init
   1727     :after org-remark
   1728     :ensure nil  ;; already installed in org-remark
   1729     :config
   1730     ;; Selectively keep or comment out the following if you want to use
   1731     ;; extensions for Info-mode, EWW, and NOV.el (EPUB) respectively.
   1732     ;; (use-package org-remark-info :after info :config (org-remark-info-mode +1))
   1733     ;; (use-package org-remark-eww  :after eww  :config (org-remark-eww-mode +1))
   1734     ;; (use-package org-remark-nov  :after nov  :config (org-remark-nov-mode +1))
   1735 
   1736     ;; Custom pens
   1737     (org-remark-create "strong-yellow"
   1738                      '(:background "yellow")
   1739                      '(CATEGORY "important")))
   1740 #+end_src
   1741 ** yasnippet
   1742 #+begin_src emacs-lisp
   1743   (use-package yasnippet
   1744     :config (yas-global-mode)
   1745     :delight)
   1746 #+end_src
   1747 * Mode/language specific packages
   1748 ** Org
   1749 *** Custom functions
   1750 **** Get number of headlines in a file
   1751 #+begin_src emacs-lisp
   1752   (defun za/org-count-headlines-in-file (level filename)
   1753     "Count number of level LEVEL headlines in FILENAME. If LEVEL is 0, count all."
   1754     (let ((headline-str (cond ((zerop level) "^\*+")
   1755                               (t (format "^%s " (apply 'concat (make-list level "\\*")))))))
   1756       (save-mark-and-excursion
   1757         (with-temp-buffer
   1758           (insert-file-contents filename)
   1759           (count-matches headline-str (point-min) (point-max))))))
   1760 #+end_src
   1761 
   1762 **** Yank URL
   1763 #+begin_src emacs-lisp
   1764   (defun org-yank-link-url ()
   1765     (interactive)
   1766     (kill-new (org-element-property :raw-link (org-element-context)))
   1767     (message "Link copied to clipboard"))
   1768 #+end_src
   1769 *** Installation
   1770 Install Org and require additional components that I use.
   1771 
   1772 #+begin_src emacs-lisp
   1773   (use-package org
   1774     :custom
   1775     (org-outline-path-complete-in-steps nil "Complete path all at once (needed for completion frameworks")
   1776     (org-format-latex-options (plist-put org-format-latex-options :scale 2.0) "Larger latex previews")
   1777     (org-goto-interface 'outline-path-completion "Use outline path completion for org-goto, instead of its weird interface")
   1778     (org-insert-heading-respect-content t "Insert headings after current subtree")
   1779     (org-clock-report-include-clocking-task t "Include currently active task in clocktable")
   1780     (org-id-link-to-org-use-id 'create-if-interactive "If org-store-link is called directly, create an ID.")
   1781     (org-clock-mode-line-total 'today)
   1782     (org-return-follows-link t "Easier link following. Actual enter is still possible with ~C-q C-j~.")
   1783     (org-hide-emphasis-markers t "Don't show italics/bold markers")
   1784     (org-babel-python-command "python3")
   1785     (org-confirm-babel-evaluate nil)
   1786     (org-file-apps '((auto-mode . emacs)
   1787                      (directory . emacs)
   1788                      ("\\.mm\\'" . default)
   1789                      ("\\.x?html?\\'" . default)
   1790                      ("\\.pdf\\'" . emacs)))
   1791     (org-link-elisp-confirm-function #'y-or-n-p)
   1792     (org-link-elisp-skip-confirm-regexp "^org-noter$")
   1793     (org-clock-sound (concat user-emacs-directory "notification.wav"))
   1794     (org-export-backends '(ascii html icalendar latex md odt org pandoc jira))
   1795     (org-catch-invisible-edits 'show-and-error
   1796                                "Sometimes when text is folded away, I might accidentally edit text inside of it. This option prevents that. I wanted to do 'smart', but that has a 'fixme' so it might change in the future...Instead, show what's being edited, but don't perform the edit.")
   1797     (org-src-tab-acts-natively t "a tab in a code block indents the code as it should")
   1798     (org-attach-store-link-p 'attached)
   1799     (org-attach-archive-delete 'query)
   1800     (org-archive-subtree-add-inherited-tags t)
   1801     (org-stuck-projects '("/PROJ"
   1802                           ("NEXT" "STARTED")
   1803                           nil nil)
   1804                         "List projects that are stuck (don't have a next action)")
   1805     (org-tag-alist (let ((za/org-tag-energy-levels
   1806                           '((:startgroup)
   1807                             ("focused" . ?f)
   1808                             ("quick" . ?q)
   1809                             ("errand" . ?e)
   1810                             ("think" . ?t)
   1811                             ("call" . ?c)
   1812                             (:endgroup)))
   1813                          (za/org-tag-1-3-5
   1814                           '(; 1-3-5 tagging
   1815                             (:startgroup)
   1816                             ("_1" . ?1) ; 1 big task, 3-4 hrs
   1817                             ("_3" . ?3) ; 3 medium tasks, 1-2 hrs
   1818                             ("_5" . ?5) ; 5 small tasks, 30min-1hr
   1819                             (:endgroup))))
   1820                      `(,@za/org-tag-contexts ,@za/org-tag-energy-levels ,@za/org-tag-1-3-5)))
   1821 
   1822     :bind (("C-c a" . org-agenda)
   1823            ("C-c n" . org-capture)
   1824            ("C-c l" . org-store-link)
   1825            :map org-mode-map
   1826            ("C-M-<return>" . org-insert-todo-heading)
   1827            ("C-c M-y" . org-yank-link-url)
   1828            ("C-c N" . org-noter)
   1829            ("C-M-i" . completion-at-point)
   1830            ("C-c SPC" . org-table-blank-field)
   1831            ("C-c C-w" . za/org-refile-wrapper))
   1832     :hook ((org-mode . abbrev-mode)
   1833            (org-mode . za/echo-area-tooltips)
   1834            (org-mode . org-superstar-mode)
   1835            (org-mode . org-indent-mode)
   1836            (org-mode . za/settings-on-org-mode)
   1837            (org-mode . org-pretty-table-mode)
   1838            (org-mode . variable-pitch-mode)
   1839            (ediff-prepare-buffer . org-show-all))
   1840     :config
   1841     (za/package-vc-install :repo "Fuco1/org-pretty-table")
   1842     (require 'org-pretty-table)
   1843     (delight 'org-pretty-table nil)
   1844 
   1845 
   1846     (za/package-vc-install :repo "https://git.sr.ht/~bzg/org-contrib" :load "lisp/")
   1847     (require 'org-contrib)
   1848     (require 'org-checklist)
   1849     (delight 'org-indent-mode nil 'org-indent)
   1850     (defun za/settings-on-org-mode ()
   1851       "Settings on enabling org mode"
   1852       (za/toggle-wrap t))
   1853 
   1854     (defcustom za/org-inline-images-desired-screen-proportion (/ (float 3) 4)
   1855       "Percentage of the window (as a float) that Org inline images should take up."
   1856       :type 'float)
   1857 
   1858     (defun za/org-display-inline-images-set-width (&rest _)
   1859       "Set `org-image-actual-width` dynamically before displaying images."
   1860       (if (window-system)
   1861           (let* ((total-width (window-pixel-width))
   1862                  (image-width (round (* total-width za/org-inline-images-desired-screen-proportion))))
   1863             (setq-local org-image-actual-width image-width))))
   1864 
   1865     (advice-add 'org-display-inline-images :before #'za/org-display-inline-images-set-width)
   1866 
   1867     (defun za/org-attach-tag (old/org-attach-tag &rest args)
   1868       "Wraps :around org-attach-tag (as OLD/ORG-ATTACH-TAG) with ARGS.
   1869   When inside capture for org-roam, attaching fails at
   1870   org-attach-tag. This function prevents that error interrupting
   1871   org-attach."
   1872       (if ; there's no heading
   1873           (not (org-element-lineage (org-element-at-point)
   1874                                     '(headline inlinetask)
   1875                                     'include-self))
   1876           nil ; there's no point attaching a tag
   1877                                           ; otherwise, normal attach
   1878         (apply old/org-attach-tag args)))
   1879 
   1880     (advice-add #'org-attach-tag :around #'za/org-attach-tag)
   1881     (defun za/org-clear-1-3-5 ()
   1882       "Clears the _1/_3/_5 daily tags from all antries."
   1883       (interactive)
   1884       (let ((number-of-entries
   1885              (length (org-map-entries
   1886                       (lambda ()
   1887                         (let* ((tags-1-3-5 '("_1" "_3" "_5"))
   1888                                (tags-without-1-3-5 (seq-remove (lambda (e) (member e tags-1-3-5))
   1889                                                                org-scanner-tags)))
   1890                           (org-set-tags tags-without-1-3-5)))
   1891                       "_1|_3|_5"
   1892                       'agenda-with-archives))))
   1893         (message "Modified %d entries." number-of-entries)))
   1894     (defun za/archive-finished-tickler ()
   1895       (interactive)
   1896       (progn
   1897         (find-file-other-window za/org-life-tickler)
   1898         (length (org-map-entries
   1899                  (lambda ()
   1900                    (org-fold-show-subtree)
   1901                    (when (y-or-n-p "Archive? ")
   1902                      (org-archive-subtree-default)
   1903                      (save-buffer)))
   1904                  "TIMESTAMP<*\"<today>\""
   1905                  'file))))
   1906 
   1907     (require 'org-tempo)
   1908     (require 'org-habit)
   1909     (require 'org-id)
   1910     (use-package ob-async)
   1911     (use-package ob-rust)
   1912     (org-babel-do-load-languages
   1913      'org-babel-load-languages
   1914      '((emacs-lisp . t)
   1915        (R . t)
   1916        (python . t)
   1917        (ruby . t)
   1918        (shell . t)
   1919        (sqlite . t)
   1920        (rust . t)
   1921        (passthrough . t)))
   1922     (use-package inf-ruby)
   1923     (use-package org-superstar
   1924       :custom
   1925       (org-superstar-leading-bullet ?\s))
   1926 
   1927     ;; Linking to emails via notmuch
   1928     (use-package ol-notmuch)
   1929 
   1930     ;; Improved search
   1931     (use-package org-ql)
   1932 
   1933     ;; My override for org clock resolve
   1934     (require 'org-clock-override)
   1935 
   1936     ;; Tempo expansions
   1937     (add-to-list 'org-structure-template-alist '("se" . "src emacs-lisp"))
   1938     (add-to-list 'org-structure-template-alist '("sb" . "src bibtex"))
   1939     (add-to-list 'org-structure-template-alist '("ss" . "src sh"))
   1940     (add-to-list 'org-structure-template-alist '("sy" . "src yaml")))
   1941 #+end_src
   1942 *** Agenda & GTD
   1943 **** Agenda mode settings
   1944 #+begin_src emacs-lisp
   1945   (use-package org-agenda
   1946     :bind (:map org-agenda-mode-map
   1947                 ("C-c TAB" . za/org-agenda-goto-narrowed-subtree)
   1948                 ("@" . za/org-agenda-show-context-tags))
   1949     :custom
   1950     (org-agenda-files (list za/org-life-main
   1951                             za/org-life-inbox
   1952                             za/org-life-tickler))
   1953     (org-agenda-text-search-extra-files
   1954      (directory-files za/org-life-dir t (rx bol (not ?.) (* anything) ".org"))
   1955      "I want to search all Org files in the life directory")
   1956 
   1957     :config
   1958     (defun za/org-agenda-show-context-tags ()
   1959       "Show the context tags (e.g. @computer) applicable to the current item."
   1960       (interactive)
   1961       (let* ((tags (org-get-at-bol 'tags))
   1962              (context-tag-p (lambda (tag) (string-prefix-p "@" tag)))
   1963              (context-tags (seq-filter context-tag-p tags)))
   1964         (if context-tags
   1965             (message "Contexts are :%s:"
   1966                      (org-no-properties (mapconcat #'identity context-tags ":")))
   1967           (message "No contexts associated with this line"))))
   1968     (defun za/org-agenda-goto-narrowed-subtree ()
   1969       "Jump to current agenda item and narrow to its subtree."
   1970       (interactive)
   1971       (delete-other-windows)
   1972       (org-agenda-goto)
   1973       (org-narrow-to-subtree)
   1974       (outline-hide-subtree)
   1975       (org-show-children 1)
   1976       (other-window 1)))
   1977 #+end_src
   1978 
   1979 Fix tag display by dynamically calculating the column.
   1980 
   1981 #+begin_src emacs-lisp
   1982   (defun za/settings-org-agenda-mode ()
   1983     "My settings for org agenda mode"
   1984     )
   1985   (add-hook 'org-agenda-mode-hook #'za/settings-org-agenda-mode)
   1986 #+end_src
   1987 
   1988 **** Opening files
   1989 Convenience functions to make opening the main file faster:
   1990 
   1991 #+begin_src emacs-lisp
   1992   (defun gtd () "GTD: main file" (interactive) (find-file za/org-life-main))
   1993   (defun gtd-inbox ()
   1994     "GTD: inbox"
   1995     (interactive)
   1996     (let ((count-docs (length (directory-files za/org-life-doc-inbox nil (rx bos (not ?.))))))
   1997       (find-file za/org-life-inbox)
   1998       (when (> count-docs 0)
   1999         (dired-other-window za/org-life-doc-inbox)
   2000         (dired-revert)
   2001         (other-window 1))))
   2002   (defun gtd-inbox-mobile () "GTD: mobile inbox" (interactive) (find-file za/org-life-inbox-mobile))
   2003   (defun gtd-archive () "GTD: archive" (interactive) (find-file za/org-life-archive))
   2004   (defun gtd-someday () "GTD: someday" (interactive) (find-file za/org-life-someday))
   2005   (defun gtd-tickler () "GTD: tickler" (interactive) (find-file za/org-life-tickler))
   2006 #+end_src
   2007 
   2008 Bind keys to those functions:
   2009 
   2010 #+begin_src emacs-lisp
   2011   (bind-keys :prefix "M-g t"
   2012              :prefix-map za/gtd-files-map
   2013              :prefix-docstring "Visit GTD file"
   2014              ("i" . gtd-inbox)
   2015              ("l" . gtd)
   2016              ("a" . gtd-archive)
   2017              ("s" . gtd-someday)
   2018              ("t" . gtd-tickler))
   2019 #+end_src
   2020 
   2021 To improve jumping to any headline via counsel, filter returned candidates to include source file.
   2022 
   2023 #+begin_src emacs-lisp
   2024   (defun za/counsel-org-agenda-headlines--candidates-with-filename (candidates)
   2025     "Convert CANDIDATES to include source filename for each candidate."
   2026     (mapcar (lambda (candidate)
   2027               (let ((name (nth 0 candidate))
   2028                     (path (nth 1 candidate))
   2029                     (pos (nth 2 candidate)))
   2030                 (list (format "%s/%s" (file-name-nondirectory path) name)
   2031                       path
   2032                       pos)))
   2033             candidates))
   2034 
   2035   (advice-add #'counsel-org-agenda-headlines--candidates :filter-return #'za/counsel-org-agenda-headlines--candidates-with-filename)
   2036 #+end_src
   2037 
   2038 *** Processing inbox
   2039 I made a function for processing the inbox, focusing on one item at a time:
   2040 
   2041 #+begin_src emacs-lisp
   2042   (defun za/gtd-inbox-next-item ()
   2043     (interactive)
   2044     (unless (string= (buffer-file-name) (file-truename za/org-life-inbox))
   2045       (user-error "You're not in your GTD inbox file."))
   2046     (widen)
   2047     (org-first-headline-recenter)
   2048     (org-narrow-to-subtree))
   2049 #+end_src
   2050 
   2051 And a conditional binding:
   2052 
   2053 #+begin_src emacs-lisp
   2054   (bind-key "C-c g n" #'za/gtd-inbox-next-item 'org-mode-map (string= (buffer-file-name) (file-truename za/org-life-inbox)))
   2055 #+end_src
   2056 
   2057 And a function for importing other inboxes:
   2058 
   2059 #+begin_src emacs-lisp
   2060   (defun za/gtd-inbox-import ()
   2061     (interactive)
   2062     (unless (string= (buffer-file-name) (file-truename za/org-life-inbox))
   2063       (user-error "You're not in your GTD inbox file"))
   2064     (when (directory-files za/org-life-dir nil "\\.sync-conflict-")
   2065         (user-error "Sync conflicts found, please fix them"))
   2066     (let ((mobile (if (boundp 'za/org-life-inbox-mobile) (file-truename za/org-life-inbox-mobile) nil))
   2067           (calendar (if (boundp 'za/org-life-calendar-inbox) (file-truename za/org-life-calendar-inbox) nil)))
   2068       (save-mark-and-excursion
   2069         (goto-char (point-max))
   2070         (when mobile
   2071           (insert-file mobile)
   2072           (goto-char (point-max))
   2073           (write-region "" nil mobile))
   2074         (when calendar
   2075           (insert-file calendar)
   2076           (write-region "" nil calendar)
   2077           (goto-char (point-max)))
   2078         (message "Imported other inboxes."))))
   2079 #+end_src
   2080 
   2081 Also with a conditional binding:
   2082 
   2083 #+begin_src emacs-lisp
   2084   (bind-key "C-c g i" #'za/gtd-inbox-import 'org-mode-map (string= (buffer-file-name) (file-truename za/org-life-inbox)))
   2085 #+end_src
   2086 *** Refiling & archiving
   2087 #+begin_src emacs-lisp
   2088   (use-package org-refile
   2089     :custom
   2090     (org-refile-targets `((,za/org-life-main :maxlevel . 3)
   2091                           (,za/org-life-someday :level . 1)
   2092                           (,za/org-life-tickler :maxlevel . 3))
   2093                         "Where I want to be able to move subtrees (doesn't include inbox because I never refile to that, and the archive has its own keybining)")
   2094     (org-archive-location (concat za/org-life-archive "::datetree/")
   2095                           "I want to archive to a specific file, in a date tree")
   2096     (org-refile-use-outline-path 'file
   2097                                  "Include the destination file as an element in the path to a heading, and to use the full paths as completion targets rather than just the heading text itself")
   2098     (org-outline-path-complete-in-steps nil
   2099                                         "Tell Org that I don’t want to complete in steps; I want Org to generate all of the possible completions and present them at once (necessary for Helm/Ivy)")
   2100     (org-refile-allow-creating-parent-nodes 'confirm
   2101                                             "Allow me to tack new heading names onto the end of my outline path, and if I am asking to create new ones, make me confirm it"))
   2102 #+end_src
   2103 
   2104 *** Quick capture
   2105 Quick capture lets me send something to my inbox very quickly, without thinking about where it should go.
   2106 The inbox is processed later.
   2107 
   2108 Templates for quick capture:
   2109 
   2110 #+begin_src emacs-lisp
   2111   (use-package org-capture
   2112     :custom
   2113     (org-capture-templates `(("t" "Todo [inbox]" entry
   2114                               (file ,za/org-life-inbox)
   2115                               "* TODO %i%?")
   2116 
   2117                              ("s" "Save for read/watch/listen" entry
   2118                               (file+headline ,za/org-life-someday "Read/watch/listen")
   2119                               "* %?[[%^{link}][%^{description}]] %^g"))))
   2120 #+end_src
   2121 
   2122 *** Todo & custom agenda views
   2123 Todo keywords based on the GTD system (pipe separates incomplete from complete).
   2124 Apart from the logging-on-done configured [[*Logging][below]], I also want to log a note & timestamp when I start waiting on something.
   2125 In ~org-todo-keywords~, ~@~ means note+timestamp, ~!~ means timestamp, ~@/!~ means note+timestamp on state entry and timestamp on leave.
   2126 
   2127 #+begin_src emacs-lisp
   2128   (custom-set-variables '(org-todo-keywords '((sequence "TODO(t)" "NEXT(n)" "STARTED(s)" "WAITING(w@)" "PROJ(p)" "|" "DONE(d)" "CANCELLED(c)")))
   2129                         '(org-todo-keyword-faces '(("TODO" . org-todo)
   2130                                                    ("NEXT" . org-todo)
   2131                                                    ("WAITING" . org-todo)
   2132                                                    ("STARTED" . org-todo)
   2133                                                    ("PROJ" . org-todo)
   2134                                                    ("DONE" . org-done)
   2135                                                    ("CANCELLED" . org-done))))
   2136 #+end_src
   2137 
   2138 
   2139 Something is a habit if: it has a HABIT tag, STYLE is habit, LOGGING is logrepeat, it has a scheduled repeater from today.
   2140 
   2141 #+begin_src emacs-lisp
   2142   (defun za/mark-as-habit ()
   2143     "This function makes sure that the current heading has:
   2144   (1) a HABIT tag
   2145   (2) todo set to TODO
   2146   (3) LOGGING property set to logrepeat
   2147   (4) a scheduled repeater from today"
   2148     (interactive)
   2149     (org-back-to-heading t)
   2150     (org-set-property "TODO" "TODO")
   2151     (org-set-property "LOGGING" "logrepeat")
   2152     (org-set-property "STYLE" "habit")
   2153     (org-toggle-tag "HABIT" 'on)
   2154     (org-schedule nil))
   2155 #+end_src
   2156 
   2157 +I decided that projects will not be TODO items, but their progress will be tracked with a progress cookie ([x/y]). This function converts an item to a project: it adds a PROJECT tag, sets the progress indicator to count all checkboxes in sub-items (only TODO items), and removes any existing TODO keywords. Finally, PROJECT tags shouldn't be inherited (i.e. subtasks shouldn't be marked as projects).+
   2158 In the end, I want NEXT items that are part of a project to be shown as such (so inherit that PROJECT tag), but projects themselves will have a PROJ todo keyword.
   2159 This function converts an item to a project.
   2160 
   2161 #+begin_src emacs-lisp
   2162   (defun za/mark-as-project ()
   2163     "This function makes sure that the current heading has
   2164       (1) the tag PROJECT
   2165       (2) the todo keyword PROJ
   2166       (3) the property COOKIE_DATA set to \"todo recursive\"
   2167       (4) a progress indicator"
   2168     (interactive)
   2169     (org-back-to-heading t)
   2170     ;; Step 1: clear out everything
   2171     (org-set-property "TODO" "")
   2172 
   2173     ;; org-set-property errors via org-priority if you try to clear
   2174     ;; priority of an item that doesn't have priority. Stupid design,
   2175     ;; but I can't change that so we gotta jump through hoops:
   2176     (let ((have-priority (org-element-property :priority (org-element-at-point))))
   2177       (when have-priority
   2178         (org-set-property "PRIORITY" "")))
   2179 
   2180     ;; Step 2: set info (stats cookie, todo, tag, properties drawer)
   2181     (forward-whitespace 1)
   2182     (insert "[/] ")
   2183     (org-set-property "TODO" "PROJ")
   2184     (org-toggle-tag "PROJECT" 'on)
   2185     (org-set-property "COOKIE_DATA" "todo recursive")
   2186     (org-update-statistics-cookies nil))
   2187 #+end_src
   2188 
   2189 And a keybinding for it:
   2190 
   2191 #+begin_src emacs-lisp
   2192   (bind-key "C-c g p" #'za/mark-as-project 'org-mode-map)
   2193 #+end_src
   2194 
   2195 Want all tags to be inherited:
   2196 
   2197 #+begin_src emacs-lisp
   2198   (custom-set-variables '(org-tags-exclude-from-inheritance nil))
   2199 #+end_src
   2200 
   2201 Define a function to skip items if they're part of a project (i.e. one of their parents has a "PROJECT" tag).
   2202 +The problem is, the "PROJECT" tag isn't inherited. So, we temporarily disable excluding from inheritance, just for the ~org-get-tags~ call. Then check if "PROJECT" is one of the tags.+ That tag is now inherited.
   2203 
   2204 #+begin_src emacs-lisp
   2205   (defun za/skip-if-in-project ()
   2206     "Skip items that are part of a project but not a project themselves."
   2207     (let ((skip (save-excursion (org-end-of-subtree t)))
   2208           (keep nil)
   2209           (item-tags (let ((org-use-tag-inheritance t)) (org-get-tags)))
   2210           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags))))
   2211       (if (and (member "PROJECT" item-tags)
   2212                (not (member "PROJECT" item-tags-without-inherited)))
   2213           skip
   2214         keep)))
   2215 #+end_src
   2216 
   2217 Also, define a function to skip tasks (trees) that are not habits (i.e. don't have the STYLE property ~habit~):
   2218 
   2219 #+begin_src emacs-lisp
   2220   (defun za/skip-unless-habit ()
   2221     "Skip trees that are not habits"
   2222     (let ((skip (save-excursion (org-end-of-subtree t)))
   2223           (keep nil))
   2224       (if (string= (org-entry-get nil "STYLE") "habit")
   2225           keep
   2226         skip)))
   2227 #+end_src
   2228 
   2229 And one to skip tasks that /are/ habits:
   2230 
   2231 #+begin_src emacs-lisp
   2232   (defun za/skip-if-habit ()
   2233     "Skip trees that are not habits"
   2234     (let ((skip (save-excursion (org-end-of-subtree t)))
   2235           (keep nil))
   2236       (if (string= (org-entry-get nil "STYLE") "habit")
   2237           skip
   2238         keep)))
   2239 #+end_src
   2240 
   2241 Skip ones with a habit tag:
   2242 
   2243 #+begin_src emacs-lisp
   2244   (defun za/skip-if-has-habit-tag ()
   2245     (let ((skip (save-excursion (org-end-of-subtree t)))
   2246           (keep nil)
   2247           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags))))
   2248       (if (or (member "HABIT" item-tags-without-inherited)
   2249               (member "flatastic" item-tags-without-inherited))
   2250           skip
   2251         keep)))
   2252 #+end_src
   2253 
   2254 And another function, to skip tasks that are blocked:
   2255 
   2256 #+begin_src emacs-lisp
   2257   (defun za/skip-if-blocked ()
   2258     "Skip trees that are blocked by previous tasks"
   2259     (let ((skip (save-excursion (org-end-of-subtree t)))
   2260           (keep nil))
   2261       (if (org-entry-blocked-p)
   2262           skip
   2263         keep)))
   2264 #+end_src
   2265 
   2266 For listing tasks without a context - skip if it has a context tag:
   2267 
   2268 #+begin_src emacs-lisp
   2269   (defun za/skip-if-has-context ()
   2270     (let ((skip (save-excursion (org-end-of-subtree t)))
   2271           (keep nil)
   2272           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags)))
   2273           (context-tag-p (lambda (s) (eq (aref s 0) ?@))))
   2274       (if (cl-some context-tag-p item-tags-without-inherited)
   2275           skip
   2276         keep)))
   2277 #+end_src
   2278 
   2279 For listing tasks without an energy level - skip if it has an energy level:
   2280 
   2281 #+begin_src emacs-lisp
   2282   (defun za/skip-if-has-energy-level ()
   2283     (let ((skip (save-excursion (org-end-of-subtree t)))
   2284           (keep nil)
   2285           (item-tags-without-inherited (let ((org-use-tag-inheritance nil)) (org-get-tags)))
   2286           (energy-tag-p (lambda (s) (member s '("deep" "quick_shallow" "errand")))))
   2287       (if (cl-some energy-tag-p item-tags-without-inherited)
   2288           skip
   2289         keep)))
   2290 #+end_src
   2291 
   2292 #+begin_src emacs-lisp
   2293   (defun za/skip-if-scheduled-in-future ()
   2294     (let* ((skip (save-excursion (org-end-of-subtree t)))
   2295            (keep nil)
   2296            (scheduled-time (org-get-scheduled-time (point))))
   2297       (if (and scheduled-time (time-less-p (current-time) scheduled-time))
   2298           skip
   2299         keep)))
   2300 #+end_src
   2301 
   2302 #+begin_src emacs-lisp
   2303   (defun za/skip-if-scheduled ()
   2304     (let* ((skip (save-excursion (org-end-of-subtree t)))
   2305            (keep nil)
   2306            (scheduled-time (org-get-scheduled-time (point))))
   2307       (if scheduled-time
   2308           skip
   2309         keep)))
   2310 #+end_src
   2311 
   2312 Create custom agenda view based on those keywords.
   2313 Agenda views are made up of blocks, appearing in the order that you declare them.
   2314 The first two strings are what shows up in the agenda dispatcher (the key to press and the description).
   2315 
   2316 #+begin_src emacs-lisp
   2317   (setq org-agenda-custom-commands
   2318         '(("n" "Next actions"
   2319            todo "NEXT" ((org-agenda-overriding-header "Next actions:")
   2320                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2321                         (org-agenda-skip-function #'za/skip-if-scheduled)))
   2322           ("q" "Query" (lambda (&rest _) (call-interactively #'org-ql-search)))
   2323 
   2324           ("W" "Waiting"
   2325            ((todo "WAITING" ((org-agenda-overriding-header "Waiting:")))))
   2326           ("S" . "Saved for later...")
   2327           ("Sw" "Saved to watch"
   2328            ((tags-todo "WATCH" ((org-agenda-overriding-header "To watch:")
   2329                                 (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2330 
   2331           ("Sr" "Saved to read"
   2332            ((tags-todo "READ" ((org-agenda-overriding-header "To read:")
   2333                                (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2334           ("Sl" "Saved to listen"
   2335            ((tags-todo "LISTEN" ((org-agenda-overriding-header "To listen:")
   2336                                  (org-agenda-files `(,za/org-life-someday ,@org-agenda-files))))))
   2337 
   2338           ("a" . "Agenda with schedule only...")
   2339           ("aw" "This week"
   2340            ((agenda "" ((org-agenda-span 'week)))))
   2341           ("aD" "Today"
   2342            ((agenda "" ((org-agenda-span 'day)))))
   2343           ("ad" "Today (no habits)"
   2344            ((agenda "" ((org-agenda-span 'day)
   2345                         (org-agenda-skip-function 'za/skip-if-has-habit-tag)))))
   2346           ("at" "Tomorrow (no habits)"
   2347            ((agenda "" ((org-agenda-span 'day)
   2348                         (org-agenda-start-day "+1d")
   2349                         (org-agenda-skip-function 'za/skip-if-has-habit-tag)))))
   2350           ("aT" "Tomorrow"
   2351            ((agenda "" ((org-agenda-span 'day)
   2352                         (org-agenda-start-day "+1d")))))
   2353 
   2354           ("w" "Week Agenda + Next Actions"
   2355            ((agenda "" ((org-agenda-overriding-header "Week agenda:")))
   2356             (todo "NEXT" ((org-agenda-overriding-header "Next actions:")))))
   2357 
   2358           ("o" "Month agenda"
   2359            ((agenda "" ((org-agenda-overriding-header "Month agenda:")
   2360                         (org-agenda-span 'month)))))
   2361 
   2362           ("d" "Day Agenda with habit tags + Habits + Waiting"
   2363            ((agenda "" ((org-agenda-overriding-header "Day:")
   2364                         (org-agenda-span 'day)
   2365                         (org-habit-show-habits nil)))
   2366             (todo "STARTED" ((org-agenda-overriding-header "In progress:")))
   2367             (todo "WAITING" ((org-agenda-overriding-header "Waiting:")))
   2368             (agenda "" ((org-agenda-overriding-header "Habits:")
   2369                         (org-agenda-span 'day)
   2370                         (org-agenda-use-time-grid nil)
   2371                         (org-agenda-skip-function 'za/skip-unless-habit)
   2372                         (org-habit-show-habits t)
   2373                         (org-habit-show-habits-only-for-today nil)
   2374                         (org-habit-show-all-today t)))))
   2375 
   2376 
   2377           ("k" "Kanban view"
   2378            ((todo "STARTED" ((org-agenda-overriding-header "In progress:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))
   2379             (todo "NEXT" ((org-agenda-overriding-header "To do:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))
   2380             (todo "WAITING" ((org-agenda-overriding-header "Waiting:") (org-agenda-sorting-strategy '(deadline-up priority-down alpha-up))))
   2381             (todo "DONE" ((org-agenda-overriding-header "Done:") (org-agenda-sorting-strategy '(tsia-down))))))
   2382 
   2383           ("p" "Projects"
   2384            ((todo "PROJ" ((org-agenda-overriding-header "Projects:")
   2385                           (org-agenda-prefix-format '((todo . " %i %-22(let ((deadline (org-entry-get nil \"DEADLINE\"))) (if deadline deadline \"\"))")))
   2386                           (org-agenda-dim-blocked-tasks nil)
   2387                           (org-agenda-sorting-strategy '((todo deadline-up alpha-down)))))))
   2388           ("1" "1-3-5"
   2389            ((tags "_1" ((org-agenda-overriding-header "Big tasks:")
   2390                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2391                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))
   2392             (tags "_3" ((org-agenda-overriding-header "Medium tasks:")
   2393                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2394                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))
   2395             (tags "_5" ((org-agenda-overriding-header "Small tasks:")
   2396                         (org-agenda-skip-function 'za/skip-if-scheduled-in-future)
   2397                         (org-agenda-sorting-strategy '(todo-state-down deadline-up priority-down alpha-up))))))
   2398 
   2399           ;; Useful thread for opening calfw: https://github.com/kiwanami/emacs-calfw/issues/18
   2400           ("c" "Calendar view" (lambda (&rest _)
   2401                                  (interactive)
   2402                                  (let ((org-agenda-skip-function 'za/skip-if-habit))
   2403                                    (cfw:open-org-calendar))))
   2404           ("f" . "Find & fix...")
   2405           ("f@" "Next actions missing context"
   2406            todo "NEXT" ((org-agenda-overriding-header "Missing context:")
   2407                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2408                         (org-agenda-skip-function 'za/skip-if-has-context)))
   2409           ("fe" "Next actions missing energy"
   2410            todo "NEXT" ((org-agenda-overriding-header "Missing energy level:")
   2411                         (org-agenda-sorting-strategy '(priority-down alpha-up))
   2412                         (org-agenda-skip-function 'za/skip-if-has-energy-level)))
   2413           ("ff" "Finished tasks that aren't in a project"
   2414            ((tags "TODO=\"DONE\"|TODO=\"CANCELLED\"" ((org-agenda-overriding-header "Finished tasks:")
   2415                                                       (org-agenda-skip-function 'za/skip-if-in-project)))))
   2416           ("ft" "Tasks without a scheduled time"
   2417            alltodo "" ((org-agenda-overriding-header "Missing scheduled time:")
   2418                        (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline 'timestamp))))))
   2419 #+end_src
   2420 
   2421 In calfw, I don't want to show habits:
   2422 
   2423 #+begin_src emacs-lisp
   2424   (add-hook 'cfw:calendar-mode-hook (setq-local org-agenda-skip-function 'za/skip-if-habit))
   2425 #+end_src
   2426 
   2427 *** Automatically mark next project item as NEXT
   2428 Unless the current item is a project, when a project item is done, the next item in the project should be marked "NEXT".
   2429 I tried org-edna but I couldn't get it working after an hour of effort. So a bit of lisp is the easier solution.
   2430 
   2431 #+begin_src emacs-lisp
   2432   (defun za/gtd-auto-next ()
   2433     "Automatically mark project item as next."
   2434     (save-excursion
   2435       (org-back-to-heading)
   2436       (when (buffer-narrowed-p)
   2437         (widen))
   2438       ;; org-state is set automatically in the hook
   2439       (when (and (member org-state org-done-keywords)
   2440                  (not (member "PROJECT" (org-get-tags nil 'local)))
   2441                  (member "PROJECT" (let ((org-use-tag-inheritance t))
   2442                                      (org-get-tags nil))))
   2443         (when (org-goto-sibling)
   2444           ;; if TODO and scheduled => no change
   2445           ;; if not TODO => no change
   2446           ;; else => change
   2447           (let* ((is-todo-state (string= "TODO" (org-get-todo-state)))
   2448                  (is-scheduled (or (org-get-scheduled-time nil)
   2449                                    (org-get-deadline-time nil)))
   2450                  (should-change-state (cond ((and is-todo-state is-scheduled) nil)
   2451                                             ((not is-todo-state) nil)
   2452                                             (t t))))
   2453             (when should-change-state
   2454               (org-entry-put (point) "TODO" "NEXT")))))))
   2455   (add-hook #'org-after-todo-state-change-hook #'za/gtd-auto-next)
   2456 #+end_src
   2457 
   2458 *** Logging for tasks
   2459 I want to log into the LOGBOOK drawer (useful when I want to take quick notes):
   2460 
   2461 #+begin_src emacs-lisp
   2462   (setq org-log-into-drawer "LOGBOOK")
   2463 #+end_src
   2464 
   2465 I also want to log when I finish a task (useful for archiving).
   2466 Furthermore, when I'm done, I want to add a note (any important
   2467 workarounds/tips). And when I reschedule, I want to know the reason.
   2468 I can disable logging on state change for a specific task by adding ~:LOGGING: nil~ to the ~:PROPERTIES:~ drawer.
   2469 
   2470 #+begin_src emacs-lisp
   2471   (setq org-log-done 'time
   2472         org-log-reschedule 'note)
   2473 #+end_src
   2474 
   2475 I want to hide drawers on startup. This variable has options:
   2476 - 'overview': Top-level headlines only.
   2477 - 'content': All headlines.
   2478 - 'showall': No folding on any entry.
   2479 - 'show2levels: Headline levels 1-2.
   2480 - 'show3levels: Headline levels 1-3.
   2481 - 'show4levels: Headline levels 1-4.
   2482 - 'show5levels: Headline levels 1-5.
   2483 - 'showeverything: Show even drawer contents.
   2484 
   2485 #+begin_src emacs-lisp
   2486   (setq org-startup-folded 'content)
   2487 #+end_src
   2488 
   2489 *** Task ordering
   2490 Some tasks should be ordered, i.e. they should be done in steps.
   2491 Those have the ~:ORDERED: t~ setting in ~:PROPERTIES:~, and it should be enforced:
   2492 
   2493 #+begin_src emacs-lisp
   2494   (setq org-enforce-todo-dependencies t)
   2495 #+end_src
   2496 
   2497 Furthermore, tasks that are ordered and can't be done yet because of previous steps should be dimmed in the agenda:
   2498 
   2499 #+begin_src emacs-lisp
   2500   (setq org-agenda-dim-blocked-tasks t)
   2501 #+end_src
   2502 
   2503 I might also want to set ~org-enforce-todo-checkbox-dependencies~, but not convinced on that one yet.
   2504 
   2505 *** Time tracking & effort
   2506 Time tracking should be done in its own drawer:
   2507 
   2508 #+begin_src emacs-lisp
   2509   (setq org-clock-into-drawer "CLOCK")
   2510 #+end_src
   2511 
   2512 And to customize how clock tables work:
   2513 
   2514 #+begin_src emacs-lisp
   2515   (setq org-clocktable-defaults '(:lang "en" :scope agenda-with-archives  :wstart 1 :mstart 1 :compact t :maxlevel nil))
   2516   (setq org-agenda-clockreport-parameter-plist '(:link t :maxlevel nil))
   2517 #+end_src
   2518 
   2519 I want to set effort in hours:minutes:
   2520 
   2521 #+begin_src emacs-lisp
   2522   (add-to-list 'org-global-properties '("Effort_ALL" . "0:05 0:10 0:15 0:20 0:30 0:45 1:00 1:30 2:00 4:00 6:00 8:00"))
   2523 #+end_src
   2524 
   2525 I want column view to look like this:
   2526 
   2527 | To do        | Task      | Tags | Sum of time elapsed | Sum of time estimated (effort) |
   2528 |--------------+-----------+------+---------------------+--------------------------------|
   2529 | todo keyword | task name | tags | sum of clock        | sum of estimated time          |
   2530 | ...          | ...       | ...  | ...                 | ...                            |
   2531 
   2532 #+begin_src emacs-lisp
   2533   (setq org-columns-default-format "%7TODO (To Do) %32ITEM(Task) %TAGS(Tags) %11CLOCKSUM_T(Clock) %10Difficulty(Difficulty) %8Effort(Effort){:}")
   2534 #+end_src
   2535 
   2536 Fix column alignment in agenda.
   2537 
   2538 #+begin_src emacs-lisp
   2539   (set-face-attribute 'org-column nil
   2540                       :height (face-attribute 'default :height)
   2541                       :family (face-attribute 'default :family))
   2542   (set-face-attribute 'org-agenda-date-today nil
   2543                       :height (face-attribute 'default :height))
   2544 #+end_src
   2545 
   2546 *** Calculate time since timestamp
   2547 #+begin_src emacs-lisp
   2548   (defun za/org-time-since ()
   2549     "Print the amount of time between the timestamp at point and the current date and time."
   2550     (interactive)
   2551     (unless (org-at-timestamp-p 'lax)
   2552       (user-error "Not at timestamp"))
   2553 
   2554     (when (org-at-timestamp-p 'lax)
   2555       (let ((timestamp (match-string 0)))
   2556         (with-temp-buffer
   2557           (insert timestamp
   2558                   "--"
   2559                   (org-time-stamp '(16)))
   2560           (org-evaluate-time-range)))))
   2561 #+end_src
   2562 
   2563 Also a method to add overlays with that timestamp:
   2564 
   2565 #+begin_src emacs-lisp
   2566   (defvar-local za/org-timestamp-overlays--list nil "Buffer-local list of overlays with timestamps")
   2567   (defvar-local za/org-timestamp-overlays--show nil "Buffer-local boolean to show overlays.")
   2568   (defun za/org-timestamp-overlays-clear ()
   2569     "Clear all overlays with timestamps in current buffer."
   2570     (dolist (ov za/org-timestamp-overlays--list)
   2571       (delete-overlay ov))
   2572     (setq-local za/org-timestamp-overlays--list nil))
   2573 
   2574   (defun za/org-timestamp-overlays-add ()
   2575     "Add overlays for active timestamps in current buffer."
   2576     (let ((markup-string (lambda (s) (propertize (format "{%s}" s)
   2577                                                  'face 'org-habit-ready-future-face))))
   2578       (save-excursion
   2579         (let* ((beg (point-min))
   2580                (end (point-max)))
   2581           (goto-char beg)
   2582           (while (re-search-forward (org-re-timestamp 'active) end t)
   2583             (let ((ov (make-overlay (point) (point))))
   2584               (overlay-put ov 'before-string (funcall markup-string (za/org-time-since)))
   2585               (add-to-list 'za/org-timestamp-overlays--list ov)))))))
   2586 
   2587   (defun za/org-timestamp-overlays-redraw ()
   2588     "Redraw all overlays for active timestamps."
   2589     (za/org-timestamp-overlays-clear)
   2590     (za/org-timestamp-overlays-add))
   2591 
   2592   (defun za/org-timestamp-hook-fn (&rest _)
   2593     (za/org-timestamp-overlays-redraw))
   2594 
   2595   (bind-key "C-c q p" #'tmp/p)
   2596   (defun za/org-timestamp-overlays-toggle (&optional prefix)
   2597     "With no prefix, toggle showing timestamp overlay.
   2598   With PREFIX = 0, redraw overlays.
   2599   With PREFIX > 0, show overlays.
   2600   With PREFIX < 0, hide overlays."
   2601     (interactive "P")
   2602     (let ((overlays-hide (lambda ()
   2603                            (za/org-timestamp-overlays-clear)
   2604                            (remove-hook 'org-cycle-hook #'za/org-timestamp-hook-fn)
   2605                            (setq za/org-timestamp-overlays--show nil)
   2606                            (message "Overlays hidden.")))
   2607           (overlays-show (lambda ()
   2608                            (za/org-timestamp-overlays-redraw)
   2609                            (add-hook 'org-cycle-hook #'za/org-timestamp-hook-fn)
   2610                            (setq za/org-timestamp-overlays--show t)
   2611                            (message "Overlays showing.")))
   2612           (overlays-redraw-maybe (lambda ()
   2613                                    (when za/org-timestamp-overlays--show
   2614                                      (za/org-timestamp-overlays-redraw)
   2615                                      (message "Redrawing overlays."))))
   2616           (prefix-num (prefix-numeric-value prefix)))
   2617       (cond ((not prefix)
   2618              (cond (za/org-timestamp-overlays--show
   2619                     (funcall overlays-hide))
   2620                    (t
   2621                     (funcall overlays-show))))
   2622             ((zerop prefix-num)
   2623              )
   2624             ((> prefix-num 0)
   2625              (funcall overlays-show))
   2626             ((< prefix-num 0)
   2627              (funcall overlays-hide)))))
   2628 
   2629 #+end_src
   2630 
   2631 Bind a key:
   2632 
   2633 #+begin_src emacs-lisp
   2634   (bind-key "C-c q d" #'za/org-timestamp-overlays-toggle 'org-mode-map)
   2635   (bind-key "C-c q d" #'za/org-timestamp-overlays-toggle 'org-agenda-mode-map)
   2636 #+end_src
   2637 *** Priorities: how important something is
   2638 I usually have a lot of 'next' actions, so I prefer 4 priority levels instead of the default 3: A (urgent, ASAP), B (important),  C (if you have nothing else, do this), D (do in free time):
   2639 
   2640 #+begin_src emacs-lisp
   2641   (setq org-priority-highest ?A
   2642         org-priority-lowest ?D
   2643         org-priority-default ?C)
   2644 #+end_src
   2645 
   2646 Faces for priorities in agenda:
   2647 
   2648 #+begin_src emacs-lisp
   2649   (setq org-priority-faces `((?A . (:foreground ,(face-foreground 'error)))
   2650                              (?B . (:foreground ,(face-foreground 'org-todo)))
   2651                              (?C . (:foreground ,(face-foreground 'font-lock-constant-face) :weight semi-light))
   2652                              (?D . (:foreground ,(face-foreground 'font-lock-string-face) :slant italic :weight light))))
   2653 #+end_src
   2654 
   2655 And to be able to bulk-set priorities in agenda:
   2656 
   2657 #+begin_src emacs-lisp
   2658   (setq org-agenda-bulk-custom-functions '((?P (lambda nil (org-agenda-priority 'set)))))
   2659 #+end_src
   2660 *** Energy requirement: how difficult something is
   2661 #+begin_src emacs-lisp
   2662   (add-to-list 'org-global-properties '("Difficulty_ALL" . "low medium high"))
   2663 #+end_src
   2664 *** Org export backends
   2665 #+begin_src emacs-lisp
   2666   (use-package ox-pandoc)
   2667 #+end_src
   2668 
   2669 *** org publishing
   2670 I decided, after trying many different things, to settle on org-publish.
   2671 
   2672 #+begin_src emacs-lisp
   2673   (defconst za/org-roam-top-name "Top" "The name of the top-level Org-roam node.")
   2674   (defun za/org-roam-sitemap-function (title list)
   2675     "Customized function to generate sitemap for org-roam, almost the same as `org-publish-sitemap-default`."
   2676     (concat "#+TITLE: " title "\n\n"
   2677             (format "[[file:%s][%s]]\n\n"
   2678                     (file-name-nondirectory (org-roam-node-file
   2679                                              (org-roam-node-from-title-or-alias za/org-roam-top-name)))
   2680                     "Click here for entrypoint.")))
   2681   ;; (org-list-to-org list)))  <-- this is taken care of by Zola
   2682 
   2683 #+end_src
   2684 
   2685 To make this work with Zola, I need to export Github-flavored markdown (fenced code blocks with language):
   2686 
   2687 #+begin_src emacs-lisp
   2688   (require 'ox-publish)
   2689   (require 'ox-md)
   2690 
   2691   (use-package ox-gfm
   2692     :init
   2693     (with-eval-after-load 'org (require 'ox-gfm)))
   2694 #+end_src
   2695 
   2696 First difficulty: Zola needs front matter with ~+++...+++~.
   2697 The default Markdown backend doesn't provide that, so need to customize it by advising the default ~org-md-template~.
   2698 
   2699 #+begin_src emacs-lisp
   2700   (defun za/org-md-template-zola (contents info)
   2701     "Markdown template compatible with Zola (generates the necessary front matter from CONTENTS and INFO)."
   2702     (let ((title (org-md-plain-text (org-element-interpret-data (plist-get info :title)) info)))
   2703       (concat "+++\n"
   2704               (format "title = \"%s\"\n" (string-replace "\"" "'" title))
   2705 
   2706               ;; If the note contains a math org-roam tag
   2707               (when (member "math" (plist-get info :filetags))
   2708                 "template = \"page-math.html\"\n")
   2709 
   2710               "+++\n"
   2711               (format "# %s\n" title)
   2712               contents)))
   2713 #+end_src
   2714 
   2715 Second difficulty: links need to be reformatted and changed for static data (like images).
   2716 This function filters the return value of ~org-md-link~.
   2717 
   2718 #+begin_src emacs-lisp
   2719   (defun za/org-md-link-zola (linkstr)
   2720     "A filter function for the return value of
   2721           `org-md-link` (LINKSTR) to generate a link compatible with Zola."
   2722     (cond ((string-match-p (rx ".md") linkstr)
   2723            (string-replace "](" "](@/org-roam/" linkstr))
   2724           ((string-match-p (rx "](" (? (* alnum) "://") "/") linkstr)
   2725            (replace-regexp-in-string (rx "](" (? (* alnum) "://") "/" (* any) "/org-roam/data") "](/org-roam-data" linkstr))
   2726           (t linkstr)))
   2727 #+end_src
   2728 
   2729 A wrapper to set the right image link:
   2730 
   2731 #+begin_src emacs-lisp
   2732   (defun za/org-html--format-image (args)
   2733     "Modify source image link to work with my Org roam setup"
   2734     (let ((source (nth 0 args))
   2735           (_attributes (nth 1 args))
   2736           (_info (nth 2 args)))
   2737       (list (replace-regexp-in-string (rx bos "data/") "/org-roam-data/" source)
   2738             _attributes
   2739             _info)))
   2740 #+end_src
   2741 
   2742 And here's the custom publish function that adds/removes the necessary advice:
   2743 
   2744 #+begin_src emacs-lisp
   2745   (defun za/org-gfm-publish-to-gfm-zola (plist filename pub-dir)
   2746     "Run `org-gfm-publish-to-gfm`, advising the necessary
   2747   functions to generate Zola-compatible markdown."
   2748     (let* ((org-export-output-file-name-locked (lambda (extension &rest _)
   2749                                                  (concat (plist-get plist :publishing-directory)
   2750                                                          "locked-"
   2751                                                          (file-name-base filename)
   2752                                                          extension)))
   2753            (node (car (seq-filter
   2754                        (lambda (node) (file-equal-p (org-roam-node-file node) filename))
   2755                        (org-roam-node-list))))
   2756            (locked-p (cond ((file-equal-p filename
   2757                                           (file-name-concat (plist-get plist :base-directory) (plist-get plist :sitemap-filename)))
   2758                             nil)
   2759                            (t
   2760                             (member "locked" (org-roam-node-tags node)))))
   2761            (advice '((org-gfm-inner-template :override za/org-md-template-zola)
   2762                      (org-md-link :filter-return za/org-md-link-zola)
   2763                      (org-html--format-image :filter-args za/org-html--format-image)
   2764                      (org-gfm-table :override org-md--convert-to-html)))) ; Zola uses CommonMark, so doesn't support Markdown tables
   2765 
   2766       (dolist (orig-type-new advice) (apply #'advice-add orig-type-new))
   2767       (unwind-protect
   2768           (cond (locked-p
   2769                  (advice-add #'org-export-output-file-name :override org-export-output-file-name-locked)
   2770                  (unwind-protect
   2771                      (org-gfm-publish-to-gfm plist filename pub-dir)
   2772                    (advice-remove #'org-export-output-file-name org-export-output-file-name-locked)))
   2773                 (t
   2774                  (org-gfm-publish-to-gfm plist filename pub-dir)))
   2775         (dolist (orig-type-new advice)
   2776           (advice-remove (nth 0 orig-type-new)
   2777                          (nth 2 orig-type-new))))))
   2778 #+end_src
   2779 
   2780 Finally, the list of things we can publish with their respective publishin functions:
   2781 
   2782 #+begin_src emacs-lisp
   2783   (if (boundp 'za/my-website-dir)
   2784       (setq org-publish-project-alist
   2785             `(
   2786               ("org-notes"
   2787                :base-directory ,za/org-roam-dir
   2788                :base-extension "org"
   2789                :publishing-directory ,(concat za/my-website-dir "content/org-roam/")
   2790                :publishing-function za/org-gfm-publish-to-gfm-zola
   2791                :recursive t
   2792                :sitemap-filename "_index.md"
   2793                :sitemap-title "Org Roam"
   2794                :sitemap-function za/org-roam-sitemap-function
   2795                :auto-sitemap t)
   2796 
   2797               ("org-notes-data"
   2798                :base-directory ,(concat za/org-roam-dir "/data")
   2799                :base-extension any
   2800                :publishing-directory ,(concat za/my-website-dir "static/org-roam-data/")
   2801                :recursive t
   2802                :publishing-function org-publish-attachment)
   2803 
   2804               ("org-roam" :components ("org-notes" "org-notes-data"))))
   2805     (warn "za/my-website-dir not bound, not setting org publishing targets."))
   2806 #+end_src
   2807 
   2808 And a function to rsync to my VPS:
   2809 
   2810 #+begin_src emacs-lisp
   2811   (defun za/publish-upload-to-website ()
   2812     "Upload my website to my VPS"
   2813     (interactive)
   2814     (async-shell-command (format "cd %s && zola build && yes|publish" za/my-website-dir) "*Async Shell publish*"))
   2815 #+end_src
   2816 *** Rebuild org cache
   2817 
   2818 #+begin_src emacs-lisp
   2819   (defun za/force-org-rebuild-cache ()
   2820     "Rebuild the `org-mode' and `org-roam' cache."
   2821     (interactive)
   2822     (org-id-update-id-locations)
   2823     ;; Note: you may need `org-roam-db-clear-all'
   2824     ;; followed by `org-roam-db-sync'
   2825     (org-roam-db-sync)
   2826     (org-roam-update-org-id-locations))
   2827 #+end_src
   2828 *** Sync with Flatastic
   2829 API work is handled via an external ruby script.
   2830 
   2831 #+begin_src emacs-lisp
   2832   (defun za/org-flatastic-sync-tasks ()
   2833     "Add tasks from flatastic to inbox"
   2834     (interactive)
   2835     (unless (json-available-p)
   2836       (user-error "JSON not available"))
   2837     (unless (boundp 'za/org-life-inbox)
   2838       (user-error "Please set za/org-life-inbox"))
   2839     (let* ((api-data (json-parse-string
   2840                       (progn
   2841                         (require 'exec-path-from-shell)
   2842                         (exec-path-from-shell-copy-envs
   2843                          '("FLATASTIC_API_KEY" "FLATASTIC_USER_ID"))
   2844                         (shell-command-to-string "~/.local/share/rbenv/shims/ruby ~/.scripts/flatastic.rb"))
   2845                       :object-type 'alist))
   2846            (format-data-as-org (lambda (l)
   2847                                  (format "* TODO %s :flatastic:\n  SCHEDULED: <%s>\n  Points: %d\n"
   2848                                          (alist-get 'description l)
   2849                                          (alist-get 'scheduled_due_date l)
   2850                                          (alist-get 'point_value l))))
   2851            (org-flatastic-items (mapcar format-data-as-org api-data)))
   2852       (with-current-buffer (find-file-noselect za/org-life-inbox)
   2853         (goto-char (point-max))
   2854         (insert "\n" (string-join org-flatastic-items "\n")))
   2855       (message "Synced %d Flatastic tasks to inbox" (length api-data))))
   2856 #+end_src
   2857 *** Link to Thunderbird messages
   2858 Create a custom link to open thunderbird emails by ID:
   2859 
   2860 #+begin_src emacs-lisp
   2861   (org-link-set-parameters
   2862    "thunderbird"
   2863    :follow #'za/org-link-thunderbird-follow)
   2864 
   2865   (defun za/org-link-thunderbird-follow (messageid)
   2866     "Open the message with id `messageid` in Thunderbird"
   2867     (shell-command (format "thunderbird mid:%s" (shell-quote-argument messageid))))
   2868 #+end_src
   2869 *** Inverse refile
   2870 #+begin_src emacs-lisp
   2871   (defun za/org-refile-to-point (refloc)
   2872     "Prompt for a heading and refile it to point."
   2873     (interactive (list (org-refile-get-location "Heading: ")))
   2874     (let* ((file (nth 1 refloc))
   2875            (pos (nth 3 refloc)))
   2876       (save-excursion
   2877         (with-current-buffer (find-file-noselect file 'noward)
   2878           (save-excursion
   2879             (save-restriction
   2880               (widen)
   2881               (goto-char pos)
   2882               (org-copy-subtree 1 t))))
   2883         (org-paste-subtree nil nil nil t))))
   2884 
   2885 
   2886   (defun za/org-refile-wrapper (arg)
   2887     "Wrap org-refile so that it refiles some heading to point with a negative argument"
   2888     (interactive "P")
   2889     (if (cl-minusp (prefix-numeric-value arg))
   2890         (call-interactively #'za/org-refile-to-point)
   2891       (org-refile arg)))
   2892 
   2893 #+end_src
   2894 
   2895 *** org-caldav
   2896 This lets me sync my Org agenda to my CalDAV server.
   2897 The main reason is because Orgzly doesn't have a calendar view and can't (yet) search for events on a specific day, so if someone asks "are you free on that day", it's a bit hard for me to answer if I don't have my computer with me.
   2898 This way, I can just check my calendar.
   2899 
   2900 #+begin_src emacs-lisp
   2901   (if (and (boundp 'za/caldav-url)
   2902            (boundp 'za/caldav-org-calendar-id)
   2903            (boundp 'za/org-life-calendar-inbox))
   2904       (use-package org-caldav
   2905         :init
   2906         (defconst za/org-life-calendar-inbox (concat za/org-life-dir "calendar-inbox.org"))
   2907         :custom
   2908         (org-caldav-url za/caldav-url)
   2909         (org-caldav-calendar-id za/caldav-org-calendar-id)
   2910         (org-caldav-inbox za/org-life-calendar-inbox)
   2911         (org-caldav-files (cons (car (split-string org-archive-location "::")) org-agenda-files))
   2912         (org-caldav-sync-todo nil)
   2913         (org-icalendar-include-todo nil)
   2914         (org-icalendar-use-deadline '(event-if-todo-not-done))
   2915         (org-icalendar-use-scheduled '(event-if-todo-not-done))
   2916         (org-caldav-exclude-tags '("HABIT")
   2917                                  "I don't want to export habits, because those will just clutter up my calendar. The calendar is supposed to be for one-off stuff, or rarely repeating stuff. Yes, I have to manually add the HABIT tag to every habit. Perhaps nicer would be to exclude based on the property ~:STYLE: habit~, but I haven't figured that one out yet.")
   2918         (org-caldav-todo-percent-states '((0 "TODO")
   2919                                           (0 "WAITING")
   2920                                           (1 "NEXT")
   2921                                           (2 "STARTED")
   2922                                           (0 "PROJ")
   2923                                           (100 "DONE")
   2924                                           (100 "CANCELLED")))
   2925         :config
   2926         (defun za/caldav-after-sync-notify () (za/notify "org-caldav sync complete" "Finished syncing"))
   2927         (advice-add #'org-caldav-sync :after #'za/caldav-after-sync-notify)
   2928         (advice-add #'org-caldav-sync :around #'za/notify-on-interactivity))
   2929     (warn "za/caldav-url, za/caldav-org-calendar-id, za/org-life-calendar-inbox not bound, not using org-caldav."))
   2930 #+end_src
   2931 
   2932 Maybe check [[https://old.reddit.com/r/orgmode/comments/8rl8ep/making_orgcaldav_useable/e0sb5j0/][this]] for a way to sync on save.
   2933 
   2934 *** org-ref
   2935 #+begin_src emacs-lisp
   2936   (use-package org-ref)
   2937 #+end_src
   2938 *** org-roam
   2939 #+begin_src emacs-lisp
   2940   (use-package org-roam
   2941     :custom
   2942     (org-roam-directory za/org-roam-dir)
   2943     (org-roam-completion-everywhere t)
   2944     (org-roam-dailies-capture-templates
   2945      '(("d" "default" entry
   2946         "* %U\n%?"
   2947         :target (file+head "%<%Y-%m-%d>.org"
   2948                            "#+title: %<%Y-%m-%d>\n"))))
   2949     :config
   2950                                           ; can't use nil because org-roam-ui checks for boundp on this and
   2951                                           ; errors if bound but nil.
   2952     (with-eval-after-load 'org-roam-dailies
   2953       (makunbound 'org-roam-dailies-directory))
   2954     (defun za/org-roam-dailies-goto-latest-note ()
   2955     (interactive)
   2956     (unless (boundp 'org-roam-dailies-directory)
   2957       (za/org-roam-dailies-select-dir))
   2958     (let* ((dailies (seq-filter
   2959                      (lambda (e) (let ((file-date (file-name-base e)))
   2960                                    (and (not (string= "marginalia" file-date))
   2961                                         (or (time-less-p (date-to-time file-date) (current-time))
   2962                                             (time-equal-p (date-to-time file-date) (current-time))))))
   2963                      (org-roam-dailies--list-files)))
   2964            (latest-note (car (last dailies))))
   2965       (unless latest-note
   2966         (user-error "Can't find latest note"))
   2967       (find-file latest-note)
   2968       (run-hooks 'org-roam-dailies-find-file-hook)))
   2969     (org-roam-setup)
   2970     (bind-keys :prefix "C-c w"
   2971                :prefix-map za/org-roam-map
   2972                :prefix-docstring "Org roam"
   2973                ("n" . org-roam-capture)
   2974                ("f" . org-roam-node-find)
   2975                ("w" . org-roam-buffer-toggle)
   2976                ("i" . org-roam-node-insert))
   2977     (bind-keys :prefix "C-c j"
   2978                :prefix-map za/org-roam-dailies-map
   2979                :prefix-docstring "Org roam dailies"
   2980                ("s" . za/org-roam-dailies-select-dir)
   2981                ("n" . org-roam-dailies-capture-today)
   2982                ("j" . org-roam-dailies-goto-today)
   2983                ("+" . org-roam-dailies-goto-tomorrow)
   2984                (">" . org-roam-dailies-goto-next-note)
   2985                ("-" . org-roam-dailies-goto-yesterday)
   2986                ("<" . org-roam-dailies-goto-previous-note)
   2987                ("g" . org-roam-dailies-goto-date)
   2988                ("l" . za/org-roam-dailies-goto-latest-note)
   2989                ("." . org-roam-dailies-find-directory))
   2990 
   2991     (defun za/org-roam-dailies--daily-note-p (&optional file)
   2992       "Replacement of default function. Return t if FILE is an Org-roam daily-note, nil otherwise.
   2993   If FILE is not specified, use the current buffer's file-path."
   2994       (when-let ((path (expand-file-name
   2995                         (or file
   2996                             (buffer-file-name (buffer-base-buffer)))))
   2997                  (directory (expand-file-name org-roam-dailies-directory org-roam-directory)))
   2998         (setq path (expand-file-name path))
   2999         (save-match-data
   3000           (and
   3001            ;; (org-roam-file-p path) ; don't want this, dailies might not be in org-roam path
   3002            (org-roam-descendant-of-p path directory)))))
   3003     (advice-add #'org-roam-dailies--daily-note-p :override #'za/org-roam-dailies--daily-note-p)
   3004 
   3005     (defun za/org-roam-dailies-select-dir ()
   3006       "Select an org-roam-dailies folder."
   3007       (interactive)
   3008       (let* ((choices (cons '(?0 nil) za/org-roam-dailies-dirs))
   3009              (choice (nth 1 (read-multiple-choice "org-roam-dailies dir" choices))))
   3010         (if choice
   3011             (progn (setq org-roam-dailies-directory choice)
   3012                    (message "Selected org-roam-dailies directory: %s" org-roam-dailies-directory))
   3013           (makunbound 'org-roam-dailies-directory))))
   3014 
   3015     (defun za/org-roam-dailies-calendar-mark-entries-p ()
   3016       "Only mark dailies entries in calendar if a dailies directory is set."
   3017       (boundp 'org-roam-dailies-directory))
   3018     (advice-add #'org-roam-dailies-calendar-mark-entries :before-while #'za/org-roam-dailies-calendar-mark-entries-p)
   3019 
   3020     ;; Before doing anything journal-related, check that a journal is
   3021     ;; selected, or prompt for one.
   3022     (defun za/org-roam-dailies--capture-check-non-nil-dailies-dir (&rest _)
   3023       (unless (boundp 'org-roam-dailies-directory)
   3024         (za/org-roam-dailies-select-dir))
   3025       (unless (boundp 'org-roam-dailies-directory)
   3026         (user-error "No org-roam-dailies-directory selected!")))
   3027 
   3028     (advice-add #'org-roam-dailies--capture :before #'za/org-roam-dailies--capture-check-non-nil-dailies-dir)
   3029     (advice-add #'org-roam-dailies-goto-date :before #'za/org-roam-dailies--capture-check-non-nil-dailies-dir)
   3030     (require 'org-roam-export))
   3031 #+end_src
   3032 
   3033 *** org-roam-ui
   3034 #+begin_src emacs-lisp
   3035   (use-package org-roam-ui)
   3036 #+end_src
   3037 *** org-download
   3038 Drag-and-drop images to Emacs Org mode.
   3039 
   3040 #+begin_src emacs-lisp
   3041   (use-package org-download
   3042     :custom
   3043     (org-download-method 'attach)
   3044     (org-download-backend t))
   3045 #+end_src
   3046 
   3047 *** org-sticky-header
   3048 Displays in the header-line the Org heading for the node that’s at the top of the window.
   3049 
   3050 #+begin_src emacs-lisp
   3051   (use-package org-sticky-header)
   3052 #+end_src
   3053 *** org-timestone
   3054 #+begin_src emacs-lisp
   3055   (use-package org-timestone
   3056     :init (za/package-vc-install :repo "thezeroalpha/org-timestone.el")
   3057     :ensure nil
   3058     :after org
   3059     :bind (:map org-mode-map
   3060                 ("C-c C-t" . org-timestone-org-todo-wrapper)))
   3061 #+end_src
   3062 *** org-noter
   3063 #+begin_src emacs-lisp
   3064   (use-package org-noter
   3065     :config
   3066     ;; Fix disabling of line wrap by no-opping set-notes-scroll
   3067     (advice-add 'org-noter--set-notes-scroll :override 'za/no-op))
   3068 #+end_src
   3069 *** el-easydraw
   3070 Lets you draw stuff in org mode documents.
   3071 
   3072 #+begin_src emacs-lisp :tangle no
   3073   (za/package-vc-install :repo "misohena/el-easydraw" :name "edraw")
   3074   (with-eval-after-load 'org
   3075     (require 'edraw-org)
   3076     (edraw-org-setup-default)
   3077     (bind-key "C-c q c" #'edraw-color-picker-insert-color))
   3078 #+end_src
   3079 *** ox-jira
   3080 #+begin_src emacs-lisp
   3081   (use-package ox-jira)
   3082 #+end_src
   3083 *** org-confluence
   3084 ox-confluence with some custom code to remove the theme & create expandable drawers.
   3085 Add to confluence by pressing ~ctrl + shift + d~ when editing a page and inserting confluence wiki text.
   3086 
   3087 #+begin_src emacs-lisp
   3088   (require 'ox-confluence)
   3089   (org-export-define-derived-backend 'confluence-ext 'confluence
   3090     :translate-alist '((drawer . za/org-confluence-drawer))
   3091     :filters-alist '((:filter-src-block . za/org-confluence--code-block-remove-theme))
   3092     :menu-entry
   3093     '(?F "Export to Confluence (ext)"
   3094          ((?F "As Confluence buffer (ext)" za/org-confluence-export-as-confluence))))
   3095 
   3096   (defun za/org-confluence-export-as-confluence
   3097       (&optional async subtreep visible-only body-only ext-plist)
   3098     (interactive)
   3099     (org-export-to-buffer 'confluence-ext "*org CONFLUENCE Export*"
   3100       async subtreep visible-only body-only ext-plist (lambda () (text-mode))))
   3101 
   3102   (defun za/org-confluence--code-block-remove-theme (block _backend _info)
   3103     "Remove the theme from the block"
   3104     (replace-regexp-in-string (rx "\{code:theme=Emacs" (? "|")) "\{code:" block))
   3105 
   3106 
   3107   (defun za/org-confluence-drawer (drawer contents info)
   3108     "Handle custom drawers"
   3109     (let* ((name (org-element-property :drawer-name drawer)))
   3110       (concat
   3111        (format "\{expand:%s\}\n" name)
   3112        contents
   3113        "\{expand\}")))
   3114 #+end_src
   3115 *** TODO the path for org-roam export and data export should be configurable, not hard-coded
   3116 ** Mail mode for neomutt
   3117 When editing a message from neomutt, I want to use mail mode.
   3118 Even though I won't be sending the email from there, I like the syntax highlighting :)
   3119 
   3120 #+begin_src emacs-lisp
   3121   (add-to-list 'auto-mode-alist '("/neomutt-" . mail-mode))
   3122 #+end_src
   3123 ** DISABLED Semantic mode
   3124 Disabled for now, don't use it much.
   3125 SemanticDB is written into ~/.emacs.d/semanticdb/.
   3126 
   3127 #+begin_src emacs-lisp :tangle no
   3128   (use-package semantic
   3129     :bind (:map semantic-mode-map
   3130                 ("C-c , ." . semantic-ia-show-summary))
   3131     :custom
   3132     (semantic-default-submodes '(global-semantic-idle-scheduler-mode ; reparse buffer when idle
   3133                                  global-semanticdb-minor-mode ; maintain database
   3134                                  global-semantic-idle-summary-mode  ; show information (e.g. types) about tag at point
   3135                                  global-semantic-stickyfunc-mode))) ; show current func in header line
   3136 
   3137 
   3138 #+end_src
   3139 
   3140 ** Bib(la)tex
   3141 #+begin_src emacs-lisp
   3142   (use-package bibtex
   3143     :config
   3144     (bibtex-set-dialect "biblatex"))
   3145 #+end_src
   3146 
   3147 ** Python
   3148 In Python, I want to enable flycheck and semantic mode:
   3149 
   3150 #+begin_src emacs-lisp
   3151   (add-hook 'python-mode-hook #'flycheck-mode)
   3152   ;;(add-hook 'python-mode-hook #'semantic-mode)
   3153 #+end_src
   3154 
   3155 ** Elisp
   3156 #+begin_src emacs-lisp
   3157   (use-package emacs-lisp
   3158     :ensure nil ; preinstalled
   3159     :hook ((emacs-lisp-mode . flycheck-mode)
   3160            (emacs-lisp-mode . rainbow-mode)
   3161            (emacs-lisp-mode . outline-minor-mode)
   3162            (emacs-lisp-mode . company-mode)))
   3163 #+end_src
   3164 ** lean-mode
   3165 Specifically for the Lean prover.
   3166 I also install company-lean and helm-lean, which are suggested on the [[https://github.com/leanprover/lean-mode][Github page]].
   3167 Then I map company-complete only for lean-mode.
   3168 
   3169 #+begin_src emacs-lisp
   3170   (use-package lean-mode
   3171     :config
   3172     (use-package company-lean)
   3173     :bind (:map lean-mode-map
   3174                 ("S-SPC" . company-complete)))
   3175 #+end_src
   3176 
   3177 ** sh-mode
   3178 #+begin_src emacs-lisp :results value
   3179   (use-package sh-script
   3180     :hook (sh-mode . flycheck-mode))
   3181 #+end_src
   3182 
   3183 ** anki-editor
   3184 Some extra keybindings that are not set up by default.
   3185 anki-editor doesn't provide a keymap so I have to set one up here:
   3186 
   3187 #+begin_src emacs-lisp
   3188   (use-package anki-editor
   3189     :init
   3190     (defvar anki-editor-mode-map (make-sparse-keymap))
   3191     (add-to-list 'minor-mode-map-alist (cons 'anki-editor-mode
   3192                                              anki-editor-mode-map))
   3193     :custom
   3194     (anki-editor-use-math-jax t)
   3195 
   3196     :bind (:map anki-editor-mode-map
   3197                 ("C-c t" . org-property-next-allowed-value)
   3198                 ("C-c i" . anki-editor-insert-note)
   3199                 ("C-c p" . anki-editor-push-notes)
   3200                 ("C-c c" . anki-editor-cloze-dwim)))
   3201 #+end_src
   3202 ** pdf-tools
   3203 A better replacement for DocView:
   3204 
   3205 #+begin_src emacs-lisp
   3206   (use-package pdf-tools
   3207     :init
   3208     (pdf-tools-install)
   3209 
   3210     :custom
   3211     (pdf-annot-default-annotation-properties '((t
   3212                                                 (label . "Alex Balgavy"))
   3213                                                (text
   3214                                                 (icon . "Note")
   3215                                                 (color . "#0088ff"))
   3216                                                (highlight
   3217                                                 (color . "yellow"))
   3218                                                (squiggly
   3219                                                 (color . "orange"))
   3220                                                (strike-out
   3221                                                 (color . "red"))
   3222                                                (underline
   3223                                                 (color . "blue"))))
   3224     :bind (:map pdf-isearch-minor-mode-map
   3225                 ("C-s" . isearch-forward)
   3226                 :map pdf-view-mode-map
   3227                 ;; Save position & jump back
   3228                 ("C-SPC" . (lambda () (interactive) (message "Position saved") (pdf-view-position-to-register ?x)))
   3229                 ("C-u C-SPC" . (lambda () (interactive) (pdf-view-jump-to-register ?x))))
   3230     :hook
   3231     (pdf-annot-list-mode . pdf-annot-list-follow-minor-mode)
   3232     (pdf-annot-edit-contents-minor-mode . org-mode)
   3233     (pdf-view-mode . (lambda () (display-line-numbers-mode 0)))
   3234 
   3235     :config
   3236     ;; The arrow tooltip does not show properly when jumping to a
   3237     ;; location. Maybe this is a Mac-only thing. See here:
   3238     ;; https://github.com/politza/pdf-tools/issues/145
   3239     ;; This ~:override~ advice fixes it, color is customized via ~tooltip~ face
   3240     (advice-add #'pdf-util-tooltip-arrow :override #'za/pdf-util-tooltip-arrow)
   3241     (defun za/pdf-util-tooltip-arrow (image-top &optional timeout)
   3242       "Fix up `pdf-util-tooltip-arrow`, the original doesn't show the arrow."
   3243       (pdf-util-assert-pdf-window)
   3244       (when (floatp image-top)
   3245         (setq image-top
   3246               (round (* image-top (cdr (pdf-view-image-size))))))
   3247       (let* (x-gtk-use-system-tooltips ;allow for display property in tooltip
   3248              (dx (+ (or (car (window-margins)) 0)
   3249                     (car (window-fringes))))
   3250              (dy image-top)
   3251              (pos (list dx dy dx (+ dy (* 2 (frame-char-height)))))
   3252              (vscroll
   3253               (pdf-util-required-vscroll pos))
   3254              (tooltip-frame-parameters
   3255               `((border-width . 0)
   3256                 (internal-border-width . 0)
   3257                 ,@tooltip-frame-parameters))
   3258              (tooltip-hide-delay (or timeout 3)))
   3259         (when vscroll
   3260           (image-set-window-vscroll vscroll))
   3261         (setq dy (max 0 (- dy
   3262                            (cdr (pdf-view-image-offset))
   3263                            (window-vscroll nil t)
   3264                            (frame-char-height))))
   3265         (when (overlay-get (pdf-view-current-overlay) 'before-string)
   3266           (let* ((e (window-inside-pixel-edges))
   3267                  (xw (pdf-util-with-edges (e) e-width)))
   3268             (cl-incf dx (/ (- xw (car (pdf-view-image-size t))) 2))))
   3269         (pdf-util-tooltip-in-window "\u2192" dx dy))))
   3270 #+end_src
   3271 
   3272 *** TODO this clobbers register x. Find a way to not clobber a register
   3273 ** virtualenvwrapper
   3274 Like virtualenvwrapper.sh, but for Emacs.
   3275 
   3276 #+begin_src emacs-lisp
   3277   (use-package virtualenvwrapper
   3278     :custom
   3279     (venv-location "~/.config/virtualenvs")
   3280 
   3281     :config
   3282     (venv-initialize-interactive-shells)
   3283     (venv-initialize-eshell))
   3284 #+end_src
   3285 
   3286 ** ledger
   3287 #+begin_src emacs-lisp
   3288   (use-package ledger-mode
   3289     :mode ("\\.ledger\\'")
   3290     :hook (ledger-mode . company-mode)
   3291     :custom
   3292     (ledger-clear-whole-transactions t)
   3293     (ledger-reconcile-default-commodity "eur")
   3294     (ledger-reports
   3295      '(("unreconciled" "%(binary) [[ledger-mode-flags]] -f %(ledger-file) --start-of-week=1 reg --uncleared")
   3296        ("net-worth-changes" "%(binary) [[ledger-mode-flags]] -f %(ledger-file) reg ^Assets ^Liabilities -R -M -X eur --effective -n")
   3297        ("budget-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective -X eur --period \"last month\" budget ^expenses:budgeted")
   3298        ("budget-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective -X eur --period \"this month\" budget ^expenses:budgeted")
   3299        ("expenses-this-month-vs-budget" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^expenses:budgeted --budget -R")
   3300        ("expenses-last-month-vs-budget" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses:budgeted --budget -R")
   3301        ("expenses-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses -X eur -R")
   3302        ("expenses-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^expenses -X eur -R")
   3303        ("expenses-vs-income-this-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"this month\" --period-sort \"(amount)\" bal ^income ^expenses -X eur -R")
   3304        ("expenses-vs-income-last-month" "%(binary) -f %(ledger-file) --start-of-week=1 --effective --period \"last month\" --period-sort \"(amount)\" bal ^expenses ^income -X eur -R")
   3305        ("bal-assets-czk" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -X czk -R")
   3306        ("bal-assets" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -R")
   3307        ("bal" "%(binary) -f %(ledger-file) --start-of-week=1 bal -B -R")
   3308        ("bal-assets-eur" "%(binary) -f %(ledger-file) --start-of-week=1 bal Assets Liabilities -X eur -R")
   3309        ("monthly-balance-abn-checking" "%(binary) -f %(ledger-file) --start-of-week=1 --effective reg --monthly 'Assets:ABN Checking' -R")
   3310        ("monthly-expenses" "%(binary) -f %(ledger-file) --monthly register ^expenses --effective --collapse -X eur -R")
   3311        ("reg" "%(binary) -f %(ledger-file) --start-of-week=1 reg -R")
   3312        ("payee" "%(binary) -f %(ledger-file) --start-of-week=1 reg @%(payee) -R")
   3313        ("account" "%(binary) -f %(ledger-file) --start-of-week=1 reg %(account) -R")
   3314        ("reg-org-table" "%(binary) -f %(ledger-file) csv --csv-format '|%(scrub(date))|%(scrub(display_account))|%(scrub(payee))|%(scrub(display_amount))|%(scrub(display_total))|
   3315   ' %(account) -R")))
   3316     :config
   3317     (with-eval-after-load 'ledger-mode
   3318       (setq ledger-amount-regex
   3319             (rx
   3320              (group (or (= 2 " ") ?\t (seq " " ?\t)))
   3321              (zero-or-more (any " " ?\t))
   3322              (opt "=")
   3323              (zero-or-more space)
   3324              (opt "-")
   3325              (opt "(")
   3326              (one-or-more (opt (group
   3327                                 (one-or-more (any "A-Z" "$(_£€₹"))
   3328                                 (zero-or-more blank)))
   3329                           (group (opt "-")
   3330                                  (or (one-or-more (any "0-9"))
   3331                                      (+\? (any "0-9" ",."))))
   3332                           (opt (group (any ",.")
   3333                                       (one-or-more (any "0-9" ")"))))
   3334                           (opt (group (zero-or-more blank)
   3335                                       (one-or-more (any "\"_£€₹" word))))
   3336                           (opt (zero-or-more (any blank))
   3337                                (any "*+/-")
   3338                                (zero-or-more (any blank))))
   3339              (opt ")")
   3340              (opt (group (zero-or-more (any blank))
   3341                          (any "=@{")
   3342                          (opt "@")
   3343                          (+? (not (any ?\xA ";")))))
   3344              (opt (group (or (seq (one-or-more (any blank)) ";" (+\? nonl))
   3345                              (zero-or-more (any blank)))))
   3346              eol))))
   3347 #+end_src
   3348 
   3349 org-capture lets me add transactions from anywhere in Emacs:
   3350 
   3351 Budget throws an error when there's multiple commodities involved.
   3352 See discussion here: https://github.com/ledger/ledger/issues/1450#issuecomment-390067165
   3353 
   3354 #+begin_src emacs-lisp
   3355   (defconst za/ledger-budget-fix-string
   3356     "-X eur -F '%(justify(scrub(get_at(display_total, 0)), 20, -1, true, false)) %(justify(get_at(display_total, 1) ? -scrub(get_at(display_total, 1)) : 0.0, 20,            20 + 1 + 20, true, false)) %(justify(get_at(display_total, 1) ? (get_at(display_total, 0) ?           -(scrub(get_at(display_total, 1) + get_at(display_total, 0))) :           -(scrub(get_at(display_total, 1)))) : -(scrub(get_at(display_total, 0))), 20,            20 + 1 + 20 + 1 + 20, true, false))%(get_at(display_total, 1) and (abs(quantity(scrub(get_at(display_total, 0))) /           quantity(scrub(get_at(display_total, 1)))) >= 1) ?  \" \" : \" \")%(justify((get_at(display_total, 1) ?           (100% * (get_at(display_total, 0) ? scrub(get_at(display_total, 0)) : 0.0)) /              -scrub(get_at(display_total, 1)) : \"na\"),            5, -1, true, false))  %(!options.flat ? depth_spacer : \"\")%-(partial_account(options.flat))\n%/%$2 %$3 %$4 %$6\n%/%(prepend_width ? \" \" * int(prepend_width) : \"\")    ----------------     ----------------     ---------------- -----\n'"
   3357     "Append this to a ledger budget to fix errors with multiple commodities.")
   3358 #+end_src
   3359 
   3360 ** Notmuch
   3361 #+begin_src emacs-lisp
   3362   (use-package notmuch
   3363     :custom
   3364     (notmuch-saved-searches
   3365      `((:name "inbox: personal" :query ,(format "folder:/%s/ tag:inbox" za/email-personal) :key ,(kbd "ip") :search-type 'tree)
   3366        (:name "inbox: school" :query ,(format "folder:/%s/ tag:inbox" za/email-vu) :key ,(kbd "is") :search-type 'tree)
   3367        (:name "archive: personal" :query ,(format "folder:/%s/ tag:archive" za/email-personal) :key ,(kbd "ap") :search-type 'tree)
   3368        (:name "archive: school" :query ,(format "folder:/%s/ tag:archive" za/email-vu) :key ,(kbd "as") :search-type 'tree))
   3369      "Define some saved searches (i.e. mailboxes)")
   3370     (notmuch-hello-sections
   3371      '(notmuch-hello-insert-header
   3372        notmuch-hello-insert-saved-searches
   3373        notmuch-hello-insert-search
   3374        notmuch-hello-insert-alltags
   3375        notmuch-hello-insert-footer)
   3376      "Define the main screen sections")
   3377     (notmuch-search-oldest-first nil "Show newest mail first")
   3378     (notmuch-archive-tags '("-inbox" "+archive"))
   3379     (notmuch-tagging-keys '(("a" notmuch-archive-tags "Archive")
   3380                             ("r" notmuch-show-mark-read-tags "Mark read")
   3381                             ("u" notmuch-show-mark-unread-tags "Mark unread")
   3382                             ("d" notmuch-delete-tags "Delete")))
   3383 
   3384     :bind (("C-c m" . notmuch)
   3385            :map notmuch-show-mode-map
   3386            ("C-c M-y" . shr-copy-url))
   3387     ;; Run notmuch-hook script on hello refresh, to move messages to
   3388     ;; folders according to their tags:
   3389     :hook (notmuch-hello-refresh . za/notmuch-hook-tags2folders)
   3390     :init (setenv "NOTMUCH_CONFIG" "/Users/alex/.config/notmuch/config")
   3391     :config
   3392     (setq notmuch-show-mark-unread-tags '("+unread"))
   3393     (setq notmuch-delete-tags '("-inbox" "+trash"))
   3394     (defun za/notmuch-hook-tags2folders ()
   3395       "Run notmuch-hook to organise email in folders based on tags."
   3396       (start-process "notmuch-hook" nil "notmuch-hook" "--tags2folders")))
   3397 #+end_src
   3398 
   3399 ** MPC
   3400 #+begin_src emacs-lisp
   3401   (use-package mpc
   3402     :custom
   3403     (mpc-browser-tags '(AlbumArtist Album Genre Playlist)
   3404                       "Set the windows I want to show")
   3405 
   3406     :bind (:map mpc-mode-map
   3407                 ("a" . mpc-playlist-add)
   3408                 ("P" . mpc-playlist)
   3409                 ("x" . mpc-playlist-delete)
   3410                 ("p" . mpc-toggle-play)
   3411                 ("t" . mpc-select-toggle)
   3412                 ("f" . za/mpc-seek-forward-20-seconds)
   3413                 ("b" . za/mpc-seek-backward-20-seconds))
   3414     :config
   3415     (defun za/mpc-seek-forward-20-seconds ()
   3416       "Seek forward 20 seconds"
   3417       (interactive)
   3418       (mpc-seek-current "+20"))
   3419 
   3420     (defun za/mpc-seek-backward-20-seconds ()
   3421       "Seek backward 20 seconds"
   3422       (interactive)
   3423       (mpc-seek-current "-20")))
   3424 #+end_src
   3425 ** Dired
   3426 #+begin_src emacs-lisp
   3427   (use-package dired
   3428     :ensure nil ; installed with Emacs
   3429     :bind (:map dired-mode-map
   3430                 ;; 'i' expands subdirs, so I want to be able to close them too.
   3431                 ("M-k" . dired-kill-subdir))
   3432     :custom
   3433     (dired-listing-switches "-alhv")
   3434     (dired-dwim-target t "If I have another dired window open, use that as target")
   3435     ;; By default, hide details (show again by pressing oparen):
   3436     :hook (dired-mode . dired-hide-details-mode))
   3437 #+end_src
   3438 
   3439 ** ess: statistics (R, SAS...)
   3440 #+begin_src emacs-lisp
   3441   (use-package ess)
   3442 #+end_src
   3443 
   3444 ** help mode
   3445 #+begin_src emacs-lisp
   3446   (use-package help-mode
   3447     :ensure nil ; included with Emacs
   3448     :hook (help-mode . za/settings-on-help-mode)
   3449     :config
   3450     (defun za/settings-on-help-mode ()
   3451       "Settings on enabling help mode"
   3452       (za/toggle-wrap t)))
   3453 #+end_src
   3454 ** helpful
   3455 An alternative to the built-in Emacs help that provides much more contextual information.
   3456 I use counsel, so I use the keybindings in [[*counsel + ivy + swiper]].
   3457 I just augment the functions counsel uses.
   3458 Also, counsel doesn't provide some keybindings that I can get from helpful.
   3459 
   3460 #+begin_src emacs-lisp
   3461   (use-package helpful
   3462     :custom
   3463     (counsel-describe-symbol-function #'helpful-symbol)
   3464     (counsel-describe-function-function #'helpful-callable)
   3465     (counsel-describe-variable-function #'helpful-variable)
   3466 
   3467     :bind (("C-h k" . helpful-key)
   3468            ("C-h C" . helpful-command)
   3469            :map helpful-mode-map
   3470            ("l" . za/helpful-previous)
   3471            ("r" . za/helpful-next))
   3472 
   3473     :hook (helpful-mode . za/settings-on-helpful-mode)
   3474     :config
   3475 
   3476     (defun za/settings-on-helpful-mode ()
   3477       "Settings on enabling helpful mode"
   3478       (za/toggle-wrap t))
   3479 
   3480     ;; Then, a way to jump forward and backward in the window:
   3481     (defvar za/helpful-buffer-ring-size 20
   3482       "How many buffers are stored for use with `helpful-next'.")
   3483 
   3484     (defvar za/helpful--buffer-ring (make-ring za/helpful-buffer-ring-size)
   3485       "Ring that stores the current Helpful buffer history.")
   3486 
   3487     (defun za/helpful--buffer-index (&optional buffer)
   3488       "If BUFFER is a Helpful buffer, return it’s index in the buffer ring."
   3489       (let ((buf (or buffer (current-buffer))))
   3490         (and (eq (buffer-local-value 'major-mode buf) 'helpful-mode)
   3491              (seq-position (ring-elements za/helpful--buffer-ring) buf #'eq))))
   3492 
   3493     (defun za/helpful--new-buffer-a (help-buf)
   3494       "Update the buffer ring according to the current buffer and HELP-BUF."
   3495       :filter-return #'helpful--buffer
   3496       (let ((buf-ring za/helpful--buffer-ring))
   3497         (let ((newer-buffers (or (za/helpful--buffer-index) 0)))
   3498           (dotimes (_ newer-buffers) (ring-remove buf-ring 0)))
   3499         (when (/= (ring-size buf-ring) za/helpful-buffer-ring-size)
   3500           (ring-resize buf-ring za/helpful-buffer-ring-size))
   3501         (ring-insert buf-ring help-buf)))
   3502 
   3503     (advice-add #'helpful--buffer :filter-return #'za/helpful--new-buffer-a)
   3504 
   3505     (defun za/helpful--next (&optional buffer)
   3506       "Return the next live Helpful buffer relative to BUFFER."
   3507       (let ((buf-ring za/helpful--buffer-ring)
   3508             (index (or (za/helpful--buffer-index buffer) -1)))
   3509         (cl-block nil
   3510           (while (> index 0)
   3511             (cl-decf index)
   3512             (let ((buf (ring-ref buf-ring index)))
   3513               (if (buffer-live-p buf) (cl-return buf)))
   3514             (ring-remove buf-ring index)))))
   3515 
   3516 
   3517     (defun za/helpful--previous (&optional buffer)
   3518       "Return the previous live Helpful buffer relative to BUFFER."
   3519       (let ((buf-ring za/helpful--buffer-ring)
   3520             (index (1+ (or (za/helpful--buffer-index buffer) -1))))
   3521         (cl-block nil
   3522           (while (< index (ring-length buf-ring))
   3523             (let ((buf (ring-ref buf-ring index)))
   3524               (if (buffer-live-p buf) (cl-return buf)))
   3525             (ring-remove buf-ring index)))))
   3526 
   3527     (defun za/helpful-next ()
   3528       "Go to the next Helpful buffer."
   3529       (interactive)
   3530       (when-let (buf (za/helpful--next))
   3531         (funcall helpful-switch-buffer-function buf)))
   3532 
   3533     (defun za/helpful-previous ()
   3534       "Go to the previous Helpful buffer."
   3535       (interactive)
   3536       (when-let (buf (za/helpful--previous))
   3537         (funcall helpful-switch-buffer-function buf))))
   3538 #+end_src
   3539 ** Tex-mode
   3540 #+begin_src emacs-lisp
   3541   (use-package tex-mode
   3542     :ensure nil ; installed with Emacs
   3543     :hook (tex-mode . za/settings-on-tex-mode)
   3544     :config
   3545     (defun za/settings-on-tex-mode ()
   3546       "Settings on enabling helpful mode"
   3547       (setq comment-add 0)))
   3548 #+end_src
   3549 ** Quail
   3550 #+begin_src emacs-lisp
   3551   (use-package quail
   3552     :ensure nil) ; provided by Emacs
   3553 #+end_src
   3554 ** Markdown
   3555 #+begin_src emacs-lisp
   3556   (use-package markdown-mode)
   3557 #+end_src
   3558 ** vdirel (contacts)
   3559 #+begin_src emacs-lisp
   3560   (use-package vdirel
   3561     :config
   3562     (vdirel-switch-repository "~/.local/share/contacts/default"))
   3563 #+end_src
   3564 ** Yaml
   3565 #+begin_src emacs-lisp
   3566   (use-package yaml-mode
   3567     :commands yaml-mode
   3568     :init
   3569     (add-hook 'yaml-mode-hook
   3570               (lambda ()
   3571                 (setq-local outline-regexp (rx (* blank)))
   3572                 (outline-minor-mode))))
   3573 #+end_src
   3574 ** calc
   3575 #+begin_src emacs-lisp
   3576   (use-package calc
   3577     :config
   3578     (setq math-additional-units
   3579      ;; elements:
   3580      ;; - symbol identifying the unit,
   3581      ;; - expression indicatingv alue of unit or nil for fundamental units
   3582      ;; - textual description
   3583      '((b nil "Bit")
   3584        (B "b * 8" "Bytes")
   3585        (KiB "1024 * B" "Kibibyte")
   3586        (MiB "1024 * KiB" "Mebibyte")
   3587        (GiB "1024 * MiB" "Gibibyte")
   3588        (TiB "1024 * GiB" "Tebibyte")
   3589        (PiB "1024 * TiB" "Pebibyte")
   3590        (EiB "1024 * PiB" "Exbibyte")
   3591        (ZiB "1024 * EiB" "Zebibyte")
   3592        (YiB "1024 * ZiB" "Yobibyte")
   3593        (KB "1000 * B" "Kilobyte")
   3594        (MB "1000 * KB" "Megabyte")
   3595        (GB "1000 * MB" "Gigabyte")
   3596        (TB "1000 * GB" "Terabyte")
   3597        (PB "1000 * TB" "Petabyte")
   3598        (EB "1000 * PB" "Exabyte")
   3599        (ZB "1000 * EB" "Zettabyte")
   3600        (YB "1000 * ZB" "Yottabyte")
   3601        (Kib "1024 * b" "Kibibit")
   3602        (Mib "1024 * Kib" "Mebibit")
   3603        (Gib "1024 * Mib" "Gibibit")
   3604        (Kb "1000 * b" "Kilobit")
   3605        (Mb "1000 * Kb" "Megabit")
   3606        (Gb "1000 * Mb" "Gigabit")))
   3607     (setq math-units-table nil))
   3608 #+end_src
   3609 ** casual
   3610 #+begin_src emacs-lisp
   3611   (use-package casual
   3612     :config
   3613     (require 'casual-image)
   3614     (require 'casual-ediff)
   3615     :bind (:map calc-mode-map
   3616            ("C-o" . 'casual-calc-tmenu)
   3617            :map dired-mode-map
   3618            ("C-o" . 'casual-dired-tmenu)
   3619            ("C-u C-o" . 'dired-display-file)
   3620            :map calendar-mode-map
   3621            ("C-o" . 'casual-calendar-tmenu)
   3622            :map image-mode-map
   3623            ("C-o" . 'casual-image-tmenu)
   3624            :map ediff-mode-map
   3625            ("C-o" . 'casual-ediff-tmenu)))
   3626 #+end_src
   3627 ** json
   3628 #+begin_src emacs-lisp
   3629   (use-package json-mode)
   3630 #+end_src
   3631 ** rust
   3632 #+begin_src emacs-lisp
   3633   (use-package rust-mode)
   3634 #+end_src
   3635 ** artist mode
   3636 #+begin_src emacs-lisp
   3637   (use-package artist
   3638     :ensure nil ; included with emacs
   3639     :custom (artist-figlet-default-font "term")
   3640     :bind
   3641     (:map artist-mode-map
   3642           ([down-mouse-3] . artist-mouse-choose-operation)))
   3643 #+end_src
   3644 * Override some faces
   3645 #+begin_src emacs-lisp
   3646   (with-eval-after-load 'org-faces
   3647     (set-face-attribute 'org-table nil :inherit 'fixed-pitch)
   3648     (set-face-attribute 'org-block nil :inherit 'fixed-pitch))
   3649 #+end_src
   3650 * Shortdoc
   3651 Set a better keybinding (I'm never gonna use ~view-hello-file~ anyways):
   3652 
   3653 #+begin_src emacs-lisp
   3654   (bind-key "C-h z" #'shortdoc-display-group)
   3655 #+end_src
   3656 * Upcoming new features
   3657 In a new version of use-package, I can use the :vc keyword, so check for when that's available.
   3658 See [[https://git.savannah.gnu.org/cgit/emacs.git/commit/?id=2ce279680bf9c1964e98e2aa48a03d6675c386fe][commit]] and [[https://tony-zorman.com/posts/use-package-vc.html][article]].
   3659 
   3660 #+begin_src emacs-lisp
   3661   (when (fboundp 'use-package-vc-install)
   3662     (user-error "use-package :vc keyword now available!"))
   3663 #+end_src
   3664 * References
   3665 Here's a list of good articles I encountered about configging emacs:
   3666 - [[https://karthinks.com/software/batteries-included-with-emacs/][Batteries included with Emacs]]
   3667 - [[https://karthinks.com/software/more-batteries-included-with-emacs/][More batteries included with emacs]]
   3668 
   3669 For Org mode, [[https://www.youtube.com/playlist?list=PLVtKhBrRV_ZkPnBtt_TD1Cs9PJlU0IIdE][Rainer König's tutorials]] are the best.
   3670 [[https://emacs.cafe/emacs/orgmode/gtd/2017/06/30/orgmode-gtd.html][Here's a good reference for setting up gtd in org mode]]