dotfiles

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

config.org (144197B)


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