emacs-config/config.org

3687 lines
151 KiB
Org Mode
Raw Normal View History

#+TITLE: Doom Emacs Configuration
#+AUTHOR: tecosaur
#+PROPERTY: header-args:emacs-lisp :tangle yes :cache yes :results silent :comments link
#+PROPERTY: header-args :tangle no :results silent
#+HTML_HEAD: <link rel='shortcut icon' type='image/png' href='https://www.gnu.org/software/emacs/favicon.png'>
#+BEGIN_QUOTE
Let us change our traditional attitude to the construction of programs:
Instead of imagining that our main task is to instruct a computer what to do,
let us concentrate rather on explaining to human beings what we want a
computer to do. --- Donald Knuth
#+END_QUOTE
2020-01-20 18:08:07 +00:00
* Intro
Customising an editor can be very rewarding ... until you have to leave it.
For years I have been looking for ways to avoid this pain.
Then I discovered [[https://github.com/cknadler/vim-anywhere][vim-anywhere]], and found that it had an Emacs companion,[[https://github.com/zachcurry/emacs-anywhere][
2020-01-20 18:08:07 +00:00
emacs-anywhere]]. To me, this looked most attractive.
Separately, online I have seen the following statement enough times I think it's a catchphrase
#+BEGIN_QUOTE
Redditor1: I just discovered this thing, isn't it cool.
Redditor2: Oh, there's an emacs mode for that.
#+END_QUOTE
I tried out the =spacemacs= distribution a bit, but it wasn't quite to my liking.
Then I heard about =doom emacs= and thought I may as well give that a try.
TLDR; it's great.
Now I've discovered the wonders of literate programming, and am becoming more
settled by the day. This is my config, and also a cautionary tale.
[[xkcd:456]]
** Notes for the unwary adventurer
If you are so bold as to wish to steal bits of my config (or if I upgrade and
wonder why things aren't working), here's a list of sections which rely on
externally setup (i.e. outside of this config).
2020-04-29 08:47:48 +00:00
+ libvterm :: I rely on my distro-provided =libvterm.so=, [[*VTerm][vterm]] sets a compile flag.
If this causes issues, just delete the ~(setq term-module-cmake-args ...)~ bit.
2020-04-29 08:47:48 +00:00
+ dictionary :: I've downloaded a custom [[http://app.aspell.com/create][SCOWL]] dictionary, which I use in [[*Ispell][ispell]].
If this causes issues, just delete the ~(setq ispell-dictionary ...)~ bit.
+ uni-units file :: I've got a file in =~/.org/.uni-units= which I use in ~org-capture~
If this causes issues, just remove the reference to that file in [[*Capture][Capture]] and
instances of ~unit-prompt~ used in ~(doct ...)~
Oh, did I mention that I started this config when I didn't know any =elisp=, and
this whole thing is a hack job? If you can suggest any improvements, please do
so, no matter how much critisism you include I'll appreciate it :)
[[xkcd:1513]]
2020-04-29 10:32:57 +00:00
*** Extra Requirements
The lovely ~doom doctor~ is good at diagnosing most missing things, but here are a
few extras.
2020-04-29 10:33:15 +00:00
+ The [[https://github.com/dandavison/delta/][Delta]] binary. It's packaged for some distributions but I installed it with
#+BEGIN_SRC shell :exec no
cargo install git-delta
#+END_SRC
2020-04-29 10:32:57 +00:00
+ A [[https://www.tug.org/texlive/][LaTeX Compiler]] is required for the mathematics rendering performed in [[#org][Org]],
and by [[*CalcTeX][CalcTeX]].
+ I use the [[https://overpassfont.org/][Overpass]] font as a go-to sans serif.
It's used as my ~doom-variable-pitch-font~ and in the graph generated by [[*Roam][Roam]].
I have chosen it because it possesses a few characteristics I consider
desirable, namely:
- A clean, and legible style. Highway-style fonts tend to be designed to be
clear at a glance, and work well with a thicker weight, and this is inspired
by /Highway Gothic/.
- It's slightly quirky. Look at the diagonal cut on stems for example.
Helvetica is a masterful design, but I like a bit more pizazz now and then.
+ A few LSP servers. Take a look at [[file:init.el][init.el]] to see which modules have the ~+lsp~ flag.
+ The =cargo-script= rust crate is required for evaluation of rust blocks by babel.
As described in the README for [[https://github.com/micanzhang/ob-rust][ob-rust]]. Like ~delta~, this can just be installed
using cargo.
#+BEGIN_SRC shell
cargo install cargo-script
#+END_SRC
2020-05-09 19:00:48 +00:00
** Current Issues
*** Magit push in daemon
Quite often trying to push to a remote in the emacs daemon produces as error like this:
#+BEGIN_SRC fundamental
128 git … push -v origin refs/heads/master\:refs/heads/master
Pushing to git@github.com:tecosaur/emacs-config.git
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
#+END_SRC
*** CalcTeX brings up compilation buffer
With my [[*Calc][Calc]] hook, the first call of =M-x calc= brings up a compilation buffer
from CalcTeX. I'm guessing this is from the compilation of the preamble / ~.fmt~ file.
2020-05-15 10:07:10 +00:00
** Editor comparison
[[xkcd:378]]
2020-05-15 10:07:10 +00:00
Over the years I have tried out (spent at least a year using as my primary
editor) the following applications
- Python IDLE
- Komodo Edit
- Brackets
- VSCode
- and now, Emacs
I have attempted to quantify aspects of my impressions of them below.
2020-05-15 10:07:10 +00:00
#+PLOT: transpose:yes type:radar min:0 max:4 ticks:4 file:"misc/editor-comparison.png"
| Editor | Extensibility | Ecosystem | Ease of Use | Comfort | Completion | Performance |
|-------------+---------------+-----------+-------------+---------+------------+-------------|
| IDLE | 1 | 1 | 3 | 1 | 1 | 2 |
| Komodo Edit | 2 | 1 | 3 | 2 | 2 | 2 |
| Brackets | 2.5 | 2 | 3 | 3 | 2.5 | 2 |
| VSCode | 3 | 3 | 4 | 3.5 | 4 | 3 |
| Emacs | 4 | 4 | 2 | 4 | 3.5 | 3 |
[[https://media.githubusercontent.com/media/tecosaur/emacs-config/master/misc/editor-comparison.png]]
* Rudimentary configuration
2020-02-03 05:28:15 +00:00
Make this file run (slightly) faster with lexical binding (see [[https://nullprogram.com/blog/2016/12/22/][this blog post]]
for more info).
2020-04-29 10:33:15 +00:00
#+BEGIN_SRC emacs-lisp :comments no
2020-02-03 05:28:15 +00:00
;;; config.el -*- lexical-binding: t; -*-
#+END_SRC
** Personal Information
It's useful to have some basic personal information
#+BEGIN_SRC emacs-lisp
(setq user-full-name "tecosaur"
user-mail-address "tecosaur@gmail.com")
#+END_SRC
Apparently this is used by ~GPG~, and all sorts of other things.
** Better defaults
*** Simple settings
Browsing the web and seeing [[https://github.com/angrybacon/dotemacs/blob/master/dotemacs.org#use-better-defaults][angrybacon/dotemacs]] and comparing with the values
shown by =SPC h v= and selecting what I thought looks good, I've ended up adding the following:
#+BEGIN_SRC emacs-lisp
(setq-default
delete-by-moving-to-trash t ; Delete files to trash
tab-width 4 ; Set width for tabs
uniquify-buffer-name-style 'forward ; Uniquify buffer names
window-combination-resize t ; take new window space from all other windows (not just current)
x-stretch-cursor t) ; Stretch cursor to the glyph width
2020-02-02 18:21:19 +00:00
(setq undo-limit 80000000 ; Raise undo-limit to 80Mb
2020-03-04 15:27:08 +00:00
evil-want-fine-undo t ; By default while in insert all changes are one big blob. Be more granular
auto-save-default t ; Nobody likes to loose work, I certainly don't
inhibit-compacting-font-caches t) ; When there are lots of glyphs, keep them in memory
(delete-selection-mode 1) ; Replace selection when inserting text
(display-time-mode 1) ; Enable time in the mode-line
2020-01-09 18:04:48 +00:00
(display-battery-mode 1) ; On laptops it's nice to know how much power you have
(global-subword-mode 1) ; Iterate through CamelCase words
#+END_SRC
*** Fullscreen
I also like the idea of fullscreen-ing when opened by ~emacs~ or the ~.desktop~ file.
#+BEGIN_SRC emacs-lisp
(if (eq initial-window-system 'x) ; if started by emacs command or desktop file
(toggle-frame-maximized)
(toggle-frame-fullscreen))
#+END_SRC
*** Auto-customisations
By default changes made via a customisation interface are added to =init.el=.
I prefer the idea of using a separate file for this. We just need to change a
setting, and load it if it exists.
#+BEGIN_SRC emacs-lisp
2020-02-26 12:50:01 +00:00
(setq-default custom-file (expand-file-name ".custom.el" doom-private-dir))
(when (file-exists-p custom-file)
(load custom-file))
#+END_SRC
*** Windows
I find it rather handy to be asked which buffer I want to see after splitting
the window. Let's make that happen.
First, we'll enter the new window
#+BEGIN_SRC emacs-lisp
(setq evil-vsplit-window-right t
evil-split-window-below t)
#+END_SRC
Then, we'll pull up ~ivy~
#+BEGIN_SRC emacs-lisp
(defadvice! prompt-for-buffer (&rest _)
:after '(evil-window-split evil-window-vsplit)
2020-02-09 15:16:25 +00:00
(+ivy/switch-buffer))
#+END_SRC
2020-04-14 09:12:09 +00:00
Oh, and previews are nice
#+BEGIN_SRC emacs-lisp
(setq +ivy-buffer-preview t)
#+END_SRC
2020-01-29 12:46:48 +00:00
*** Buffer defaults
I'd much rather have my new buffers in ~org-mode~ than ~fundamental-mode~, hence
#+BEGIN_SRC emacs-lisp
;; (setq-default major-mode 'org-mode)
2020-01-29 12:46:48 +00:00
#+END_SRC
For some reason this + the mixed pitch hook causes issues with hydra and so I'll
just need to resort to =SPC b o= for now.
** Doom configuration
*** Visual Settings
**** Font Face
'Fira Code' is nice, and 'Overpass' makes for a nice sans companion. We just need to
fiddle with the font sizes a tad so that they visually match.
#+BEGIN_SRC emacs-lisp
2020-05-16 07:43:40 +00:00
(setq doom-font (font-spec :family "JetBrains Mono" :size 24)
doom-big-font (font-spec :family "JetBrains Mono" :size 36)
2020-05-16 09:34:29 +00:00
doom-variable-pitch-font (font-spec :family "Overpass" :size 24)
doom-serif-font (font-spec :family "IBM Plex Mono" :weight 'light))
#+END_SRC
**** Theme
~doom-one~ is nice and all, but I find the ~vibrant~ variant nicer.
#+BEGIN_SRC emacs-lisp
(setq doom-theme 'doom-vibrant)
#+END_SRC
However, by default ~red~ text is used in the ~modeline~, so let's make that orange
so I don't feel like something's gone /wrong/ when editing files.
#+BEGIN_SRC emacs-lisp
(custom-set-faces!
'(doom-modeline-buffer-modified :foreground "orange"))
#+END_SRC
**** Miscellaneous
Relative line numbers are fantastic for knowing how far away line numbers are,
then =ESC 12 <UP>= gets you exactly where you think.
#+BEGIN_SRC emacs-lisp
(setq display-line-numbers-type 'relative)
#+END_SRC
2020-02-06 17:11:35 +00:00
I'd like some slightly nicer default buffer names
#+BEGIN_SRC emacs-lisp
(setq doom-fallback-buffer-name "► Doom"
+doom-dashboard-name "► Doom")
#+END_SRC
There's a bug with the modeline in insert mode for org documents ([[https://github.com/seagle0128/doom-modeline/issues/300][issue]]), so
2020-02-09 00:12:19 +00:00
#+BEGIN_SRC emacs-lisp
(custom-set-faces! '(doom-modeline-evil-insert-state :weight bold :foreground "#339CDB"))
2020-02-09 00:12:19 +00:00
#+END_SRC
*** Some helper macros
There are a few handy macros added by doom, namely
- ~load!~ for loading external ~.el~ files relative to this one
- ~use-package~ for configuring packages
- ~add-load-path!~ for adding directories to the ~load-path~ where ~emacs~ looks when
you load packages with ~require~ or ~use-package~
- ~map~ for binding new keys
To find more,
** Other things
*** Editor interaction
**** Mouse buttons
#+BEGIN_SRC emacs-lisp
(map! :n [mouse-8] #'better-jumper-jump-backward
:n [mouse-9] #'better-jumper-jump-forward)
#+END_SRC
2020-02-06 15:31:44 +00:00
*** Window title
I'd like to have just the buffer name, then if applicable the project folder
#+BEGIN_SRC emacs-lisp
(setq frame-title-format
'(""
2020-04-28 18:41:46 +00:00
(:eval
(if (s-contains-p org-roam-directory (or buffer-file-name ""))
(replace-regexp-in-string ".*/[0-9]+-" "🢔 " buffer-file-name)
2020-04-28 18:41:46 +00:00
"%b"))
2020-02-06 15:31:44 +00:00
(:eval
(let ((project-name (projectile-project-name)))
(unless (string= "-" project-name)
2020-02-16 05:23:19 +00:00
(format (if (buffer-modified-p) " ◉ %s" "  ●  %s") project-name))))))
2020-02-06 15:31:44 +00:00
#+END_SRC
2020-03-27 04:20:42 +00:00
*** Splash screen
Emacs can render an image as the splash screen, and [[https://github.com/MarioRicalde][@MarioRicalde]] came up with a
cracker! He's also provided me with a nice emacs-style /E/, which is good for
smaller windows. *@MarioRicalde* you have my sincere thanks, you're great!
[[file:misc/splash-images/blackhole-lines.svg]]
By incrementally stripping away the outer layers of the logo one can obtain
quite a nice resizing effect.
2020-03-27 04:20:42 +00:00
#+BEGIN_SRC emacs-lisp
(defvar fancy-splash-image-template
(expand-file-name "misc/splash-images/blackhole-lines-template.svg" doom-private-dir)
"Default template svg used for the splash image, with substitutions from ")
(defvar fancy-splash-image-nil
(expand-file-name "misc/splash-images/transparent-pixel.png" doom-private-dir)
"An image to use at minimum size, usually a transparent pixel")
(setq fancy-splash-sizes
`((:height 500 :min-height 50 :padding (0 . 4) :template ,(expand-file-name "misc/splash-images/blackhole-lines-0.svg" doom-private-dir))
(:height 440 :min-height 42 :padding (1 . 4) :template ,(expand-file-name "misc/splash-images/blackhole-lines-0.svg" doom-private-dir))
(:height 400 :min-height 38 :padding (1 . 4) :template ,(expand-file-name "misc/splash-images/blackhole-lines-1.svg" doom-private-dir))
(:height 350 :min-height 36 :padding (1 . 3) :template ,(expand-file-name "misc/splash-images/blackhole-lines-2.svg" doom-private-dir))
(:height 300 :min-height 34 :padding (1 . 3) :template ,(expand-file-name "misc/splash-images/blackhole-lines-3.svg" doom-private-dir))
(:height 250 :min-height 32 :padding (1 . 2) :template ,(expand-file-name "misc/splash-images/blackhole-lines-4.svg" doom-private-dir))
(:height 200 :min-height 30 :padding (1 . 2) :template ,(expand-file-name "misc/splash-images/blackhole-lines-5.svg" doom-private-dir))
(:height 100 :min-height 24 :padding (1 . 2) :template ,(expand-file-name "misc/splash-images/emacs-e-template.svg" doom-private-dir))
(:height 0 :min-height 0 :padding (0 . 0) :file ,fancy-splash-image-nil)))
(defvar fancy-splash-sizes
`((:height 500 :min-height 50 :padding (0 . 2))
(:height 440 :min-height 42 :padding (1 . 4))
(:height 330 :min-height 35 :padding (1 . 3))
(:height 200 :min-height 30 :padding (1 . 2))
(:height 0 :min-height 0 :padding (0 . 0) :file ,fancy-splash-image-nil))
"list of plists with the following properties
:height the height of the image
:min-height minimum `frame-height' for image
:padding `+doom-dashboard-banner-padding' to apply
:template non-default template file
:file file to use instead of template")
(defvar fancy-splash-template-colours
'(("$colour1" . keywords) ("$colour2" . type) ("$colour3" . base5) ("$colour4" . base8))
"list of colour-replacement alists of the form (\"$placeholder\" . 'theme-colour) which applied the template")
(unless (file-exists-p (expand-file-name "theme-splashes" doom-cache-dir))
(make-directory (expand-file-name "theme-splashes" doom-cache-dir) t))
(defun fancy-splash-filename (theme-name height)
(expand-file-name (concat (file-name-as-directory "theme-splashes")
(symbol-name doom-theme)
"-" (number-to-string height) ".svg")
doom-cache-dir))
(defun fancy-splash-clear-cache ()
"Delete all cached fancy splash images"
(interactive)
(delete-directory (expand-file-name "theme-splashes" doom-cache-dir) t)
(message "Cache cleared!"))
(defun fancy-splash-generate-image (template height)
"Read TEMPLATE and create an image if HEIGHT with colour substitutions as ;described by `fancy-splash-template-colours' for the current theme"
(with-temp-buffer
(insert-file-contents template)
(re-search-forward "$height" nil t)
(replace-match (number-to-string height) nil nil)
(dolist (substitution fancy-splash-template-colours)
(beginning-of-buffer)
(while (re-search-forward (car substitution) nil t)
(replace-match (doom-color (cdr substitution)) nil nil)))
2020-03-28 04:18:03 +00:00
(write-region nil nil
(fancy-splash-filename (symbol-name doom-theme) height) nil nil)))
(defun fancy-splash-generate-images ()
"Perform `fancy-splash-generate-image' in bulk"
(dolist (size fancy-splash-sizes)
(unless (plist-get size :file)
(fancy-splash-generate-image (or (plist-get size :file)
(plist-get size :template)
fancy-splash-image-template)
(plist-get size :height)))))
(defun ensure-theme-splash-images-exist (&optional height)
(unless (file-exists-p (fancy-splash-filename
(symbol-name doom-theme)
(or height
(plist-get (car fancy-splash-sizes) :height))))
(fancy-splash-generate-images)))
(defun get-appropriate-splash ()
(let ((height (frame-height)))
(cl-some (lambda (size) (when (>= height (plist-get size :min-height)) size))
fancy-splash-sizes)))
(setq fancy-splash-last-size nil)
(setq fancy-splash-last-theme nil)
2020-03-27 04:20:42 +00:00
(defun set-appropriate-splash (&optional frame)
(let ((appropriate-image (get-appropriate-splash)))
(unless (and (equal appropriate-image fancy-splash-last-size)
(equal doom-theme fancy-splash-last-theme)))
(unless (plist-get appropriate-image :file)
(ensure-theme-splash-images-exist (plist-get appropriate-image :height)))
(setq fancy-splash-image
(or (plist-get appropriate-image :file)
(fancy-splash-filename (symbol-name doom-theme) (plist-get appropriate-image :height))))
(setq +doom-dashboard-banner-padding (plist-get appropriate-image :padding))
(setq fancy-splash-last-size appropriate-image)
(setq fancy-splash-last-theme doom-theme)
(+doom-dashboard-reload)))
2020-03-27 04:20:42 +00:00
(add-hook 'window-size-change-functions #'set-appropriate-splash)
(add-hook 'doom-load-theme-hook #'set-appropriate-splash)
2020-03-27 04:20:42 +00:00
#+END_SRC
2020-02-16 05:12:36 +00:00
*** Systemd daemon
For running a systemd service for a Emacs server I have the following
2020-02-16 05:12:36 +00:00
#+BEGIN_SRC systemd :tangle ~/.config/systemd/user/emacs.service
[Unit]
Description=Emacs server daemon
Documentation=info:emacs man:emacs(1) https://gnu.org/software/emacs/
[Service]
Type=forking
ExecStart=/usr/bin/emacs --daemon
ExecStop=/usr/bin/emacsclient --eval "(progn (setq kill-emacs-hook nil) (kill emacs))"
Environment=SSH_AUTH_SOCK=%t/keyring/ssh
Restart=on-failure
[Install]
WantedBy=default.target
#+END_SRC
which is then enabled by
2020-04-29 10:33:15 +00:00
#+BEGIN_SRC shell :tangle no
2020-02-16 05:12:36 +00:00
systemctl --user enable emacs.service
#+END_SRC
* Package loading
:PROPERTIES:
2020-04-10 04:31:36 +00:00
:header-args:emacs-lisp: :tangle "packages.el" :comments link
:END:
This file shouldn't be byte compiled.
2020-04-29 13:20:54 +00:00
#+BEGIN_SRC emacs-lisp :tangle "packages.el" :comments no
;; -*- no-byte-compile: t; -*-
#+END_SRC
** Loading instructions
:PROPERTIES:
2020-03-23 02:59:27 +00:00
:header-args:emacs-lisp: :tangle no
:END:
This is where you install packages, by declaring them with the ~package!~
macro, then running ~doom refresh~ on the command line. You'll need to
restart Emacs for your changes to take effect! Or at least, run =M-x doom/reload=.
WARNING: Don't disable core packages listed in ~~/.emacs.d/core/packages.el~.
Doom requires these, and disabling them may have terrible side effects.
*** Packages in MELPA/ELPA/emacsmirror
To install ~some-package~ from MELPA, ELPA or emacsmirror:
#+BEGIN_SRC emacs-lisp
(package! some-package)
#+END_SRC
*** Packages from git repositories
To install a package directly from a particular repo, you'll need to specify
a ~:recipe~. You'll find documentation on what ~:recipe~ accepts [[https://github.com/raxod502/straight.el#the-recipe-format][here]]:
#+BEGIN_SRC emacs-lisp
(package! another-package
:recipe (:host github :repo "username/repo"))
#+END_SRC
If the package you are trying to install does not contain a ~PACKAGENAME.el~
file, or is located in a subdirectory of the repo, you'll need to specify
~:files~ in the ~:recipe~:
#+BEGIN_SRC emacs-lisp
(package! this-package
:recipe (:host github :repo "username/repo"
:files ("some-file.el" "src/lisp/*.el")))
#+END_SRC
2020-01-09 18:00:50 +00:00
*** Disabling built-in packages
If you'd like to disable a package included with Doom, for whatever reason,
you can do so here with the ~:disable~ property:
#+BEGIN_SRC emacs-lisp
(package! builtin-package :disable t)
#+END_SRC
You can override the recipe of a built in package without having to specify
all the properties for ~:recipe~. These will inherit the rest of its recipe
from Doom or MELPA/ELPA/Emacsmirror:
#+BEGIN_SRC emacs-lisp
(package! builtin-package :recipe (:nonrecursive t))
(package! builtin-package-2 :recipe (:repo "myfork/package"))
#+END_SRC
Specify a ~:branch~ to install a package from a particular branch or tag.
This is required for some packages whose default branch isn't 'master' (which
our package manager can't deal with; see [[https://github.com/raxod502/straight.el/issues/279][raxod502/straight.el#279]])
#+BEGIN_SRC emacs-lisp
(package! builtin-package :recipe (:branch "develop"))
#+END_SRC
*** Updating all pins in file
2020-04-10 04:31:36 +00:00
#+BEGIN_SRC emacs-lisp :tangle yes
(defun +doom/update-all-pinned-package-form ()
"Call `doom/update-pinned-package-form' on every package! statement in the buffer"
(interactive)
2020-04-29 14:18:39 +00:00
(beginning-of-buffer)
2020-04-14 06:26:51 +00:00
(let ((progress 0) (package "") (total (how-many "package!")) (updated '()))
(while (search-forward "package!" nil t)
(setq progress (1+ progress))
(forward-char) ;; move cursor to package name "package! |name"
2020-04-14 06:26:51 +00:00
(setq package (current-word))
(message (format "Re-pinning package: %s/%s (%s)" progress total package))
(backward-char)
(evil-scroll-line-to-center (line-number-at-pos))
(redisplay)
(if (s-contains-p "Updated" (condition-case nil
(doom/update-pinned-package-form)
(user-error "")))
2020-04-14 06:26:51 +00:00
(add-to-list 'updated package))
(search-forward "package!" nil t)) ;; because of cursor-moving done
2020-04-20 08:00:48 +00:00
(message (format "%s packages updated (%s)" (length updated) (s-join ", " updated)))
updated))
#+END_SRC
2020-02-16 06:13:35 +00:00
** General packages
*** Prettification
~prettify-mode~ is nice and all, but adding substitutions is a little verbose.
This helps with that.
#+BEGIN_SRC emacs-lisp
(package! prettify-utils ; simplify messing with prettify-mode
2020-04-09 17:16:13 +00:00
:recipe (:host github :repo "Ilazki/prettify-utils.el") :pin "8b783d316c")
#+END_SRC
2020-01-20 18:08:53 +00:00
*** Window management
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! rotate :pin "091b5ac4fc")
2020-01-20 18:08:53 +00:00
#+END_SRC
*** Fun
Sometimes one just wants a little fun.
XKCD comics are fun.
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! xkcd :pin "66e928706f")
2020-01-20 18:08:53 +00:00
#+END_SRC
Every so often, you want everyone else to /know/ that you're typing, or just to
amuse oneself. Introducing: typewriter sounds!
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! selectric-mode :pin "bb9e66678f")
2020-01-20 18:08:53 +00:00
#+END_SRC
Hey, let's get the weather in here while we're at it.
2020-05-17 03:06:32 +00:00
Unfortunately this seems slightly unmaintained ([[https://github.com/bcbcarl/emacs-wttrin/pulls][few open bugfix PRs]]) so let's
roll our [[file:wttrin.el][own version]].
2020-01-20 18:08:53 +00:00
#+BEGIN_SRC emacs-lisp
2020-05-17 03:06:32 +00:00
(package! wttrin :recipe (:local-repo "lisp" :no-byte-compile t))
2020-01-20 18:08:53 +00:00
#+END_SRC
Why not flash words on the screen. Why not --- hey, it could be fun.
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! spray :pin "00638bc916")
2020-01-20 18:08:53 +00:00
#+END_SRC
With all our fancy Emacs themes, my terminal is missing out!
2020-01-20 18:08:53 +00:00
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! theme-magic :pin "844c4311bd")
2020-01-20 18:08:53 +00:00
#+END_SRC
2020-04-09 17:15:17 +00:00
What's even the point of using Emacs unless you're constantly telling everyone
about it?
#+BEGIN_SRC emacs-lisp
(package! elcord :pin "94b0afb9ba")
#+END_SRC
2020-04-29 10:33:15 +00:00
*** Improving features
2020-01-20 18:08:53 +00:00
**** Flyspell-lazy
2020-01-09 18:01:52 +00:00
To alleviate some [[Flyspell][issues with flyspell]]
#+BEGIN_SRC emacs-lisp
2020-05-15 03:13:18 +00:00
(package! flyspell-lazy :pin "3ebf68cc9e")
2020-01-09 18:01:52 +00:00
#+END_SRC
2020-02-03 04:57:08 +00:00
**** CalcTeX
This is a nice extension to ~calc~
#+BEGIN_SRC emacs-lisp
(package! calctex :recipe (:host github :repo "johnbcoughlin/calctex"
2020-04-09 17:16:13 +00:00
:files ("*.el")) :pin "542b628eb4")
2020-02-03 04:57:08 +00:00
#+END_SRC
2020-02-16 06:13:35 +00:00
**** ESS
View data frames better with
2020-02-16 06:13:35 +00:00
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! ess-view :pin "d4e5a340b7")
2020-02-16 06:13:35 +00:00
#+END_SRC
2020-04-29 10:33:15 +00:00
**** Magit Delta
[[https://github.com/dandavison/delta/][Delta]] is a git diff syntax highlighter written in rust. The author also wrote a
package to hook this into the magit diff view. This requires the ~delta~ binary.
#+BEGIN_SRC emacs-lisp
2020-05-15 03:13:18 +00:00
;; (package! magit-delta :recipe (:host github :repo "dandavison/magit-delta") :pin "0c7d8b2359")
2020-04-29 10:33:15 +00:00
#+END_SRC
2020-05-16 09:34:29 +00:00
**** Info colours
This makes manual pages nicer to look at :)
Variable pitch fontification + colouring
#+BEGIN_SRC emacs-lisp
(package! info-colors :pin "47ee73cc19")
#+END_SRC
2020-02-16 06:13:35 +00:00
** Language packages
2020-05-18 16:01:23 +00:00
*** LaTeX
2020-02-03 04:57:08 +00:00
#+BEGIN_SRC emacs-lisp
2020-05-18 16:01:23 +00:00
(package! evil-tex :recipe (:host github :repo "itai33/evil-tex")
:pin "14da2c4c1d")
2020-02-03 04:57:08 +00:00
#+END_SRC
2020-02-16 06:13:35 +00:00
*** Org Mode
**** Improve agenda/capture
The agenda is nice, but a souped up version is nicer.
#+BEGIN_SRC emacs-lisp
(package! org-super-agenda :pin "dd0d104c26")
#+END_SRC
Similarly ~doct~ (Declarative Org Capture Templates) seems to be a nicer way to
set up org-capture.
#+BEGIN_SRC emacs-lisp
(package! doct
:recipe (:host github :repo "progfolio/doct")
2020-05-15 03:13:18 +00:00
:pin "1bcec209e1")
#+END_SRC
2020-04-12 05:49:54 +00:00
**** Visuals
2020-02-16 06:13:35 +00:00
Org tables aren't the prettiest thing to look at. This package is supposed to
redraw them in the buffer with box-drawing characters. Sounds like an
improvement to me! Just need to get it working...
2020-02-03 04:57:08 +00:00
#+BEGIN_SRC emacs-lisp
2020-02-16 06:13:35 +00:00
(package! org-pretty-table-mode
2020-04-09 17:16:13 +00:00
:recipe (:host github :repo "Fuco1/org-pretty-table") :pin "88380f865a")
2020-02-16 06:13:35 +00:00
#+END_SRC
2020-04-12 05:49:54 +00:00
For automatically toggling LaTeX fragment previews there's this nice package
#+BEGIN_SRC emacs-lisp
(package! org-fragtog :pin "8eca8084cc")
#+END_SRC
2020-05-01 12:52:00 +00:00
~org-superstar-mode~ is great. While we're at it we may as well make tags prettier as well :)
2020-04-12 05:49:54 +00:00
#+BEGIN_SRC emacs-lisp
(package! org-pretty-tags :pin "40fd72f3e7")
#+END_SRC
**** Extra functionality
2020-02-16 06:13:35 +00:00
Because of the /[[https://github.com/commonmark/commonmark-spec/wiki/markdown-flavors][lovely variety in markdown implementations]]/ there isn't actually
such a thing a standard table spec ... or standard anything really. Because
~org-md~ is a goody-two-shoes, it just uses HTML for all these non-standardised
elements (a lot of them). So ~ox-gfm~ is handy for exporting markdown with all the
features that GitHub has. Initialised in [[Exporting to GFM]].
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! ox-gfm :pin "99f93011b0")
2020-02-16 06:13:35 +00:00
#+END_SRC
2020-02-26 11:05:41 +00:00
Now and then citations need to happen
#+BEGIN_SRC emacs-lisp
2020-05-15 03:13:18 +00:00
(package! org-ref :pin "4ce8064437")
2020-02-26 11:05:41 +00:00
#+END_SRC
2020-02-16 06:13:35 +00:00
Came across this and ... it's cool
#+BEGIN_SRC emacs-lisp
2020-04-09 17:16:13 +00:00
(package! org-graph-view :recipe (:host github :repo "alphapapa/org-graph-view") :pin "13314338d7")
2020-02-03 04:57:08 +00:00
#+END_SRC
I *need* this in my life. It take a URL to a recipe from a common site, and
inserts an org-ified version at point. Isn't that just great.
#+BEGIN_SRC emacs-lisp
2020-05-15 03:13:18 +00:00
(package! org-chef :pin "1dd73fd3db")
#+END_SRC
2020-05-15 10:07:10 +00:00
2020-05-17 03:06:32 +00:00
I have my own [[file:org-plot.el][modified version]] of ~org-plot~, so let's use that
2020-05-15 10:07:10 +00:00
#+BEGIN_SRC emacs-lisp
(package! org-plot :recipe (:local-repo "lisp" :no-byte-compile t))
#+END_SRC
2020-05-18 16:01:23 +00:00
*** Systemd
For editing systemd unit files
#+BEGIN_SRC emacs-lisp
(package! systemd :pin "51c148e09a")
#+END_SRC
* Package configuration
** Abbrev mode
Thanks to [[https://emacs.stackexchange.com/questions/45462/use-a-single-abbrev-table-for-multiple-modes/45476#45476][use a single abbrev-table for multiple modes? - Emacs Stack Exchange]] I
have the following.
#+BEGIN_SRC emacs-lisp
(use-package abbrev
:init
(setq-default abbrev-mode t)
;; a hook funtion that sets the abbrev-table to org-mode-abbrev-table
;; whenever the major mode is a text mode
(defun tec/set-text-mode-abbrev-table ()
(if (derived-mode-p 'text-mode)
(setq local-abbrev-table org-mode-abbrev-table)))
:commands abbrev-mode
:hook
(abbrev-mode . tec/set-text-mode-abbrev-table)
:config
(setq abbrev-file-name (expand-file-name "abbrev.el" doom-private-dir))
(setq save-abbrevs 'silently))
#+END_SRC
2020-04-29 08:47:48 +00:00
** Calc
Radians are just better
#+BEGIN_SRC emacs-lisp
(setq calc-angle-mode 'rad ;; radians are rad
calc-algebraic-mode t ;; allows '2*x instead of 'x<RET>2*
calc-symbolic-mode t) ;; keeps stuff like √2 irrational for as long as possible
(after! calctex
(setq calctex-format-latex-header (concat calctex-format-latex-header
"\n\\usepackage{arevmath}")))
(add-hook 'calc-mode-hook #'calctex-mode)
#+END_SRC
** Centaur Tabs
We want to make the tabs a nice, comfy size (~36~), with icons. The modifier
marker is nice, but the particular default Unicode one causes a lag spike, so
let's just switch to an ~o~, which still looks decent but doesn't cause any
issues.
A 'active-bar' is nice, so let's have one of those. If we have it ~under~ needs us to
turn on ~x-underline-at-decent~ though. For some reason this didn't seem to work
inside the ~(after! ... )~ block ¯\_(ツ)_/¯.
Then let's change the font to a sans serif, but the default one doesn't fit too
well somehow, so let's switch to 'P22 Underground Book'; it looks much nicer.
#+BEGIN_SRC emacs-lisp
(after! centaur-tabs
2020-04-09 18:29:06 +00:00
(centaur-tabs-mode -1)
(setq centaur-tabs-height 36
centaur-tabs-set-icons t
centaur-tabs-modified-marker "o"
2020-01-09 18:02:20 +00:00
centaur-tabs-close-button "×"
centaur-tabs-set-bar 'above)
centaur-tabs-gray-out-icons 'buffer
(centaur-tabs-change-fonts "P22 Underground Book" 160))
;; (setq x-underline-at-descent-line t)
#+END_SRC
** Company
It's nice to have completions almost all the time, in my opinion. Key strokes
are just waiting to be saved!
#+BEGIN_SRC emacs-lisp
(after! company
(setq company-idle-delay 0.5
company-minimum-prefix-length 2)
2020-02-26 12:49:02 +00:00
(setq company-show-numbers t)
(add-hook 'evil-normal-state-entry-hook #'company-abort)) ;; make aborting less annoying.
#+END_SRC
Now, the improvements from ~precident~ are mostly from remembering history, so
let's improve that memory.
#+BEGIN_SRC emacs-lisp
(setq-default history-length 1000)
(setq-default prescient-history-length 1000)
#+END_SRC
*** Plain Text
~ispell~ is nice, let's have it in ~text~, ~markdown~, and ~GFM~.
#+BEGIN_SRC emacs-lisp
(set-company-backend! '(text-mode
markdown-mode
gfm-mode)
'(:seperate company-ispell
company-files
company-yasnippet))
#+END_SRC
2020-04-29 08:47:48 +00:00
We then configure the dictionary we're using in [[*Ispell][ispell]].
*** ESS
~company-dabbrev-code~ is nice. Let's have it.
#+BEGIN_SRC emacs-lisp
(set-company-backend! 'ess-r-mode '(company-R-args company-R-objects company-dabbrev-code :separate))
#+END_SRC
2020-04-29 08:47:48 +00:00
** Elcord
#+BEGIN_SRC emacs-lisp
(setq elcord-use-major-mode-as-main-icon t)
#+END_SRC
** [[https://github.com/zachcurry/emacs-anywhere][Emacs Anywhere]] configuration
2020-02-06 17:11:58 +00:00
# NB: install with curl -fsSL https://raw.github.com/zachcurry/emacs-anywhere/master/install | bash
It's nice to recognise GitHub (so we can use ~GFM~), and other apps which we know
take markdown
#+BEGIN_SRC emacs-lisp
(defun markdown-window-p (window-title)
"Judges from WINDOW-TITLE whether the current window likes markdown"
(string-match-p (rx (or "Stack Exchange" "Stack Overflow"
"Pull Request" "Issue" "Discord"))
window-title))
#+END_SRC
When the window opens, we generally want text so let's use a nice sans serif font,
a position the window below and to the left. Oh, and don't forget about checking
for ~GFM~, otherwise let's just use ~markdown~.
#+BEGIN_SRC emacs-lisp
(define-minor-mode emacs-anywhere-mode
"To tweak the current buffer for some emacs-anywhere considerations"
:init-value nil
:keymap (list
;; Finish edit, but be smart in org mode
(cons (kbd "C-c C-c") (lambda! (if (and (eq major-mode 'org-mode)
(org-in-src-block-p))
(org-ctrl-c-ctrl-c)
(delete-frame))))
;; Abort edit. emacs-anywhere saves the current edit for next time.
(cons (kbd "C-c C-k") (lambda! (setq ea-on nil)
(delete-frame))))
(when emacs-anywhere-mode
2020-03-24 04:45:07 +00:00
;; line breaking
(turn-off-auto-fill)
(visual-line-mode t)
;; DEL/C-SPC to clear (first keystroke only)
(set-transient-map (let ((keymap (make-sparse-keymap)))
(define-key keymap (kbd "DEL") (lambda! (delete-region (point-min) (point-max))))
(define-key keymap (kbd "C-SPC") (lambda! (delete-region (point-min) (point-max))))
keymap))
;; disable tabs
(when (bound-and-true-p centaur-tabs-mode)
(centaur-tabs-local-mode t))))
(defun ea-popup-handler (app-name window-title x y w h)
(interactive)
(set-frame-size (selected-frame) 80 12)
;; position the frame near the mouse
(let* ((mousepos (split-string (shell-command-to-string "xdotool getmouselocation | sed -E \"s/ screen:0 window:[^ ]*|x:|y://g\"")))
(mouse-x (- (string-to-number (nth 0 mousepos)) 100))
(mouse-y (- (string-to-number (nth 1 mousepos)) 50)))
(set-frame-position (selected-frame) mouse-x mouse-y))
(set-frame-name (concat "Quick Edit ∷ " ea-app-name " — "
(truncate-string-to-width
(string-trim
(string-trim-right window-title
(format "-[A-Za-z0-9 ]*%s" ea-app-name))
"[\s-]+" "[\s-]+")
45 nil nil "…")))
(message "window-title: %s" window-title)
;; set major mode
(cond
((markdown-window-p window-title) (gfm-mode))
(t (org-mode)) ; default major mode
)
(when-let ((selection (gui-get-selection 'PRIMARY)))
(insert selection)
;; I'll be honest with myself, I /need/ spellcheck
(flyspell-buffer))
(evil-insert-state) ; start in insert
(emacs-anywhere-mode 1))
(add-hook 'ea-popup-hook 'ea-popup-handler)
#+END_SRC
2020-04-29 08:47:48 +00:00
** Eros-eval
This makes the result of evals with =gr= and =gR= just slightly prettier. Every bit
counts right?
#+BEGIN_SRC emacs-lisp
(setq eros-eval-result-prefix "⟹ ")
#+END_SRC
** EVIL
I don't use ~evil-escape-mode~, so I may as well turn it off, I've heard it
contributes a typing delay. I'm not sure it's much, but it is an extra
~pre-command-hook~ that I don't benefit from, so...
#+BEGIN_SRC emacs-lisp
(after! evil (evil-escape-mode nil))
#+END_SRC
** Flyspell
At one point, typing became noticeably laggy, Profiling revealed
~flyspell-post-command-hook~ was responsible for 47% of CPU cycles by itself!
So I'm going to make use of ~flyspell-lazy~
#+BEGIN_SRC emacs-lisp
(after! flyspell (require 'flyspell-lazy) (flyspell-lazy-mode 1))
#+END_SRC
2020-05-16 09:34:29 +00:00
** Info colors
#+BEGIN_SRC emacs-lisp
(use-package! info-colors
:commands (info-colors-fontify-node))
(add-hook 'Info-selection-hook 'info-colors-fontify-node)
(add-hook 'Info-mode-hook #'mixed-pitch-mode)
#+END_SRC
2020-04-29 08:47:48 +00:00
** Ispell
Let's get a nice big dictionary from [[http://app.aspell.net/create][SCOWL Custom List/Dictionary Creator]] with
the following configuration
- size :: 80 (huge)
- spellings :: British(-ise) and Australian
- spelling variants level :: 0
- diacritics :: keep
- extra lists :: hacker, roman numerals
#+BEGIN_SRC emacs-lisp
(setq ispell-dictionary "en_GBs_au_SCOWL_80_0_k_hr")
#+END_SRC
Oh, and by the way, if ~company-ispell-dictionary~ is ~nil~, then
~ispell-complete-word-dict~ is used instead, which once again when ~nil~ is
~ispell-alternate-dictionary~, which at the moment maps to a plaintext version of
the above.
It seems reasonable to want to keep an eye on my personal dict, let's have it
nearby (also means that if I change the 'main' dictionary I keep my addition).
#+BEGIN_SRC emacs-lisp
(setq ispell-personal-dictionary (expand-file-name ".hunspell_personal" doom-private-dir))
#+END_SRC
2020-04-29 10:33:15 +00:00
** Magit
Magit is pretty nice by default. The diffs don't get any
syntax-highlighting-love though which is a bit sad. Thankfully
[[https://github.com/dandavison/magit-delta][dandavison/magit-delta]] exists, which we can put to use.
#+BEGIN_SRC emacs-lisp
;; (after! magit
;; (magit-delta-mode +1))
#+END_SRC
Unfortunately this seems to mess things up, which is something I'll want to look
into later.
** Org Chef
Loading after org seems a bit premature. Let's just load it when we try to use
it, either by command or in a capture template.
#+BEGIN_SRC emacs-lisp
(use-package! org-chef
:commands (org-chef-insert-recipe org-chef-get-recipe-from-url))
#+END_SRC
2020-04-29 08:47:48 +00:00
** Projectile
Looking at documentation via =SPC h f= and =SPC h v= and looking at the source can
add package src directories to projectile. This isn't desirable in my opinion.
#+BEGIN_SRC emacs-lisp
(setq projectile-ignored-projects '("~/" "/tmp" "~/.emacs.d/.local/straight/repos/"))
(defun projectile-ignored-project-function (filepath)
"Return t if FILEPATH is within any of `projectile-ignored-projects'"
(or (mapcar (lambda (p) (s-starts-with-p p filepath)) projectile-ignored-projects)))
#+END_SRC
** Smart Parentheses
#+BEGIN_SRC emacs-lisp
(sp-local-pair
'(org-mode)
"<<" ">>"
:actions '(insert))
#+END_SRC
** Spray
Let's make this suit me slightly better.
#+BEGIN_SRC emacs-lisp
(setq spray-wpm 500
spray-height 700)
#+END_SRC
** Theme magic
Let's automatically update terminals on theme change
#+BEGIN_SRC emacs-lisp
(add-hook 'doom-load-theme-hook 'theme-magic-from-emacs)
#+END_SRC
** Tramp
Let's try to make tramp handle prompts better
#+BEGIN_SRC emacs-lisp
(after! tramp
(setenv "SHELL" "/bin/bash")
(setq tramp-shell-prompt-pattern "\\(?:^\\| \\)[^]#$%>\n]*#?[]#$%>] *\\(\\[[0-9;]*[a-zA-Z] *\\)*")) ;; defult + 
#+END_SRC
**** Troubleshooting
In case the remote shell is misbehaving, here are some things to try
***** Zsh
There are some escape code you don't want, let's make it behave more considerately.
#+BEGIN_SRC shell :eval no :tangle no
if [[ "$TERM" == "dumb" ]]; then
unset zle_bracketed_paste
unset zle
PS1='$ '
return
fi
#+END_SRC
2020-03-17 17:12:17 +00:00
** Treemacs
Quite often there are superfluous files I'm not that interested in. There's no
2020-03-23 03:00:23 +00:00
good reason for them to take up space. Let's add a mechanism to ignore them.
#+BEGIN_SRC emacs-lisp
(after! treemacs
(defvar treemacs-file-ignore-extensions '()
"File extension which `treemacs-ignore-filter' will ensure are ignored")
(defvar treemacs-file-ignore-globs '()
"Globs which will are transformed to `treemacs-file-ignore-regexps' which `treemacs-ignore-filter' will ensure are ignored")
(defvar treemacs-file-ignore-regexps '()
"RegExps to be tested to ignore files, generated from `treeemacs-file-ignore-globs'")
(defun treemacs-file-ignore-generate-regexps ()
"Generate `treemacs-file-ignore-regexps' from `treemacs-file-ignore-globs'"
(setq treemacs-file-ignore-regexps (mapcar 'dired-glob-regexp treemacs-file-ignore-globs)))
(if (equal treemacs-file-ignore-globs '()) nil (treemacs-file-ignore-generate-regexps))
(defun treemacs-ignore-filter (file full-path)
"Ignore files specified by `treemacs-file-ignore-extensions', and `treemacs-file-ignore-regexps'"
(or (member (file-name-extension file) treemacs-file-ignore-extensions)
(let ((ignore-file nil))
(dolist (regexp treemacs-file-ignore-regexps ignore-file)
(setq ignore-file (or ignore-file (if (string-match-p regexp full-path) t nil)))))))
(add-to-list 'treemacs-ignored-file-predicates #'treemacs-ignore-filter))
#+END_SRC
Now, we just identify the files in question.
2020-03-17 17:12:17 +00:00
#+BEGIN_SRC emacs-lisp
2020-03-18 16:48:47 +00:00
(setq treemacs-file-ignore-extensions '(;; LaTeX
"aux"
"ptc"
"fdb_latexmk"
"fls"
"synctex.gz"
"toc"
;; LaTeX - glossary
"glg"
"glo"
"gls"
"glsdefs"
"ist"
"acn"
"acr"
"alg"
;; LaTeX - pgfplots
"mw"
;; LaTeX - pdfx
"pdfa.xmpi"
))
(setq treemacs-file-ignore-globs '(;; LaTeX
"*/_minted-*"
;; AucTeX
"*/.auctex-auto"
"*/_region_.log"
2020-03-23 03:00:23 +00:00
"*/_region_.tex"))
#+END_SRC
2020-04-29 08:47:48 +00:00
** VTerm
On my system, I want to use the ~vterm~ lib in =/usr/bin/libvterm.so=. This is not
default behaviour. Without this I see the following error message.
#+BEGIN_SRC
make[2]: *** No rule to make target 'libvterm-prefix/src/libvterm/.libs/libvterm.a', needed by '../vterm-module.so'. Stop.
make[1]: *** [CMakeFiles/Makefile2:106: CMakeFiles/vterm-module.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
2020-04-09 17:15:17 +00:00
#+END_SRC
2020-04-29 08:47:48 +00:00
I asked about this in a [[https://github.com/akermu/emacs-libvterm/issues/238#issuecomment-586385773][GitHub Issue]], and the fix is to use the ~cmake~ flag
~-DUSE_SYSTEM_LIBVTERM=yes~. This can be set for when Doom recompiles ~vterm~ on
2020-04-29 08:47:48 +00:00
updating, which saves me manually compiling with the flag.
2020-04-13 19:20:37 +00:00
#+BEGIN_SRC emacs-lisp
2020-04-29 08:47:48 +00:00
(setq vterm-module-cmake-args "-DUSE_SYSTEM_LIBVTERM=yes")
2020-04-13 19:20:37 +00:00
#+END_SRC
I also use a 'fancy powerline setup' with [[https://github.com/romkatv/powerlevel10k][Powerlevel10k]], so I need to use a
patched font for my terminal. Unfortunately I haven't quite figured out how to
do this yet.
2020-04-29 08:47:48 +00:00
** Which-key
2020-04-14 09:12:09 +00:00
Let's make this popup a bit faster
#+BEGIN_SRC emacs-lisp
(setq which-key-idle-delay 0.5) ;; I need the help, I really do
#+END_SRC
2020-04-23 02:19:31 +00:00
I also think that having =evil-= appear in so many popups is a bit too verbose, let's change that, and do a few other similar tweaks while we're at it.
2020-04-17 12:34:25 +00:00
#+BEGIN_SRC emacs-lisp
(setq which-key-allow-multiple-replacements t)
(after! which-key
(pushnew!
which-key-replacement-alist
'(("" . "\\`+?evil[-:]?\\(?:a-\\)?\\(.*\\)") . (nil . "◂\\1"))
'(("\\`g s" . "\\`evilem--?motion-\\(.*\\)") . (nil . "◃\\1"))
))
#+END_SRC
2020-05-16 07:44:01 +00:00
** xkcd
We wan't to set this up so it loads nicely in [[*Extra links][Extra links]].
#+BEGIN_SRC emacs-lisp
(use-package! xkcd
:commands (xkcd-get-json xkcd-download xkcd-get
;; now for funcs from my extension of this pkg
+xkcd-find-and-copy +xkcd-find-and-view
+xkcd-fetch-info +xkcd-select)
:config
(add-to-list 'evil-snipe-disabled-modes 'xkcd-mode)
:general (:states 'normal
:keymaps 'xkcd-mode-map
"<right>" #'xkcd-next
"n" #'xkcd-next ; evil-ish
"<left>" #'xkcd-prev
"N" #'xkcd-prev ; evil-ish
"r" #'xkcd-rand
"a" #'xkcd-rand ; because image-rotate can interfere
"t" #'xkcd-alt-text
"q" #'xkcd-kill-buffer
"o" #'xkcd-open-browser
"e" #'xkcd-open-explanation-browser
;; extras
"s" #'+xkcd-find-and-view
"/" #'+xkcd-find-and-view
"y" #'+xkcd-copy))
#+END_SRC
Let's also extend the functionality a whole bunch.
#+BEGIN_SRC emacs-lisp
(after! xkcd
(require 'emacsql-sqlite)
(defun +xkcd-select ()
"Prompt the user for an xkcd using `ivy-read' and `+xkcd-select-format'. Return the xkcd number or nil"
(let* (prompt-lines
(-dummy (maphash (lambda (key xkcd-info)
(push (+xkcd-select-format xkcd-info) prompt-lines))
+xkcd-stored-info))
(num (ivy-read (format "xkcd (%s): " xkcd-latest) prompt-lines)))
(if (equal "" num) xkcd-latest
(string-to-number (replace-regexp-in-string "\\([0-9]+\\).*" "\\1" num)))))
(defun +xkcd-select-format (xkcd-info)
"Creates each ivy-read line from an xkcd info plist. Must start with the xkcd number"
(format "%-4s %-30s %s"
(propertize (number-to-string (plist-get xkcd-info :num))
'face 'counsel-key-binding)
(plist-get xkcd-info :title)
(propertize (plist-get xkcd-info :alt)
'face '(variable-pitch font-lock-comment-face))))
(defun +xkcd-fetch-info (&optional num)
"Fetch the parsed json info for comic NUM. Fetches latest when omitted or 0"
(require 'xkcd)
(when (or (not num) (= num 0))
(+xkcd-check-latest)
(setq num xkcd-latest))
(let ((res (or (gethash num +xkcd-stored-info)
(puthash num (+xkcd-db-read num) +xkcd-stored-info))))
(unless res
(+xkcd-db-write
(let* ((url (format "http://xkcd.com/%d/info.0.json" num))
(json-assoc
(if (assoc num +xkcd-stored-info)
(assoc num +xkcd-stored-info)
(json-read-from-string (xkcd-get-json url num)))))
json-assoc))
(setq res (+xkcd-db-read num)))
res))
;; since we've done this, we may as well go one little step further
(defun +xkcd-find-and-copy ()
"Prompt for an xkcd using `+xkcd-select' and copy url to clipboard"
(interactive)
(+xkcd-copy (+xkcd-select)))
(defun +xkcd-copy (&optional num)
"Copy a url to xkcd NUM to the clipboard"
(interactive "i")
(let ((num (or num xkcd-cur)))
(gui-select-text (format "https://xkcd.com/%d" num))
(message "xkcd.com/%d copied to clipboard" num)))
(defun +xkcd-find-and-view ()
"Prompt for an xkcd using `+xkcd-select' and view it"
(interactive)
(xkcd-get (+xkcd-select))
(switch-to-buffer "*xkcd*"))
(defvar +xkcd-latest-max-age (* 60 60) ; 1 hour
"Time after which xkcd-latest should be refreshed, in seconds")
;; initialise `xkcd-latest' and `+xkcd-stored-info' with latest xkcd
(add-transient-hook! '+xkcd-select
(require 'xkcd)
(+xkcd-fetch-info xkcd-latest)
(setq +xkcd-stored-info (+xkcd-db-read-all)))
(add-transient-hook! '+xkcd-fetch-info
(xkcd-update-latest))
(defun +xkcd-check-latest ()
"Use value in `xkcd-cache-latest' as long as it isn't older thabn `+xkcd-latest-max-age'"
(unless (and (file-exists-p xkcd-cache-latest)
(< (- (time-to-seconds (current-time))
(time-to-seconds (file-attribute-modification-time (file-attributes xkcd-cache-latest))))
+xkcd-latest-max-age))
(let* ((out (xkcd-get-json "http://xkcd.com/info.0.json" 0))
(json-assoc (json-read-from-string out))
(latest (cdr (assoc 'num json-assoc))))
(when (/= xkcd-latest latest)
(+xkcd-db-write json-assoc)
(with-current-buffer (find-file xkcd-cache-latest)
(setq xkcd-latest latest)
(erase-buffer)
(insert (number-to-string latest))
(save-buffer)
(kill-buffer (current-buffer)))))
(shell-command (format "touch %s" xkcd-cache-latest))))
(defvar +xkcd-stored-info (make-hash-table :test 'eql)
"Basic info on downloaded xkcds, in the form of a hashtable")
(defadvice! xkcd-get-json--and-cache (url &optional num)
"Fetch the Json coming from URL.
If the file NUM.json exists, use it instead.
If NUM is 0, always download from URL.
The return value is a string."
:override #'xkcd-get-json
(let* ((file (format "%s%d.json" xkcd-cache-dir num))
(cached (and (file-exists-p file) (not (eq num 0))))
(out (with-current-buffer (if cached
(find-file file)
(url-retrieve-synchronously url))
(goto-char (point-min))
(unless cached (re-search-forward "^$"))
(prog1
(buffer-substring-no-properties (point) (point-max))
(kill-buffer (current-buffer))))))
(unless (or cached (eq num 0))
(xkcd-cache-json num out))
out))
(defadvice! +xkcd-get (num)
"Get the xkcd number NUM."
:override 'xkcd-get
(interactive "nEnter comic number: ")
(xkcd-update-latest)
(get-buffer-create "*xkcd*")
(switch-to-buffer "*xkcd*")
(xkcd-mode)
(let (buffer-read-only)
(erase-buffer)
(setq xkcd-cur num)
(let* ((xkcd-data (+xkcd-fetch-info num))
(num (plist-get xkcd-data :num))
(img (plist-get xkcd-data :img))
(safe-title (plist-get xkcd-data :safe-title))
(alt (plist-get xkcd-data :alt))
title file)
(message "Getting comic...")
(setq file (xkcd-download img num))
(setq title (format "%d: %s" num safe-title))
(insert (propertize title
'face 'outline-1))
(center-line)
(insert "\n")
(xkcd-insert-image file num)
(if (eq xkcd-cur 0)
(setq xkcd-cur num))
(setq xkcd-alt alt)
(message "%s" title))))
(defconst +xkcd-db--sqlite-available-p
(with-demoted-errors "+org-xkcd initialization: %S"
(emacsql-sqlite-ensure-binary)
t))
(defvar +xkcd-db--connection (make-hash-table :test #'equal)
"Database connection to +org-xkcd database.")
(defun +xkcd-db--get ()
"Return the sqlite db file."
(expand-file-name "xkcd.db" xkcd-cache-dir))
(defun +xkcd-db--get-connection ()
"Return the database connection, if any."
(gethash (file-truename xkcd-cache-dir)
+xkcd-db--connection))
(defconst +xkcd-db--table-schema
'((xkcds
[(num integer :unique :primary-key)
(year :not-null)
(month :not-null)
(link :not-null)
(news :not-null)
(safe_title :not-null)
(title :not-null)
(transcript :not-null)
(alt :not-null)
(img :not-null)])))
(defun +xkcd-db--init (db)
"Initialize database DB with the correct schema and user version."
(emacsql-with-transaction db
(pcase-dolist (`(,table . ,schema) +xkcd-db--table-schema)
(emacsql db [:create-table $i1 $S2] table schema))))
(defun +xkcd-db ()
"Entrypoint to the +org-xkcd sqlite database.
Initializes and stores the database, and the database connection.
Performs a database upgrade when required."
(unless (and (+xkcd-db--get-connection)
(emacsql-live-p (+xkcd-db--get-connection)))
(let* ((db-file (+xkcd-db--get))
(init-db (not (file-exists-p db-file))))
(make-directory (file-name-directory db-file) t)
(let ((conn (emacsql-sqlite db-file)))
(set-process-query-on-exit-flag (emacsql-process conn) nil)
(puthash (file-truename xkcd-cache-dir)
conn
+xkcd-db--connection)
(when init-db
(+xkcd-db--init conn)))))
(+xkcd-db--get-connection))
(defun +xkcd-db-query (sql &rest args)
"Run SQL query on +org-xkcd database with ARGS.
SQL can be either the emacsql vector representation, or a string."
(if (stringp sql)
(emacsql (+xkcd-db) (apply #'format sql args))
(apply #'emacsql (+xkcd-db) sql args)))
(defun +xkcd-db-read (num)
(when-let ((res
(car (+xkcd-db-query [:select * :from xkcds
:where (= num $s1)]
num
:limit 1))))
(+xkcd-db-list-to-plist res)))
(defun +xkcd-db-read-all ()
(let ((xkcd-table (make-hash-table :test 'eql :size 4000)))
(mapcar (lambda (xkcd-info-list)
(puthash (car xkcd-info-list) (+xkcd-db-list-to-plist xkcd-info-list) xkcd-table))
(+xkcd-db-query [:select * :from xkcds]))
xkcd-table))
(defun +xkcd-db-list-to-plist (xkcd-datalist)
`(:num ,(nth 0 xkcd-datalist)
:year ,(nth 1 xkcd-datalist)
:month ,(nth 2 xkcd-datalist)
:link ,(nth 3 xkcd-datalist)
:news ,(nth 4 xkcd-datalist)
:safe-title ,(nth 5 xkcd-datalist)
:title ,(nth 6 xkcd-datalist)
:transcript ,(nth 7 xkcd-datalist)
:alt ,(nth 8 xkcd-datalist)
:img ,(nth 9 xkcd-datalist)))
(defun +xkcd-db-write (data)
(+xkcd-db-query [:insert-into xkcds
:values $v1]
(list (vector
(cdr (assoc 'num data))
(cdr (assoc 'year data))
(cdr (assoc 'month data))
(cdr (assoc 'link data))
(cdr (assoc 'news data))
(cdr (assoc 'safe_title data))
(cdr (assoc 'title data))
(cdr (assoc 'transcript data))
(cdr (assoc 'alt data))
(cdr (assoc 'img data))
)))))
2020-05-16 07:44:01 +00:00
#+END_SRC
** YASnippet
Nested snippets are good, enable that.
#+BEGIN_SRC emacs-lisp
(setq yas-triggers-in-field t)
#+END_SRC
* Language configuration
*** File Templates
For some file types, we overwrite defaults in the [[file:./snippets][snippets]] directory, others
need to have a template assigned.
#+BEGIN_SRC emacs-lisp
(set-file-template! "\\.tex$" :trigger "__" :mode 'latex-mode)
#+END_SRC
2020-04-14 09:12:09 +00:00
** Plaintext
It's nice to see ansi colour codes displayed
#+BEGIN_SRC emacs-lisp
(after! text-mode
(add-hook! 'text-mode-hook
;; Apply ANSI color codes
(with-silent-modifications
(ansi-color-apply-on-region (point-min) (point-max)))))
#+END_SRC
** Org Mode
2020-04-29 10:32:57 +00:00
:PROPERTIES:
:CUSTOM_ID: org
:END:
2020-05-15 10:07:10 +00:00
I really like org mode, I've given some thought to why, and below is the result.
#+PLOT: transpose:yes type:radar min:0 max:4 file:"misc/document-format-comparison.png"
| Format | Fine-grained-control | Initial Effort | Syntax simplicity | Editor Support | Integrations | Ease-of-referencing | Versatility |
|-------------------+----------------------+----------------+-------------------+----------------+--------------+---------------------+-------------|
| Word | 2 | 4 | 4 | 2 | 3 | 2 | 2 |
| LaTeX | 4 | 1 | 1 | 3 | 2 | 4 | 3 |
| Org Mode | 4 | 2 | 3.5 | 1 | 4 | 4 | 4 |
| Markdown | 1 | 3 | 3 | 4 | 3 | 3 | 1 |
| Markdown + Pandoc | 2.5 | 2.5 | 2.5 | 3 | 3 | 3 | 2 |
[[https://media.githubusercontent.com/media/tecosaur/emacs-config/master/misc/document-format-comparison.png]]
2020-05-15 10:07:10 +00:00
*** System config
Org mode isn't recognised as it's own mime type by default, but that can easily
be changed with the following file. For system-wide changes try
~~/usr/share/mime/packages/org.xml~.
#+BEGIN_SRC xml :tangle ~/.local/share/mime/packages/org.xml
<?xml version="1.0" encoding="utf-8"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
<mime-type type="text/org">
<comment>Emacs Org-mode File</comment>
<glob pattern="*.org"/>
<alias type="text/org"/>
</mime-type>
</mime-info>
#+END_SRC
What's nice is that Papirus [[https://github.com/PapirusDevelopmentTeam/papirus-icon-theme/commit/a10fb7f2423d5e30b9c4477416ccdc93c4f3849d][now]] has an icon for =text/org=.
One simply needs to refresh their mime database
2020-03-23 02:59:27 +00:00
#+BEGIN_SRC shell :results silent
update-mime-database ~/.local/share/mime
#+END_SRC
Then set Emacs as the default editor
2020-03-23 02:59:27 +00:00
#+BEGIN_SRC shell :results silent
xdg-mime default emacs.desktop text/org
#+END_SRC
*** Behaviour
[[xkcd:1319]]
2020-03-23 11:07:40 +00:00
**** Tweaking defaults
#+BEGIN_SRC emacs-lisp
(setq org-directory "~/.org" ; let's put files here
org-use-property-inheritance t ; it's convenient to have properties inherited
org-log-done 'time ; having the time a item is done sounds convininet
org-list-allow-alphabetical t ; have a. A. a) A) list bullets
org-export-in-background t ; run export processes in external emacs process
org-catch-invisible-edits 'smart) ; try not to accidently do weird stuff in invisible regions
#+END_SRC
2020-03-23 11:07:40 +00:00
I also like the ~:comments~ header-argument, so let's make that a default.
#+BEGIN_SRC emacs-lisp
(setq org-babel-default-header-args '((:session . "none")
(:results . "replace")
(:exports . "code")
(:cache . "no")
(:noweb . "no")
(:hlines . "no")
(:tangle . "no")
(:comments . "link")))
#+END_SRC
By default, ~visual-line-mode~ is turned =on=, and ~auto-fill-mode~ =off= by a hook.
However this messes with tables in Org-mode, and other plaintext files (e.g.
markdown, \LaTeX) so I'll turn it off for this, and manually enable it for more
specific modes as desired.
#+BEGIN_SRC emacs-lisp
(remove-hook 'text-mode-hook #'visual-line-mode)
(add-hook 'text-mode-hook #'auto-fill-mode)
#+END_SRC
2020-03-23 11:07:40 +00:00
**** Extra functionality
Let's also make creating an org buffer just that little bit easier.
#+BEGIN_SRC emacs-lisp
(evil-define-command evil-buffer-org-new (count file)
"Creates a new ORG buffer replacing the current window, optionally
editing a certain FILE"
:repeat nil
(interactive "P<f>")
(if file
(evil-edit file)
(let ((buffer (generate-new-buffer "*new org*")))
(set-window-buffer nil buffer)
(with-current-buffer buffer
(org-mode)))))
(map! :leader
(:prefix "b"
:desc "New empty ORG buffer" "o" #'evil-buffer-org-new))
#+END_SRC
2020-02-29 10:46:14 +00:00
I think it makes sense to have list bullets change with depth
#+BEGIN_SRC emacs-lisp
(setq org-list-demote-modify-bullet '(("+" . "-") ("-" . "+") ("*" . "+")))
#+END_SRC
2020-02-26 11:05:41 +00:00
Occasionally I want to cite something.
#+BEGIN_SRC emacs-lisp
(use-package! org-ref
2020-02-26 11:05:41 +00:00
:after org
:config
(setq org-ref-completion-library 'org-ref-ivy-cite))
#+END_SRC
It's also nice to be able to use ~cdlatex~.
#+BEGIN_SRC emacs-lisp
(after! org (add-hook 'org-mode-hook 'turn-on-org-cdlatex))
#+END_SRC
At some point in the future it could be good to investigate [[https://scripter.co/splitting-an-org-block-into-two/][splitting org blocks]].
Likewise [[https://archive.casouri.cat/note/2020/insert-math-symbol-in-emacs/][this]] looks good for symbols.
2020-03-23 03:01:31 +00:00
My spelling is atrocious, so let's get flycheck going.
#+BEGIN_SRC emacs-lisp
(after! org (add-hook 'org-mode-hook 'turn-on-flyspell))
#+END_SRC
Now, by default, LSPs don't really function at all in ~src~ blocks.
#+BEGIN_SRC emacs-lisp
(cl-defmacro lsp-org-babel-enable (lang)
"Support LANG in org source code block."
(setq centaur-lsp 'lsp-mode)
(cl-check-type lang stringp)
(let* ((edit-pre (intern (format "org-babel-edit-prep:%s" lang)))
(intern-pre (intern (format "lsp--%s" (symbol-name edit-pre)))))
`(progn
(defun ,intern-pre (info)
(let ((file-name (->> info caddr (alist-get :file))))
(unless file-name
(setq file-name (make-temp-file "babel-lsp-")))
(setq buffer-file-name file-name)
(lsp-deferred)))
(put ',intern-pre 'function-documentation
(format "Enable lsp-mode in the buffer of org source block (%s)."
(upcase ,lang)))
(if (fboundp ',edit-pre)
(advice-add ',edit-pre :after ',intern-pre)
(progn
(defun ,edit-pre (info)
(,intern-pre info))
(put ',edit-pre 'function-documentation
(format "Prepare local buffer environment for org source block (%s)."
(upcase ,lang))))))))
(defvar org-babel-lang-list
'("go" "python" "ipython" "bash" "sh"))
(dolist (lang org-babel-lang-list)
(eval `(lsp-org-babel-enable ,lang)))
#+END_SRC
**** Super agenda
#+BEGIN_SRC emacs-lisp
(use-package! org-super-agenda
:commands (org-super-agenda-mode))
(after! org-agenda
(org-super-agenda-mode))
(setq org-agenda-skip-scheduled-if-done t
org-agenda-skip-deadline-if-done t
org-agenda-include-deadlines t
org-agenda-block-separator nil
org-agenda-tags-column 100 ;; from testing this seems to be a good value
org-agenda-compact-blocks t)
(setq org-agenda-custom-commands
'(("o" "Overview"
((agenda "" ((org-agenda-span 'day)
(org-super-agenda-groups
'((:name "Today"
:time-grid t
:date today
:todo "TODAY"
:scheduled today
:order 1)))))
(alltodo "" ((org-agenda-overriding-header "")
(org-super-agenda-groups
'((:name "Next to do"
:todo "NEXT"
:order 1)
(:name "Important"
:tag "Important"
:priority "A"
:order 6)
(:name "Due Today"
:deadline today
:order 2)
(:name "Due Soon"
:deadline future
:order 8)
(:name "Overdue"
:deadline past
:face error
:order 7)
(:name "Assignments"
:tag "Assignment"
:order 10)
(:name "Issues"
:tag "Issue"
:order 12)
(:name "Emacs"
:tag "Emacs"
:order 13)
(:name "Projects"
:tag "Project"
:order 14)
(:name "Research"
:tag "Research"
:order 15)
(:name "To read"
:tag "Read"
:order 30)
(:name "Waiting"
:todo "WAITING"
:order 20)
(:name "University"
:tag "uni"
:order 32)
(:name "Trivial"
:priority<= "E"
:tag ("Trivial" "Unimportant")
:todo ("SOMEDAY" )
:order 90)
(:discard (:tag ("Chore" "Routine" "Daily")))))))))))
#+END_SRC
**** Capture
Let's setup some org-capture templates
#+BEGIN_SRC emacs-lisp :noweb yes
(use-package! doct
:commands (doct))
(after! org-capture
<<prettify-capture>>
(setq +org-capture-uni-units (split-string (f-read-text "~/.org/.uni-units")))
(setq +org-capture-recipies "~/Desktop/TEC/Organisation/recipies.org")
(defun +doct-icon-declaration-to-icon (declaration)
"Convert :icon declaration to icon"
(let ((name (pop declaration))
(set (intern (concat "all-the-icons-" (plist-get declaration :set))))
(face (intern (concat "all-the-icons-" (plist-get declaration :color))))
(v-adjust (or (plist-get declaration :v-adjust) 0.01)))
(apply set `(,name :face ,face :v-adjust ,v-adjust))))
(defun +doct-iconify-capture-templates (groups)
"Add declaration's :icon to each template group in GROUPS."
(let ((templates (doct-flatten-lists-in groups)))
(setq doct-templates (mapcar (lambda (template)
(when-let* ((props (nthcdr (if (= (length template) 4) 2 5) template))
(spec (plist-get (plist-get props :doct) :icon)))
(setf (nth 1 template) (concat (+doct-icon-declaration-to-icon spec)
"\t"
(nth 1 template))))
template)
templates))))
(setq doct-after-conversion-functions '(+doct-iconify-capture-templates))
(add-transient-hook! 'org-capture-select-template
(setq org-capture-templates
(doct `(("Personal todo" :keys "t"
:icon ("checklist" :set "octicon" :color "green")
:file +org-capture-todo-file
:prepend t
:headline "Inbox"
:type entry
:template ("* TODO %?"
"%i %a")
)
("Personal note" :keys "n"
:icon ("sticky-note-o" :set "faicon" :color "green")
:file +org-capture-todo-file
:prepend t
:headline "Inbox"
:type entry
:template ("* %?"
"%i %a")
)
("University" :keys "u"
:icon ("graduation-cap" :set "faicon" :color "purple")
:file +org-capture-todo-file
:headline "University"
:unit-prompt ,(format "%%^{Unit|%s}" (string-join +org-capture-uni-units "|"))
:prepend t
:type entry
:children (("Test" :keys "t"
:icon ("timer" :set "material" :color "red")
:template ("* TODO [#C] %{unit-prompt} %? :uni:tests:"
"SCHEDULED: %^{Test date:}T"
"%i %a"))
("Assignment" :keys "a"
:icon ("library_books" :set "material" :color "orange")
:template ("* TODO [#B] %{unit-prompt} %? :uni:assignments:"
"DEADLINE: %^{Due date:}T"
"%i %a"))
("Lecture" :keys "l"
:icon ("keynote" :set "fileicon" :color "orange")
:template ("* TODO [#C] %{unit-prompt} %? :uni:lecture:"
"%i %a"))
("Miscellaneous task" :keys "u"
:icon ("list" :set "faicon" :color "yellow")
:template ("* TODO [#D] %{unit-prompt} %? :uni:"
"%i %a"))))
("Email" :keys "e"
:icon ("envelope" :set "faicon" :color "blue")
:file +org-capture-todo-file
:prepend t
:headline "Inbox"
:type entry
2020-04-13 19:09:13 +00:00
:template ("* TODO %^{type|reply to|contact} %\\3 %? :email:"
"Send an email %^{urgancy|soon|ASAP|anon|at some point|eventually} to %^{recipiant}"
"about %^{topic}"
"%U %i %a"))
("Interesting" :keys "i"
:icon ("eye" :set "faicon" :color "lcyan")
:file +org-capture-todo-file
:prepend t
:headline "Interesting"
:type entry
:template ("* [ ] %{desc}%? :%{i-type}:"
"%i %a")
:children (("Webpage" :keys "w"
:icon ("globe" :set "faicon" :color "green")
:desc "%(org-cliplink-capture) "
:i-type "read:web"
)
("Article" :keys "a"
:icon ("file-text" :set "octicon" :color "yellow")
:desc ""
:i-type "read:reaserch"
)
("\tRecipie" :keys "r"
:icon ("spoon" :set "faicon" :color "dorange")
:file +org-capture-recipies
:headline "Unsorted"
:template "%(org-chef-get-recipe-from-url)"
)
("Information" :keys "i"
:icon ("info-circle" :set "faicon" :color "blue")
:desc ""
:i-type "read:info"
)
("Idea" :keys "I"
:icon ("bubble_chart" :set "material" :color "silver")
:desc ""
:i-type "idea"
)))
("Tasks" :keys "k"
:icon ("inbox" :set "octicon" :color "yellow")
:file +org-capture-todo-file
:prepend t
:headline "Tasks"
:type entry
:template ("* TODO %? %^G%{extra}"
2020-04-20 08:00:48 +00:00
"%i %a")
:children (("General Task" :keys "k"
:icon ("inbox" :set "octicon" :color "yellow")
:extra ""
)
("Task with deadline" :keys "d"
:icon ("timer" :set "material" :color "orange" :v-adjust -0.1)
:extra "\nDEADLINE: %^{Deadline:}t"
)
("Scheduled Task" :keys "s"
:icon ("calendar" :set "octicon" :color "orange")
:extra "\nSCHEDULED: %^{Start time:}t"
)
))
("Project" :keys "p"
:icon ("repo" :set "octicon" :color "silver")
:prepend t
:type entry
:headline "Inbox"
:template ("* %{time-or-todo} %?"
"%i"
"%a")
:file ""
:custom (:time-or-todo "")
:children (("Project-local todo" :keys "t"
:icon ("checklist" :set "octicon" :color "green")
:time-or-todo "TODO"
:file +org-capture-project-todo-file)
("Project-local note" :keys "n"
:icon ("sticky-note" :set "faicon" :color "yellow")
:time-or-todo "%U"
:file +org-capture-project-notes-file)
("Project-local changelog" :keys "c"
:icon ("list" :set "faicon" :color "blue")
:time-or-todo "%U"
:heading "Unreleased"
:file +org-capture-project-changelog-file))
)
("\tCentralised project templates"
:keys "o"
:type entry
:prepend t
:template ("* %{time-or-todo} %?"
"%i"
"%a")
:children (("Project todo"
:keys "t"
:prepend nil
:time-or-todo "TODO"
:heading "Tasks"
:file +org-capture-central-project-todo-file)
("Project note"
:keys "n"
:time-or-todo "%U"
:heading "Notes"
:file +org-capture-central-project-notes-file)
("Project changelog"
:keys "c"
:time-or-todo "%U"
:heading "Unreleased"
:file +org-capture-central-project-changelog-file))
))))))
#+END_SRC
It would also be nice to improve how the capture dialogue looks
#+NAME: prettify-capture
#+BEGIN_SRC emacs-lisp :tangle no
(defun org-capture-select-template-prettier (&optional keys)
"Select a capture template, in a prettier way than default
Lisp programs can force the template by setting KEYS to a string."
(let ((org-capture-templates
(or (org-contextualize-keys
(org-capture-upgrade-templates org-capture-templates)
org-capture-templates-contexts)
'(("t" "Task" entry (file+headline "" "Tasks")
"* TODO %?\n %u\n %a")))))
(if keys
(or (assoc keys org-capture-templates)
(error "No capture template referred to by \"%s\" keys" keys))
(org-mks org-capture-templates
"Select a capture template\n━━━━━━━━━━━━━━━━━━━━━━━━━"
"Template key: "
`(("q" ,(concat (all-the-icons-octicon "stop" :face 'all-the-icons-red :v-adjust 0.01) "\tAbort")))))))
(advice-add 'org-capture-select-template :override #'org-capture-select-template-prettier)
(defun org-mks-pretty (table title &optional prompt specials)
"Select a member of an alist with multiple keys. Prettified.
TABLE is the alist which should contain entries where the car is a string.
There should be two types of entries.
1. prefix descriptions like (\"a\" \"Description\")
This indicates that `a' is a prefix key for multi-letter selection, and
that there are entries following with keys like \"ab\", \"ax\"…
2. Select-able members must have more than two elements, with the first
being the string of keys that lead to selecting it, and the second a
short description string of the item.
The command will then make a temporary buffer listing all entries
that can be selected with a single key, and all the single key
prefixes. When you press the key for a single-letter entry, it is selected.
When you press a prefix key, the commands (and maybe further prefixes)
under this key will be shown and offered for selection.
TITLE will be placed over the selection in the temporary buffer,
PROMPT will be used when prompting for a key. SPECIALS is an
alist with (\"key\" \"description\") entries. When one of these
is selected, only the bare key is returned."
(save-window-excursion
(let ((inhibit-quit t)
(buffer (org-switch-to-buffer-other-window "*Org Select*"))
(prompt (or prompt "Select: "))
case-fold-search
current)
(unwind-protect
(catch 'exit
(while t
(setq-local evil-normal-state-cursor (list nil))
(erase-buffer)
(insert title "\n\n")
(let ((des-keys nil)
(allowed-keys '("\C-g"))
(tab-alternatives '("\s" "\t" "\r"))
(cursor-type nil))
;; Populate allowed keys and descriptions keys
;; available with CURRENT selector.
(let ((re (format "\\`%s\\(.\\)\\'"
(if current (regexp-quote current) "")))
(prefix (if current (concat current " ") "")))
(dolist (entry table)
(pcase entry
;; Description.
(`(,(and key (pred (string-match re))) ,desc)
(let ((k (match-string 1 key)))
(push k des-keys)
;; Keys ending in tab, space or RET are equivalent.
(if (member k tab-alternatives)
(push "\t" allowed-keys)
(push k allowed-keys))
(insert (propertize prefix 'face 'font-lock-comment-face) (propertize k 'face 'bold) (propertize "" 'face 'font-lock-comment-face) " " desc "…" "\n")))
;; Usable entry.
(`(,(and key (pred (string-match re))) ,desc . ,_)
(let ((k (match-string 1 key)))
(insert (propertize prefix 'face 'font-lock-comment-face) (propertize k 'face 'bold) " " desc "\n")
(push k allowed-keys)))
(_ nil))))
;; Insert special entries, if any.
(when specials
(insert "─────────────────────────\n")
(pcase-dolist (`(,key ,description) specials)
(insert (format "%s %s\n" (propertize key 'face '(bold all-the-icons-red)) description))
(push key allowed-keys)))
;; Display UI and let user select an entry or
;; a sub-level prefix.
(goto-char (point-min))
(unless (pos-visible-in-window-p (point-max))
(org-fit-window-to-buffer))
(let ((pressed (org--mks-read-key allowed-keys prompt)))
(setq current (concat current pressed))
(cond
((equal pressed "\C-g") (user-error "Abort"))
;; Selection is a prefix: open a new menu.
((member pressed des-keys))
;; Selection matches an association: return it.
((let ((entry (assoc current table)))
(and entry (throw 'exit entry))))
;; Selection matches a special entry: return the
;; selection prefix.
((assoc current specials) (throw 'exit current))
(t (error "No entry available")))))))
(when buffer (kill-buffer buffer))))))
(advice-add 'org-mks :override #'org-mks-pretty)
#+END_SRC
The [[file:~/.emacs.d/bin/org-capture][org-capture bin]] is rather nice, but I'd be nicer with a smaller frame, and
no modeline.
#+BEGIN_SRC emacs-lisp
(setf (alist-get 'height +org-capture-frame-parameters) 15)
;; (alist-get 'name +org-capture-frame-parameters) "❖ Capture") ;; ATM hardcoded in other places, so changing breaks stuff
(setq +org-capture-fn
(lambda ()
(interactive)
(set-window-parameter nil 'mode-line-format 'none)
(org-capture)))
#+END_SRC
2020-04-28 18:41:46 +00:00
**** Roam
***** Basic settings
I'll just set this to be within =Organisation= folder for now, in the future it
could be worth seeing if I could hook this up to a [[https://nextcloud.com/][Nextcloud]] instance.
#+BEGIN_SRC emacs-lisp
(setq org-roam-directory "~/Desktop/TEC/Organisation/Roam")
#+END_SRC
***** Registering roam protocol
The recommended method of registering a protocal is by registering a desktop
application, which seems reasonable.
#+BEGIN_SRC conf :tangle ~/.local/share/applications/org-protocol.desktop
[Desktop Entry]
Name=Org-Protocol
Exec=emacsclient %u
Icon=emacs-icon
Type=Application
Terminal=false
MimeType=x-scheme-handler/org-protocol
#+END_SRC
To associate ~org-protocol://~ links with the desktop file,
#+BEGIN_SRC shell
xdg-mime default org-protocol.desktop x-scheme-handler/org-protocol
#+END_SRC
***** Graph Behaviour
2020-05-09 18:48:36 +00:00
By default, clicking on an ~org-protocol://~ link messes with the =svg= view. To fix
this we can use an ~iframe~, however that requires shifting to an =html= file.
Hence, we need to do a bit of overriding.
#+BEGIN_SRC html :tangle misc/org-roam-template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Roam Graph</title>
<meta name="viewport" content="width=device-width">
<style type="text/css">
svg {
position: relative;
top: 50vh;
left: 50vw;
transform: translate(-50%, -50%);
}
a > polygon {
transition-duration: 200ms;
transition-property: fill;
}
a > polyline {
transition-duration: 400ms;
transition-property: stroke;
}
a:hover > polygon {
fill: #d4d4d4;
}
a:hover > polyline {
stroke: #888;
}
</style>
<script type="text/javascript">
function create_iframe (url) {
i = document.createElement('iframe');
i.setAttribute('src', url);
i.style.setProperty('display', 'none');
document.body.append(i);
}
function listen_on_all_a () {
document.querySelectorAll("svg a").forEach(elem => {
elem.addEventListener('click', (e) => {
e.preventDefault();
create_iframe(elem.href.baseVal);
});
});
}
</script>
</head>
<body onload="listen_on_all_a()">
%s
</body>
</html>
#+END_SRC
#+BEGIN_SRC emacs-lisp
(after! org-roam
(setq +org-roam-graph--html-template (replace-regexp-in-string "%\\([^s]\\)" "%%\\1" (f-read-text (concat doom-private-dir "misc/org-roam-template.html"))))
(defadvice! +org-roam-graph--build-html (&optional node-query)
"Generate a graph showing the relations between nodes in NODE-QUERY. HTML style."
:override #'org-roam-graph--build
(unless org-roam-graph-executable
(user-error "Can't find %s executable. Please check if it is in your path"
org-roam-graph-executable))
(let* ((node-query (or node-query
`[:select [file titles]
:from titles
,@(org-roam-graph--expand-matcher 'file t)]))
(graph (org-roam-graph--dot node-query))
(temp-dot (make-temp-file "graph." nil ".dot" graph))
(temp-graph (make-temp-file "graph." nil ".svg"))
(temp-html (make-temp-file "graph." nil ".html")))
(call-process org-roam-graph-executable nil 0 nil
temp-dot "-Tsvg" "-o" temp-graph)
(sleep-for 0.1)
(write-region (format +org-roam-graph--html-template (f-read-text temp-graph)) nil temp-html)
temp-html)))
2020-04-28 18:41:46 +00:00
#+END_SRC
***** Modeline file name
All those numbers! It's messy. Let's adjust this in a similar way that I have in
the[[*Window title][Window title]].
#+BEGIN_SRC emacs-lisp
(defadvice! doom-modeline--reformat-roam (orig-fun)
:around #'doom-modeline-buffer-file-name
(message "Reformat?")
(message (buffer-file-name))
(if (s-contains-p org-roam-directory (or buffer-file-name ""))
(replace-regexp-in-string
"\\(?:^\\|.*/\\)\\([0-9]\\{4\\}\\)\\([0-9]\\{2\\}\\)\\([0-9]\\{2\\}\\)[0-9]*-"
"🢔(\\1-\\2-\\3) "
(funcall orig-fun))
(funcall orig-fun)))
#+END_SRC
**** Nicer generated heading IDs
Thanks to alphapapa's [[https://github.com/alphapapa/unpackaged.el#export-to-html-with-useful-anchors][unpackaged.el]].
By default, ~url-hexify-string~ seemed to cause me some issues. Replacing that in
~a53899~ resolved this for me. To go one step further, I create a function for
producing nice short links, like an inferior version of ~reftex-label~.
#+BEGIN_SRC emacs-lisp
(defvar org-heading-contraction-max-words 3
"Maximum number of words in a heading")
(defvar org-heading-contraction-max-length 35
"Maximum length of resulting string")
(defvar org-heading-contraction-stripped-words
'("the" "on" "in" "off" "a" "for" "by" "of" "and" "is" "to")
"Unnecesary words to be removed from a heading")
(defun org-heading-contraction (heading-string)
"Get a contracted form of HEADING-STRING that is onlu contains alphanumeric charachters.
Strips 'joining' words in `org-heading-contraction-stripped-words',
and then limits the result to the first `org-heading-contraction-max-words' words.
If the total length is > `org-heading-contraction-max-length' then individual words are
truncated to fit within the limit"
(let ((heading-words
(-filter (lambda (word)
(not (member word org-heading-contraction-stripped-words)))
(split-string
(->> heading-string
s-downcase
(replace-regexp-in-string "\\[\\[[^]]+\\]\\[\\([^]]+\\)\\]\\]" "\\1") ; get description from org-link
(replace-regexp-in-string "[-/ ]+" " ") ; replace seperator-type chars with space
(replace-regexp-in-string "[^a-z0-9 ]" "") ; strip chars which need %-encoding in a uri
) " "))))
(when (> (length heading-words)
org-heading-contraction-max-words)
(setq heading-words
(subseq heading-words 0 org-heading-contraction-max-words)))
(when (> (+ (-sum (mapcar #'length heading-words))
(1- (length heading-words)))
org-heading-contraction-max-length)
;; trucate each word to a max word length determined by
;; max length = \floor{ \frac{total length - chars for seperators - \sum_{word \leq average length} length(word) }{num(words) > average length} }
(setq heading-words (let* ((total-length-budget (- org-heading-contraction-max-length ; how many non-separator chars we can use
(1- (length heading-words))))
(word-length-budget (/ total-length-budget ; max length of each word to keep within budget
org-heading-contraction-max-words))
(num-overlong (-count (lambda (word) ; how many words exceed that budget
(> (length word) word-length-budget))
heading-words))
(total-short-length (-sum (mapcar (lambda (word) ; total length of words under that budget
(if (<= (length word) word-length-budget)
(length word) 0))
heading-words)))
(max-length (/ (- total-length-budget total-short-length) ; max(max-length) that we can have to fit within the budget
num-overlong)))
(mapcar (lambda (word)
(if (<= (length word) max-length)
word
(substring word 0 max-length)))
heading-words))))
(string-join heading-words "-")))
#+END_SRC
Now here's alphapapa's subtley tweaked mode.
#+BEGIN_SRC emacs-lisp
(define-minor-mode unpackaged/org-export-html-with-useful-ids-mode
"Attempt to export Org as HTML with useful link IDs.
Instead of random IDs like \"#orga1b2c3\", use heading titles,
made unique when necessary."
:global t
(if unpackaged/org-export-html-with-useful-ids-mode
(advice-add #'org-export-get-reference :override #'unpackaged/org-export-get-reference)
(advice-remove #'org-export-get-reference #'unpackaged/org-export-get-reference)))
(defun unpackaged/org-export-get-reference (datum info)
"Like `org-export-get-reference', except uses heading titles instead of random numbers."
(let ((cache (plist-get info :internal-references)))
(or (car (rassq datum cache))
(let* ((crossrefs (plist-get info :crossrefs))
(cells (org-export-search-cells datum))
;; Preserve any pre-existing association between
;; a search cell and a reference, i.e., when some
;; previously published document referenced a location
;; within current file (see
;; `org-publish-resolve-external-link').
;;
;; However, there is no guarantee that search cells are
;; unique, e.g., there might be duplicate custom ID or
;; two headings with the same title in the file.
;;
;; As a consequence, before re-using any reference to
;; an element or object, we check that it doesn't refer
;; to a previous element or object.
(new (or (cl-some
(lambda (cell)
(let ((stored (cdr (assoc cell crossrefs))))
(when stored
(let ((old (org-export-format-reference stored)))
(and (not (assoc old cache)) stored)))))
cells)
(when (org-element-property :raw-value datum)
;; Heading with a title
(unpackaged/org-export-new-title-reference datum cache))
;; NOTE: This probably breaks some Org Export
;; feature, but if it does what I need, fine.
(org-export-format-reference
(org-export-new-reference cache))))
(reference-string new))
;; Cache contains both data already associated to
;; a reference and in-use internal references, so as to make
;; unique references.
(dolist (cell cells) (push (cons cell new) cache))
;; Retain a direct association between reference string and
;; DATUM since (1) not every object or element can be given
;; a search cell (2) it permits quick lookup.
(push (cons reference-string datum) cache)
(plist-put info :internal-references cache)
reference-string))))
(defun unpackaged/org-export-new-title-reference (datum cache)
"Return new reference for DATUM that is unique in CACHE."
(cl-macrolet ((inc-suffixf (place)
`(progn
(string-match (rx bos
(minimal-match (group (1+ anything)))
(optional "--" (group (1+ digit)))
eos)
,place)
;; HACK: `s1' instead of a gensym.
(-let* (((s1 suffix) (list (match-string 1 ,place)
(match-string 2 ,place)))
(suffix (if suffix
(string-to-number suffix)
0)))
(setf ,place (format "%s--%s" s1 (cl-incf suffix)))))))
(let* ((title (org-element-property :raw-value datum))
;; get ascii-only form of title without needing percent-encoding
(ref (org-heading-contraction (substring-no-properties title)))
(parent (org-element-property :parent datum)))
(while (--any (equal ref (car it))
cache)
;; Title not unique: make it so.
(if parent
;; Append ancestor title.
(setf title (concat (org-element-property :raw-value parent)
"--" title)
;; get ascii-only form of title without needing percent-encoding
ref (org-heading-contraction (substring-no-properties title))
parent (org-element-property :parent parent))
;; No more ancestors: add and increment a number.
(inc-suffixf ref)))
ref)))
(add-hook 'org-load-hook #'unpackaged/org-export-html-with-useful-ids-mode)
#+END_SRC
**** Nicer ~org-return~
Once again, from [[https://github.com/alphapapa/unpackaged.el#org-return-dwim][unpackaged.el]]
#+BEGIN_SRC emacs-lisp
(after! org
(defun unpackaged/org-element-descendant-of (type element)
"Return non-nil if ELEMENT is a descendant of TYPE.
TYPE should be an element type, like `item' or `paragraph'.
ELEMENT should be a list like that returned by `org-element-context'."
;; MAYBE: Use `org-element-lineage'.
(when-let* ((parent (org-element-property :parent element)))
(or (eq type (car parent))
(unpackaged/org-element-descendant-of type parent))))
;;;###autoload
(defun unpackaged/org-return-dwim (&optional default)
"A helpful replacement for `org-return-indent'. With prefix, call `org-return-indent'.
On headings, move point to position after entry content. In
lists, insert a new item or end the list, with checkbox if
appropriate. In tables, insert a new row or end the table."
;; Inspired by John Kitchin: http://kitchingroup.cheme.cmu.edu/blog/2017/04/09/A-better-return-in-org-mode/
(interactive "P")
(if default
(org-return t)
(cond
;; Act depending on context around point.
;; NOTE: I prefer RET to not follow links, but by uncommenting this block, links will be
;; followed.
;; ((eq 'link (car (org-element-context)))
;; ;; Link: Open it.
;; (org-open-at-point-global))
((org-at-heading-p)
;; Heading: Move to position after entry content.
;; NOTE: This is probably the most interesting feature of this function.
(let ((heading-start (org-entry-beginning-position)))
(goto-char (org-entry-end-position))
(cond ((and (org-at-heading-p)
(= heading-start (org-entry-beginning-position)))
;; Entry ends on its heading; add newline after
(end-of-line)
(insert "\n\n"))
(t
;; Entry ends after its heading; back up
(forward-line -1)
(end-of-line)
(when (org-at-heading-p)
;; At the same heading
(forward-line)
(insert "\n")
(forward-line -1))
;; FIXME: looking-back is supposed to be called with more arguments.
(while (not (looking-back (rx (repeat 3 (seq (optional blank) "\n")))))
(insert "\n"))
(forward-line -1)))))
((org-at-item-checkbox-p)
;; Checkbox: Insert new item with checkbox.
(org-insert-todo-heading nil))
((org-in-item-p)
;; Plain list. Yes, this gets a little complicated...
(let ((context (org-element-context)))
(if (or (eq 'plain-list (car context)) ; First item in list
(and (eq 'item (car context))
(not (eq (org-element-property :contents-begin context)
(org-element-property :contents-end context))))
(unpackaged/org-element-descendant-of 'item context)) ; Element in list item, e.g. a link
;; Non-empty item: Add new item.
(org-insert-item)
;; Empty item: Close the list.
;; TODO: Do this with org functions rather than operating on the text. Can't seem to find the right function.
(delete-region (line-beginning-position) (line-end-position))
(insert "\n"))))
((when (fboundp 'org-inlinetask-in-task-p)
(org-inlinetask-in-task-p))
;; Inline task: Don't insert a new heading.
(org-return t))
((org-at-table-p)
(cond ((save-excursion
(beginning-of-line)
;; See `org-table-next-field'.
(cl-loop with end = (line-end-position)
for cell = (org-element-table-cell-parser)
always (equal (org-element-property :contents-begin cell)
(org-element-property :contents-end cell))
while (re-search-forward "|" end t)))
;; Empty row: end the table.
(delete-region (line-beginning-position) (line-end-position))
(org-return t))
(t
;; Non-empty row: call `org-return-indent'.
(org-return t))))
(t
;; All other cases: call `org-return-indent'.
(org-return t)))))
(advice-add #'org-return-indent :override #'unpackaged/org-return-dwim))
#+END_SRC
2020-05-15 10:07:10 +00:00
**** Org Plot
There are two main bits of extra functionality I wan to add
+ the ability to transpose tables (internally)
+ a radar type
To accomplish this, overriding the ~org-plot/gnuplot~ function seems to be the
clear way. I tried this, and overrode so much that it seemed to make sense
just to modify =org-plot.el= instead, as it was only ~350 lines and I functions
that encompassed most of that line count.
Given that my [[file:lisp/org-plot.el][org-plot.el]] is now ~700 lines, this seems to have been a good call.
For transposition, I've added the following (equivalent) keys
+ ~[transpose|t]~
+ ~t~
When set to ~yes~, ~y~, or ~t~ the table is internally transposed (i.e. the =elisp= data
form of the table only).
The radar chart is a lot more involved, and I've added the following keys
+ ~type:radar~
This uses the radar template, the result of which can be seen in <<...>>
+ ~[min|ymin]:0..n~
This sets the start value of /every/ axis.
+ ~[max|ymax]:0..n~
This sets the end value of /every/ axis.
If both ~ymin~ and ~ymax~ are set, only the first axis gets tick labels.
+ ~ticks:0..n~
This sets the number of ticks. Only works for \(n>2\), or \(n=0\) in which
case no ticks are shown.
**** Extra links
***** xkcd
Because xkcd is cool, let's make it as easy and fun as possible to insert them.
Saving seconds adds up after all! (but only so much)
[[xkcd:1205]]
#+BEGIN_SRC emacs-lisp
(after! org
(org-link-set-parameters "xkcd"
:image-data-fun #'+org-xkcd-image-fn
:follow #'+org-xkcd-open-fn
:export #'+org-xkcd-export
:complete #'+org-xkcd-complete)
(defun +org-xkcd-open-fn (link)
(+org-xkcd-image-fn nil link nil))
2020-05-16 07:44:01 +00:00
(defun +org-xkcd-image-fn (protocol link description)
"Get image data for xkcd num LINK"
(let* ((xkcd-info (+xkcd-fetch-info (string-to-number link)))
2020-05-16 07:44:01 +00:00
(img (plist-get xkcd-info :img))
(alt (plist-get xkcd-info :alt)))
(message alt)
(+org-image-file-data-fn protocol (xkcd-download img (string-to-number link)) description)))
(defun +org-xkcd-export (path desc backend _com)
"Convert xkcd to html/LaTeX form"
(let* ((xkcd-info (+xkcd-fetch-info (string-to-number path)))
2020-05-16 07:44:01 +00:00
(img (plist-get xkcd-info :img))
(alt (plist-get xkcd-info :alt))
(title (plist-get xkcd-info :title))
(file (xkcd-download img (string-to-number path))))
(cond ((org-export-derived-backend-p backend 'html)
(format "<img src='%s' title=\"%s\" alt='%s'>" img (subst-char-in-string ?\" ?“ alt) title))
((org-export-derived-backend-p backend 'latex)
(format "\\begin{figure}[!htb]
\\centering
\\includegraphics[scale=0.4]{%s}
\\caption*{\\label{xkcd:%s} %s}
\\end{figure}" file path (or desc
(format "\\textbf{%s} %s" title alt))))
(t (format "https://xkcd.com/%s" path)))))
(defun +org-xkcd-complete (&optional arg)
"Complete xkcd using `+xkcd-stored-info'"
(format "xkcd:%d" (+xkcd-select))))
#+END_SRC
***** YouTube
The ~[[yt:...]]~ links preview nicely, but don't export nicely. Thankfully, we can
fix that.
#+BEGIN_SRC emacs-lisp
(after! org
(org-link-set-parameters "yt" :export #'+org-export-yt)
(defun +org-export-yt (path desc backend _com)
(cond ((org-export-derived-backend-p backend 'html)
(format "<iframe width='440' \
height='335' \
src='https://www.youtube.com/embed/%s' \
frameborder='0' \
allowfullscreen>%s</iframe>" path (or "" desc)))
((org-export-derived-backend-p backend 'latex)
(format "\\href{https://youtu.be/%s}{%s}" path (or desc "youtube")))
(t (format "https://youtu.be/%s" path)))))
#+END_SRC
*** Visuals
Here I try to do two things: improve the styling of the various documents, via
font changes etc, and also propagate colours from the current theme.
[[xkcd:1882]]
**** In editor
***** Font Display
Mixed pitch is great. As is ~+org-pretty-mode~, let's use them.
#+BEGIN_SRC emacs-lisp
(add-hook! 'org-mode-hook #'+org-pretty-mode #'mixed-pitch-mode)
#+END_SRC
2020-01-09 17:58:01 +00:00
Earlier I loaded the ~org-pretty-table~ package, let's enable it everywhere!
#+BEGIN_SRC emacs-lisp
(setq global-org-pretty-table-mode t)
#+END_SRC
2020-03-14 15:30:49 +00:00
Let's make headings a bit bigger
#+BEGIN_SRC emacs-lisp
(custom-set-faces!
2020-04-20 15:59:21 +00:00
'(outline-1 :weight extra-bold :height 1.25)
'(outline-2 :weight bold :height 1.15)
'(outline-3 :weight bold :height 1.12)
'(outline-4 :weight semi-bold :height 1.09)
'(outline-5 :weight semi-bold :height 1.06)
'(outline-6 :weight semi-bold :height 1.03)
2020-03-14 15:30:49 +00:00
'(outline-8 :weight semi-bold)
'(outline-9 :weight semi-bold))
#+END_SRC
***** Symbols
2020-01-09 17:58:01 +00:00
It's also nice to change the character used for collapsed items (by default ~…~),
I think ~▾~ is better for indicating 'collapsed section'.
and add an extra ~org-bullet~ to the default list of four.
I've also added some fun alternatives, just commented out.
#+BEGIN_SRC emacs-lisp
;; (after! org
;; (use-package org-pretty-tags
;; :config
;; (setq org-pretty-tags-surrogate-strings
;; `(("uni" . ,(all-the-icons-faicon "graduation-cap" :face 'all-the-icons-purple :v-adjust 0.01))
;; ("ucc" . ,(all-the-icons-material "computer" :face 'all-the-icons-silver :v-adjust 0.01))
;; ("assignment" . ,(all-the-icons-material "library_books" :face 'all-the-icons-orange :v-adjust 0.01))
;; ("test" . ,(all-the-icons-material "timer" :face 'all-the-icons-red :v-adjust 0.01))
;; ("lecture" . ,(all-the-icons-fileicon "keynote" :face 'all-the-icons-orange :v-adjust 0.01))
;; ("email" . ,(all-the-icons-faicon "envelope" :face 'all-the-icons-blue :v-adjust 0.01))
;; ("read" . ,(all-the-icons-octicon "book" :face 'all-the-icons-lblue :v-adjust 0.01))
;; ("article" . ,(all-the-icons-octicon "file-text" :face 'all-the-icons-yellow :v-adjust 0.01))
;; ("web" . ,(all-the-icons-faicon "globe" :face 'all-the-icons-green :v-adjust 0.01))
;; ("info" . ,(all-the-icons-faicon "info-circle" :face 'all-the-icons-blue :v-adjust 0.01))
;; ("issue" . ,(all-the-icons-faicon "bug" :face 'all-the-icons-red :v-adjust 0.01))
;; ("someday" . ,(all-the-icons-faicon "calendar-o" :face 'all-the-icons-cyan :v-adjust 0.01))
;; ("idea" . ,(all-the-icons-octicon "light-bulb" :face 'all-the-icons-yellow :v-adjust 0.01))
;; ("emacs" . ,(all-the-icons-fileicon "emacs" :face 'all-the-icons-lpurple :v-adjust 0.01))))
;; (org-pretty-tags-global-mode)))
(after! org-superstar
(setq org-superstar-headline-bullets-list '("◉" "○" "✸" "✿" "✤" "✜" "◆" "▶")
;; org-superstar-headline-bullets-list '("" "Ⅱ" "Ⅲ" "Ⅳ" "" "Ⅵ" "Ⅶ" "Ⅷ" "Ⅸ" "")
org-superstar-prettify-item-bullets t ))
(after! org
(setq org-ellipsis " ▾ "
org-priority-highest ?A
2020-04-12 05:50:29 +00:00
org-priority-lowest ?E
2020-05-08 06:40:36 +00:00
org-priority-faces
'((?A . 'all-the-icons-red)
(?B . 'all-the-icons-orange)
(?C . 'all-the-icons-yellow)
(?D . 'all-the-icons-green)
(?E . 'all-the-icons-blue))))
2020-01-09 17:58:01 +00:00
#+END_SRC
It's also nice to make use of the Unicode characters for check boxes, and other commands.
2020-01-09 17:58:01 +00:00
#+BEGIN_SRC emacs-lisp
(after! org
(appendq! +pretty-code-symbols
`(:checkbox "☐"
:pending "◼"
:checkedbox "☑"
:list_property "∷"
:results "🠶"
:property "☸"
:properties "⚙"
:end "∎"
:options "⌥"
:title "𝙏"
:author "𝘼"
:date "𝘿"
:latex_header "⇥"
2020-04-28 13:09:04 +00:00
:latex_class "🄲"
:begin_quote ""
:end_quote ""
:begin_export "⯮"
:end_export "⯬"
:priority_a ,(propertize "⚑" 'face 'all-the-icons-red)
:priority_b ,(propertize "⬆" 'face 'all-the-icons-orange)
:priority_c ,(propertize "■" 'face 'all-the-icons-yellow)
:priority_d ,(propertize "⬇" 'face 'all-the-icons-green)
:priority_e ,(propertize "❓" 'face 'all-the-icons-blue)
:em_dash "—"))
2020-01-09 17:58:01 +00:00
(set-pretty-symbols! 'org-mode
:merge t
:checkbox "[ ]"
:pending "[-]"
:checkedbox "[X]"
:list_property "::"
:results "#+RESULTS:"
:property "#+PROPERTY:"
:property ":PROPERTIES:"
:end ":END:"
:options "#+OPTIONS:"
:title "#+TITLE:"
:author "#+AUTHOR:"
:date "#+DATE:"
2020-04-28 13:09:04 +00:00
:latex_class "#+LATEX_CLASS:"
:latex_header "#+LATEX_HEADER:"
:begin_quote "#+BEGIN_QUOTE"
:end_quote "#+END_QUOTE"
:begin_export "#+BEGIN_EXPORT"
:end_export "#+END_EXPORT"
:priority_a "[#A]"
:priority_b "[#B]"
:priority_c "[#C]"
:priority_d "[#D]"
:priority_e "[#E]"
:em_dash "---"))
2020-01-09 17:58:01 +00:00
(plist-put +pretty-code-symbols :name "⁍") ; or could be good?
#+END_SRC
2020-02-16 08:13:17 +00:00
We also like ~org-fragtog~, and that wants a hook.
#+BEGIN_SRC emacs-lisp
(add-hook 'org-mode-hook 'org-fragtog-mode)
#+END_SRC
2020-02-03 05:01:57 +00:00
***** LaTeX Fragments
First off, we want those fragments to look good.
#+BEGIN_SRC emacs-lisp
(after! org
(setq org-highlight-latex-and-related '(native script entities)))
#+END_SRC
2020-02-03 05:01:57 +00:00
It's nice to customise the look of LaTeX fragments so they fit better in the
text --- like this \(\sqrt{\beta^2+3}-\sum_{\phi=1}^\infty \frac{x^\phi-1}{\Gamma(a)}\). Let's start by adding a sans font.
2020-02-03 05:01:57 +00:00
#+BEGIN_SRC emacs-lisp
(setq org-format-latex-header "\\documentclass{article}
\\usepackage[usenames]{color}
\\usepackage[T1]{fontenc}
\\usepackage{mathtools}
\\usepackage{textcomp,amssymb}
2020-02-26 11:05:41 +00:00
\\usepackage[makeroom]{cancel}
\\usepackage{booktabs}
2020-02-03 05:01:57 +00:00
\\pagestyle{empty} % do not remove
% The settings below are copied from fullpage.sty
\\setlength{\\textwidth}{\\paperwidth}
\\addtolength{\\textwidth}{-3cm}
\\setlength{\\oddsidemargin}{1.5cm}
\\addtolength{\\oddsidemargin}{-2.54cm}
\\setlength{\\evensidemargin}{\\oddsidemargin}
\\setlength{\\textheight}{\\paperheight}
\\addtolength{\\textheight}{-\\headheight}
\\addtolength{\\textheight}{-\\headsep}
\\addtolength{\\textheight}{-\\footskip}
\\addtolength{\\textheight}{-3cm}
\\setlength{\\topmargin}{1.5cm}
\\addtolength{\\topmargin}{-2.54cm}
% my custom stuff
2020-02-09 00:36:59 +00:00
\\usepackage{arev}
2020-02-03 05:01:57 +00:00
\\usepackage{arevmath}")
#+END_SRC
We can either render from a ~dvi~ or ~pdf~ file, so let's benchmark ~latex~ and
~pdflatex~.
| ~latex~ time | ~pdflatex~ time |
|------------+---------------|
| 135±2 ms | 215±3 ms |
On the rendering side, there are two ~.dvi~-to-image converters which I am
interested in: ~dvipng~ and ~dvisvgm~. Then with the a ~.pdf~ we have ~pdf2svg~.
For inline preview we care about speed, while for exporting we care about file
size and prefer a vector graphic.
Using the above latex expression and benchmarking lead to the following results:
| ~dvipng~ time | ~dvisvgm~ time | ~pdf2svg~ time |
|-------------+--------------+--------------|
| 89±2 ms | 178±2 ms | 12±2 ms |
Now let's combine this to see what's best
| Tool chain | Total time | Resultant file size |
|--------------------+------------+---------------------|
| ~latex~ + ~dvipng~ | 226±2 ms | 7 KiB |
| ~latex~ + ~dvisvgm~ | 392±4 ms | 8 KiB |
| ~pdflatex~ + ~pdf2svg~ | 230±2 ms | 16 KiB |
So, let's use ~dvipng~ for previewing LaTeX fragments in-Emacs, but ~dvisvgm~ for [[
2020-02-03 05:01:57 +00:00
Exporting to HTML][LaTeX Rendering]].
/Unfortunately: it seems that svg sizing is annoying ATM, so let's actually not do this right now./
2020-02-03 05:01:57 +00:00
As well as having a sans font, there are a few other tweaks which can make them
look better. Namely making sure that the colours switch when the theme does.
2020-02-03 05:01:57 +00:00
#+BEGIN_SRC emacs-lisp
(after! org
;; make background of fragments transparent
;; (let ((dvipng--plist (alist-get 'dvipng org-preview-latex-process-alist)))
;; (plist-put dvipng--plist :use-xcolor t)
;; (plist-put dvipng--plist :image-converter '("dvipng -D %D -bg 'transparent' -T tight -o %O %f")))
2020-02-09 15:14:21 +00:00
(add-hook! 'doom-load-theme-hook
(defun +org-refresh-latex-background ()
(plist-put! org-format-latex-options
:background
(face-attribute (or (cadr (assq 'default face-remapping-alist))
'default)
:background nil t))))
2020-02-03 05:01:57 +00:00
)
#+END_SRC
It'd be nice to make ~mhchem~ equations able to be rendered.
NB: This doesn't work at the moment.
#+BEGIN_SRC emacs-lisp
(after! org
(add-to-list 'org-latex-regexps '("\\ce" "^\\\\ce{\\(?:[^\000{}]\\|{[^\000}]+?}\\)}" 0 nil)))
#+END_SRC
***** Stolen from [[https://github.com/jkitchin/scimax][scimax]] (semi-working right now)
I want fragment justification
#+BEGIN_SRC emacs-lisp
(after! org
(defun scimax-org-latex-fragment-justify (justification)
"Justify the latex fragment at point with JUSTIFICATION.
JUSTIFICATION is a symbol for 'left, 'center or 'right."
(interactive
(list (intern-soft
(completing-read "Justification (left): " '(left center right)
nil t nil nil 'left))))
(let* ((ov (ov-at))
(beg (ov-beg ov))
(end (ov-end ov))
(shift (- beg (line-beginning-position)))
(img (overlay-get ov 'display))
(img (and (and img (consp img) (eq (car img) 'image)
(image-type-available-p (plist-get (cdr img) :type)))
img))
space-left offset)
(when (and img
;; This means the equation is at the start of the line
(= beg (line-beginning-position))
(or
(string= "" (s-trim (buffer-substring end (line-end-position))))
(eq 'latex-environment (car (org-element-context)))))
(setq space-left (- (window-max-chars-per-line) (car (image-size img)))
offset (floor (cond
((eq justification 'center)
(- (/ space-left 2) shift))
((eq justification 'right)
(- space-left shift))
(t
0))))
(when (>= offset 0)
(overlay-put ov 'before-string (make-string offset ?\ ))))))
(defun scimax-org-latex-fragment-justify-advice (beg end image imagetype)
"After advice function to justify fragments."
(scimax-org-latex-fragment-justify (or (plist-get org-format-latex-options :justify) 'left)))
(defun scimax-toggle-latex-fragment-justification ()
"Toggle if LaTeX fragment justification options can be used."
(interactive)
(if (not (get 'scimax-org-latex-fragment-justify-advice 'enabled))
(progn
(advice-add 'org--format-latex-make-overlay :after 'scimax-org-latex-fragment-justify-advice)
(put 'scimax-org-latex-fragment-justify-advice 'enabled t)
(message "Latex fragment justification enabled"))
(advice-remove 'org--format-latex-make-overlay 'scimax-org-latex-fragment-justify-advice)
(put 'scimax-org-latex-fragment-justify-advice 'enabled nil)
(message "Latex fragment justification disabled"))))
#+END_SRC
There's also this lovely equation numbering stuff I'll nick
#+BEGIN_SRC emacs-lisp
;; Numbered equations all have (1) as the number for fragments with vanilla
;; org-mode. This code injects the correct numbers into the previews so they
;; look good.
(after! org
(defun scimax-org-renumber-environment (orig-func &rest args)
"A function to inject numbers in LaTeX fragment previews."
(let ((results '())
(counter -1)
(numberp))
(setq results (loop for (begin . env) in
(org-element-map (org-element-parse-buffer) 'latex-environment
(lambda (env)
(cons
(org-element-property :begin env)
(org-element-property :value env))))
collect
(cond
((and (string-match "\\\\begin{equation}" env)
(not (string-match "\\\\tag{" env)))
(incf counter)
(cons begin counter))
((string-match "\\\\begin{align}" env)
(prog2
(incf counter)
(cons begin counter)
(with-temp-buffer
(insert env)
(goto-char (point-min))
;; \\ is used for a new line. Each one leads to a number
(incf counter (count-matches "\\\\$"))
;; unless there are nonumbers.
(goto-char (point-min))
(decf counter (count-matches "\\nonumber")))))
(t
(cons begin nil)))))
(when (setq numberp (cdr (assoc (point) results)))
(setf (car args)
(concat
(format "\\setcounter{equation}{%s}\n" numberp)
(car args)))))
(apply orig-func args))
(defun scimax-toggle-latex-equation-numbering ()
"Toggle whether LaTeX fragments are numbered."
(interactive)
(if (not (get 'scimax-org-renumber-environment 'enabled))
(progn
(advice-add 'org-create-formula-image :around #'scimax-org-renumber-environment)
(put 'scimax-org-renumber-environment 'enabled t)
(message "Latex numbering enabled"))
(advice-remove 'org-create-formula-image #'scimax-org-renumber-environment)
(put 'scimax-org-renumber-environment 'enabled nil)
(message "Latex numbering disabled.")))
(advice-add 'org-create-formula-image :around #'scimax-org-renumber-environment)
(put 'scimax-org-renumber-environment 'enabled t))
#+END_SRC
**** Exporting (general)
#+BEGIN_SRC emacs-lisp
(after! org (setq org-export-headline-levels 5)) ; I like nesting
#+END_SRC
I'm also going to make use of an item in =ox-extra= so that I can add an =:ignore:=
tag to headings for the content to be kept, but the heading itself ignored
(unlike =:noexport:= which ignored both heading and content). This is useful when
I want to use headings to provide a structure for writing that doesn't appear in
the final documents.
#+BEGIN_SRC emacs-lisp
(after! org
(require 'ox-extra)
(ox-extras-activate '(ignore-headlines)))
#+END_SRC
**** Exporting to HTML
***** Custom CSS/JS
There is a fantastic exporter config ([[https://github.com/fniessen/org-html-themes][fniessen/org-html-themes]]) which we can
setup to be used with all our org files. Since most of the syntax highlighting
colours from our [[Theme]] gets used, we benefit from customising the code block style.
#+NAME: orgHtmlStyle
#+BEGIN_SRC web :exports none :tangle no
<link rel='stylesheet' type='text/css' href='https://fniessen.github.io/org-html-themes/styles/readtheorg/css/htmlize.css'/>
<link rel='stylesheet' type='text/css' href='https://fniessen.github.io/org-html-themes/styles/readtheorg/css/readtheorg.css'/>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script>
<script type='text/javascript' src='https://fniessen.github.io/org-html-themes/styles/lib/js/jquery.stickytableheaders.min.js'></script>
<script type='text/javascript' src='https://fniessen.github.io/org-html-themes/styles/readtheorg/js/readtheorg.js'></script>
<style>
pre.src {
background-color: var(--theme-bg);
color: var(--theme-fg);
scrollbar-color:#bbb6#9992;
scrollbar-width: thin;
margin: 0;
border: none;
}
div.org-src-container {
border-radius: 12px;
overflow: hidden;
margin-bottom: 24px;
margin-top: 1px;
border: 1px solid#e1e4e5;
}
pre.src::before {
background-color:#6666;
top: 8px;
border: none;
border-radius: 5px;
line-height: 1;
border: 2px solid var(--theme-bg);
opacity: 0;
transition: opacity 200ms;
}
pre.src:hover::before { opacity: 1; }
pre.src:active::before { opacity: 0; }
pre.example {
border-radius: 12px;
background: var(--theme-bg-alt);
color: var(--theme-fg);
}
code {
border-radius: 5px;
background:#e8e8e8;
font-size: 80%;
}
kbd {
display: inline-block;
padding: 3px 5px;
font: 80% SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;
line-height: normal;
line-height: 10px;
color:#444d56;
vertical-align: middle;
background-color:#fafbfc;
border: 1px solid#d1d5da;
border-radius: 3px;
box-shadow: inset 0 -1px 0#d1d5da;
}
table {
max-width: 100%;
overflow-x: auto;
display: block;
border-top: none;
}
a {
text-decoration: none;
background-image: linear-gradient(#d8dce9, #d8dce9);
background-position: 0% 100%;
background-repeat: no-repeat;
background-size: 0% 2px;
transition: background-size .3s;
}
\#table-of-contents a {
background-image: none;
}
a:hover, a:focus {
background-size: 100% 2px;
}
a[href^='#'] { font-variant-numeric: oldstyle-nums; }
a[href^='#']:visited { color:#3091d1; }
li .checkbox {
display: inline-block;
width: 0.9em;
height: 0.9em;
border-radius: 3px;
margin: 3px;
top: 4px;
position: relative;
}
li.on > .checkbox { background: var(--theme-green); box-shadow: 0 0 2px var(--theme-green); }
li.trans > .checkbox { background: var(--theme-orange); box-shadow: 0 0 2px var(--theme-orange); }
li.off > .checkbox { background: var(--theme-red); box-shadow: 0 0 2px var(--theme-red); }
li.on > .checkbox::after {
content: '';
height: 0.45em;
width: 0.225em;
-webkit-transform-origin: left top;
transform-origin: left top;
transform: scaleX(-1) rotate(135deg);
border-right: 2.8px solid#fff;
border-top: 2.8px solid#fff;
opacity: 0.9;
left: 0.10em;
top: 0.45em;
position: absolute;
}
li.trans > .checkbox::after {
content: '';
font-weight: bold;
font-size: 1.6em;
position: absolute;
top: 0.23em;
left: 0.09em;
width: 0.35em;
height: 0.12em;
background:#fff;
opacity: 0.9;
border-radius: 0.1em;
}
li.off > .checkbox::after {
content: '✖';
color:#fff;
opacity: 0.9;
position: relative;
top: -0.40rem;
left: 0.17em;
font-size: 0.75em;
}
span.timestamp {
color: #003280;
background: #647CFF44;
border-radius: 3px;
line-height: 1.25;
}
\#content img {
border-radius: 3px;
}
\#table-of-contents { overflow-y: auto; }
blockquote p { margin: 8px 0px 16px 0px; }
\#postamble .date { color: var(--theme-green); }
::-webkit-scrollbar { width: 10px; height: 8px; }
::-webkit-scrollbar-track { background:#9992; }
::-webkit-scrollbar-thumb { background:#ccc; border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background:#888; }
</style>
#+END_SRC
#+NAME: orgHtmlScript
We also want to make the background and foreground colours of the ~<pre>~ blocks
match out theme (they don't by default), so I scraped some code from ~emacs.stackexchange~.
#+BEGIN_SRC emacs-lisp :noweb yes
(defun my-org-inline-css-hook (exporter)
"Insert custom inline css to automatically set the
background of code to whatever theme I'm using's background"
(when (eq exporter 'html)
(setq
org-html-head-extra
(concat
(if (s-contains-p "<!tec/custom-head-start-->" org-html-head-extra)
(s-replace-regexp "<!tec\\/custom-head-start-->[^🙜]*<!tec\\/custom-head-end-->" "" org-html-head-extra)
org-html-head-extra)
(format "<!tec/custom-head-start-->
<style type=\"text/css\">
:root {
--theme-bg: %s;
--theme-bg-alt: %s;
--theme-base0: %s;
--theme-base1: %s;
--theme-base2: %s;
--theme-base3: %s;
--theme-base4: %s;
--theme-base5: %s;
--theme-base6: %s;
--theme-base7: %s;
--theme-base8: %s;
--theme-fg: %s;
--theme-fg-alt: %s;
--theme-grey: %s;
--theme-red: %s;
--theme-orange: %s;
--theme-green: %s;
--theme-teal: %s;
--theme-yellow: %s;
--theme-blue: %s;
--theme-dark-blue: %s;
--theme-magenta: %s;
--theme-violet: %s;
--theme-cyan: %s;
--theme-dark-cyan: %s;
}
</style>"
(doom-color 'bg)
(doom-color 'bg-alt)
(doom-color 'base0)
(doom-color 'base1)
(doom-color 'base2)
(doom-color 'base3)
(doom-color 'base4)
(doom-color 'base5)
(doom-color 'base6)
(doom-color 'base7)
(doom-color 'base8)
(doom-color 'fg)
(doom-color 'fg-alt)
(doom-color 'grey)
(doom-color 'red)
(doom-color 'orange)
(doom-color 'green)
(doom-color 'teal)
(doom-color 'yellow)
(doom-color 'blue)
(doom-color 'dark-blue)
(doom-color 'magenta)
(doom-color 'violet)
(doom-color 'cyan)
(doom-color 'dark-cyan))
"
<<orgHtmlStyle>>
<!tec/custom-head-end-->
"
))))
(add-hook 'org-export-before-processing-hook 'my-org-inline-css-hook)
#+END_SRC
***** Make verbatim different to code
Since we have =verbatim= and ~code~, let's use =verbatim= for key strokes.
#+BEGIN_SRC emacs-lisp
(setq org-html-text-markup-alist
'((bold . "<b>%s</b>")
(code . "<code>%s</code>")
(italic . "<i>%s</i>")
(strike-through . "<del>%s</del>")
(underline . "<span class=\"underline\">%s</span>")
(verbatim . "<kbd>%s</kbd>")))
#+END_SRC
***** Change checkbox type
We also want to use HTML checkboxes, however we want to get a bit fancier than default
#+BEGIN_SRC emacs-lisp
(after! org
(appendq! org-html-checkbox-types '((html-span .
((on . "<span class='checkbox'></span>")
(off . "<span class='checkbox'></span>")
(trans . "<span class='checkbox'></span>")))))
(setq org-html-checkbox-type 'html-span))
#+END_SRC
- [ ] I'm yet to do this
- [-] Work in progress
- [X] This is done
2020-02-03 05:01:57 +00:00
***** LaTeX Rendering
On the maths side of things, I consider ~dvisvgm~ to be a rather compelling
option. However this isn't sized very well at the moment.
#+BEGIN_SRC emacs-lisp
;; (setq-default org-html-with-latex `dvisvgm)
#+END_SRC
**** Exporting to LaTeX
I like automatically using spaced small caps for acronyms. For strings I want to
be unaffected lest's use ~;~ as a prefix to prevent the transformation --- i.e.
~;JFK~ (as one would want for two-letter geographic locations and names).
#+BEGIN_SRC emacs-lisp
;; TODO make this /only/ apply to text (i.e. not URL)
(after! org
(defun tec/org-export-latex-filter-acronym (text backend info)
(when (org-export-derived-backend-p backend 'latex)
(let ((case-fold-search nil))
(replace-regexp-in-string
"[;\\\\]?\\b[A-Z][A-Z]+s?"
(lambda (all-caps-str)
; only \acr if str doesn't start with ";" or "\" (for LaTeX commands)
(cond ((equal (aref all-caps-str 0) ?\;) (substring all-caps-str 1))
((equal (aref all-caps-str 0) ?\\) all-caps-str)
((equal (aref all-caps-str (- (length all-caps-str) 1)) ?s)
(concat "\\textls*[70]{\\textsc{"
(s-downcase (substring all-caps-str 0 -1))
"}\\protect\\scalebox{.91}[.84]{s}}"))
(t (concat "\\textls*[70]{\\textsc{"
(s-downcase all-caps-str) "}}"))))
text t t))))
(add-to-list 'org-export-filter-plain-text-functions
'tec/org-export-latex-filter-acronym)
(add-to-list 'org-export-filter-headline-functions
'tec/org-export-latex-filter-acronym))
#+END_SRC
Now for a few more adjustments.
#+BEGIN_SRC emacs-lisp
2020-03-23 03:01:56 +00:00
(after! ox-latex
(add-to-list 'org-latex-classes
'("fancy-article"
2020-03-23 03:01:56 +00:00
"\\documentclass{scrartcl}\n\
\\usepackage[T1]{fontenc}\n\
\\usepackage[osf,largesc,helvratio=0.9]{newpxtext}\n\
\\usepackage[scale=0.92]{sourcecodepro}\n\
\\usepackage[varbb]{newpxmath}\n\
\\usepackage[activate={true,nocompatibility},final,tracking=true,kerning=true,spacing=true,factor=2000]{microtype}\n\
\\usepackage{xcolor}\n\
\\usepackage{booktabs}
\\usepackage{subcaption}
\\usepackage[hypcap=true]{caption}
\\setkomafont{caption}{\\sffamily\\small}
\\setkomafont{captionlabel}{\\upshape\\bfseries}
\\captionsetup{justification=raggedright,singlelinecheck=true}
\\setcapindent{0pt}
2020-03-23 03:01:56 +00:00
\\setlength{\\parskip}{\\baselineskip}\n\
\\setlength{\\parindent}{0pt}"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
(add-to-list 'org-latex-classes
'("blank"
"[NO-DEFAULT-PACKAGES]
[NO-PACKAGES]
[EXTRA]"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2020-02-29 11:09:06 +00:00
(add-to-list 'org-latex-classes
2020-02-26 11:05:41 +00:00
'("bmc-article"
"\\documentclass[article,code,maths]{bmc}
[NO-DEFAULT-PACKAGES]
[NO-PACKAGES]
[EXTRA]"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2020-02-29 11:09:06 +00:00
(add-to-list 'org-latex-classes
2020-02-26 11:05:41 +00:00
'("bmc"
"\\documentclass[code,maths]{bmc}
[NO-DEFAULT-PACKAGES]
[NO-PACKAGES]
[EXTRA]"
("\\chapter{%s}" . "\\chapter*{%s}")
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
2020-03-23 03:01:56 +00:00
(setq org-latex-default-class "fancy-article")
2020-02-29 11:09:06 +00:00
(add-to-list 'org-latex-packages-alist '("" "minted"))
2020-04-20 08:00:48 +00:00
(setq org-latex-listings 'minted
org-latex-minted-options
2020-03-01 13:22:15 +00:00
'(("frame" "lines")
("fontsize" "\\scriptsize")
("linenos" "")
("breakanywhere" "true")
("breakautoindent" "true")
("breaklines" "true")
("autogobble" "true")
("obeytabs" "true")
("python3" "true")
("breakbefore" "\\\\\\.+")
("breakafter" "\\,")
("style" "autumn")
("breaksymbol" "\\tiny\\ensuremath{\\hookrightarrow}")
("breakanywheresymbolpre" "\\,\\footnotesize\\ensuremath{{}_{\\rfloor}}")
("breakbeforesymbolpre" "\\,\\footnotesize\\ensuremath{{}_{\\rfloor}}")
("breakaftersymbolpre" "\\,\\footnotesize\\ensuremath{{}_{\\rfloor}}")))
(setq org-latex-tables-booktabs t)
2020-03-01 13:22:15 +00:00
(setq org-latex-hyperref-template "
2020-05-14 19:13:12 +00:00
\\colorlet{greenyblue}{blue!70!green}
\\colorlet{blueygreen}{blue!40!green}
\\providecolor{link}{named}{greenyblue}
\\providecolor{cite}{named}{blueygreen}
\\hypersetup{
2020-03-23 03:01:56 +00:00
pdfauthor={%a},
pdftitle={%t},
pdfkeywords={%k},
pdfsubject={%d},
pdfcreator={%c},
pdflang={%L},
breaklinks=true,
colorlinks=true,
linkcolor=,
urlcolor=link,
citecolor=cite\n}
2020-03-23 03:01:56 +00:00
\\urlstyle{same}\n")
2020-02-29 11:09:06 +00:00
(setq org-latex-pdf-process
'("latexmk -shell-escape -interaction=nonstopmode -f -pdf -output-directory=%o %f")))
#+END_SRC
***** Chameleon --- aka. match theme
Once the idea of having the look of the LaTeX document produced match the
current Emacs theme, I was enraptured. The result is the pseudo-class ~chameleon~.
#+BEGIN_SRC emacs-lisp
(after! ox
(defvar ox-chameleon-base-class "fancy-article"
"The base class that chameleon builds on")
(defvar ox-chameleon--p nil
"Used to indicate whether the current export is trying to blend in. Set just before being accessed.")
;; (setf (alist-get :filter-latex-class
;; (org-export-backend-filters
;; (org-export-get-backend 'latex)))
;; 'ox-chameleon-latex-class-detector-filter)
;; (defun ox-chameleon-latex-class-detector-filter (info backend)
;; ""
;; (setq ox-chameleon--p (when (equal (plist-get info :latex-class)
;; "chameleon")
;; (plist-put info :latex-class ox-chameleon-base-class)
;; t)))
;; TODO make this less hacky. One ideas was as follows
;; (map-put (org-export-backend-filters (org-export-get-backend 'latex))
;; :filter-latex-class 'ox-chameleon-latex-class-detector-filter))
;; Never seemed to execute though
(defadvice! ox-chameleon-org-latex-detect (orig-fun info)
:around #'org-export-install-filters
(setq ox-chameleon--p (when (equal (plist-get info :latex-class)
"chameleon")
(plist-put info :latex-class ox-chameleon-base-class)
t))
(funcall orig-fun info))
(defadvice! ox-chameleon-org-latex-export (orig-fn info &optional template snippet?)
:around #'org-latex-make-preamble
(funcall orig-fn info)
(if (not ox-chameleon--p)
(funcall orig-fn info template snippet?)
(concat (funcall orig-fn info template snippet?)
(ox-chameleon-generate-colourings))))
(defun ox-chameleon-generate-colourings ()
(apply #'format
"%% make document follow Emacs theme
\\definecolor{bg}{HTML}{%s}
\\definecolor{fg}{HTML}{%s}
\\definecolor{red}{HTML}{%s}
\\definecolor{orange}{HTML}{%s}
\\definecolor{green}{HTML}{%s}
\\definecolor{teal}{HTML}{%s}
\\definecolor{yellow}{HTML}{%s}
\\definecolor{blue}{HTML}{%s}
\\definecolor{dark-blue}{HTML}{%s}
\\definecolor{magenta}{HTML}{%s}
\\definecolor{violet}{HTML}{%s}
\\definecolor{cyan}{HTML}{%s}
\\definecolor{dark-cyan}{HTML}{%s}
\\definecolor{level1}{HTML}{%s}
\\definecolor{level2}{HTML}{%s}
\\definecolor{level3}{HTML}{%s}
\\definecolor{level4}{HTML}{%s}
\\definecolor{level5}{HTML}{%s}
\\definecolor{level6}{HTML}{%s}
\\definecolor{level7}{HTML}{%s}
\\definecolor{level8}{HTML}{%s}
\\definecolor{link}{HTML}{%s}
\\definecolor{cite}{HTML}{%s}
\\definecolor{itemlabel}{HTML}{%s}
\\definecolor{code}{HTML}{%s}
\\definecolor{verbatim}{HTML}{%s}
\\pagecolor{bg}
\\color{fg}
\\addtokomafont{section}{\\color{level1}}
\\newkomafont{sectionprefix}{\\color{level1}}
\\addtokomafont{subsection}{\\color{level2}}
\\newkomafont{subsectionprefix}{\\color{level2}}
\\addtokomafont{subsubsection}{\\color{level3}}
\\newkomafont{subsubsectionprefix}{\\color{level3}}
\\addtokomafont{paragraph}{\\color{level4}}
\\newkomafont{paragraphprefix}{\\color{level4}}
\\addtokomafont{subparagraph}{\\color{level5}}
\\newkomafont{subparagraphprefix}{\\color{level5}}
\\renewcommand{\\labelitemi}{\\textcolor{itemlabel}{\\textbullet}}
\\renewcommand{\\labelitemii}{\\textcolor{itemlabel}{\\normalfont\\bfseries \\textendash}}
\\renewcommand{\\labelitemiii}{\\textcolor{itemlabel}{\\textasteriskcentered}}
\\renewcommand{\\labelitemiv}{\\textcolor{itemlabel}{\\textperiodcentered}}
\\renewcommand{\\labelenumi}{\\textcolor{itemlabel}{\\theenumi.}}
\\renewcommand{\\labelenumii}{\\textcolor{itemlabel}{(\\theenumii)}}
\\renewcommand{\\labelenumiii}{\\textcolor{itemlabel}{\\theenumiii.}}
\\renewcommand{\\labelenumiv}{\\textcolor{itemlabel}{\\theenumiv.}}
\\DeclareTextFontCommand{\\texttt}{\\color{code}\\ttfamily}
\\makeatletter
\\def\\verbatim@font{\\color{verbatim}\\normalfont\\ttfamily}
\\makeatother
%% end customisations
"
(mapcar (doom-rpartial #'substring 1)
(list
(face-attribute 'solaire-default-face :background)
(face-attribute 'default :foreground)
;;
(doom-color 'red)
(doom-color 'orange)
(doom-color 'green)
(doom-color 'teal)
(doom-color 'yellow)
(doom-color 'blue)
(doom-color 'dark-blue)
(doom-color 'magenta)
(doom-color 'violet)
(doom-color 'cyan)
(doom-color 'dark-cyan)
;;
(face-attribute 'outline-1 :foreground)
(face-attribute 'outline-2 :foreground)
(face-attribute 'outline-3 :foreground)
(face-attribute 'outline-4 :foreground)
(face-attribute 'outline-5 :foreground)
(face-attribute 'outline-6 :foreground)
(face-attribute 'outline-7 :foreground)
(face-attribute 'outline-8 :foreground)
;;
(face-attribute 'link :foreground)
(or (face-attribute 'org-ref-cite-face :foreground) (doom-color 'yellow))
(face-attribute 'org-list-dt :foreground)
(face-attribute 'org-code :foreground)
(face-attribute 'org-verbatim :foreground)
))))
)
#+END_SRC
***** Make verbatim different to code
Since have just gone to so much effort above let's make the most of it by making
=verbatim= use ~verb~ instead of ~protectedtexttt~ (default).
#+BEGIN_SRC emacs-lisp
(setq org-latex-text-markup-alist '((bold . "\\textbf{%s}")
(code . protectedtexttt)
(italic . "\\emph{%s}")
(strike-through . "\\sout{%s}")
(underline . "\\uline{%s}")
(verbatim . verb)))
#+END_SRC
2020-01-20 18:15:09 +00:00
**** Exporting to Beamer
It's nice to use a different theme
#+BEGIN_SRC emacs-lisp
(setq org-beamer-theme "[progressbar=foot]metropolis")
#+END_SRC
Then customise it a bit
#+BEGIN_SRC emacs-lisp
#+END_SRC
And I think that it's natural to divide a presentation into sections, e.g.
Introduction, Overview... so let's set bump up the headline level that becomes a
frame from ~1~ to ~2~.
#+BEGIN_SRC emacs-lisp
(setq org-beamer-frame-level 2)
2020-01-20 18:17:20 +00:00
#+END_SRC
**** Exporting to GFM
We just need to load ~ox-gfm~ for org-mode documents
#+BEGIN_SRC emacs-lisp
(eval-after-load "org"
'(require 'ox-gfm nil t))
#+END_SRC
2020-01-09 18:02:54 +00:00
*** Babel
2020-02-09 03:06:01 +00:00
Doom lazy-loads babel languages, with is lovely.
We need to tell babel to use python3. Who uses python2 anymore anyway? And why
2020-01-20 18:17:00 +00:00
doesn't ~python~ refer to the latest version!?
#+BEGIN_SRC emacs-lisp
(setq org-babel-python-command "python3")
#+END_SRC
We also like auto-completion here
#+BEGIN_SRC emacs-lisp
(defun tec-org-python ()
(if (eq major-mode 'python-mode)
(progn (anaconda-mode t)
(company-mode t)))
)
(add-hook 'org-src-mode-hook 'tec-org-python)
#+END_SRC
2020-01-09 18:03:18 +00:00
*** ESS
We don't want ~R~ evaluation to hang the editor, hence
#+BEGIN_SRC emacs-lisp
(setq ess-eval-visibly 'nowait)
#+END_SRC
2020-01-09 18:03:42 +00:00
Syntax highlighting is nice, so let's turn all of that on
#+BEGIN_SRC emacs-lisp
(setq ess-R-font-lock-keywords '((ess-R-fl-keyword:keywords . t)
(ess-R-fl-keyword:constants . t)
(ess-R-fl-keyword:modifiers . t)
(ess-R-fl-keyword:fun-defs . t)
(ess-R-fl-keyword:assign-ops . t)
(ess-R-fl-keyword:%op% . t)
(ess-fl-keyword:fun-calls . t)
(ess-fl-keyword:numbers . t)
(ess-fl-keyword:operators . t)
(ess-fl-keyword:delimiters . t)
(ess-fl-keyword:= . t)
(ess-R-fl-keyword:F&T . t)))
#+END_SRC
** LaTeX
[[xkcd:1301]]
2020-03-23 03:12:19 +00:00
*** To-be-implemented ideas
- Paste image from clipboard
+ Determine first folder in ~graphicspath~ if applicable
+ Ask for file name
+ Use ~xclip~ to save file to graphics folder, or current directory (whichever applies)
2020-04-29 10:33:15 +00:00
#+BEGIN_SRC shell :eval no :tangle no
2020-03-23 03:12:19 +00:00
command -v xclip >/dev/null 2>&1 || { echo >&1 "no xclip"; exit 1; }
if
xclip -selection clipboard -target image/png -o >/dev/null 2>&1
then
xclip -selection clipboard -target image/png -o >$1 2>/dev/null
echo $1
else
echo "no image"
fi
#+END_SRC
+ Insert figure, with filled in details as a result (activate =yasnippet= with
filename as variable maybe?)
2020-04-09 18:06:28 +00:00
*** Compilation
#+BEGIN_SRC emacs-lisp
(setq TeX-save-query nil
TeX-show-compilation t
TeX-command-extra-options "-shell-escape")
(after! latex
(add-to-list 'TeX-command-list '("XeLaTeX" "%`xelatex%(mode)%' %t" TeX-run-TeX nil t)))
#+END_SRC
*** Snippet helpers
**** Template
For use in the new-file template, let's set out a nice preamble we may want to use.
#+NAME: latex-nice-preable
#+BEGIN_SRC latex :tangle no
\\usepackage[pdfa,unicode=true,hidelinks]{hyperref}
\\usepackage[dvipsnames,svgnames,table,hyperref]{xcolor}
\\renewcommand{\\UrlFont}{\\ttfamily\\small}
\\usepackage[a-2b]{pdfx} % why not be archival
\\usepackage[T1]{fontenc}
\\usepackage[osf,helvratio=0.9]{newpxtext} % pallatino
\\usepackage[scale=0.92]{sourcecodepro}
\\usepackage[varbb]{newpxmath}
\\usepackage{mathtools}
\\usepackage{amssymb}
\\usepackage[activate={true,nocompatibility},final,tracking=true,kerning=true,spacing=true,factor=2000]{microtype}
% microtype makes text look nicer
\\usepackage{graphicx} % include graphics
\\usepackage{grffile} % fix allowed graphicx filenames
\\usepackage{booktabs} % nice table rules
#+END_SRC
Then let's bind the content to a function, and define some nice helpers.
#+BEGIN_SRC emacs-lisp :noweb yes
(setq tec/yas-latex-template-preamble "
<<latex-nice-preable>>
")
(defun tec/yas-latex-get-class-choice ()
"Prompt user for LaTeX class choice"
(setq tec/yas-latex-class-choice (ivy-read "Select document class: " '("article" "scrartcl" "bmc") :def "bmc")))
(defun tec/yas-latex-preamble-if ()
"Based on class choice prompt for insertion of default preamble"
(if (equal tec/yas-latex-class-choice "bmc") 'nil
(eq (read-char-choice "Include default preamble? [Type y/n]" '(?y ?n)) ?y)))
#+END_SRC
**** Deliminators
#+BEGIN_SRC emacs-lisp
(after! tex
(defvar tec/tex-last-delim-char nil
"Last open delim expanded in a tex document")
(defvar tec/tex-delim-dot-second t
"When the `tec/tex-last-delim-char' is . a second charachter (this) is prompted for")
(defun tec/get-open-delim-char ()
"Exclusivly read next char to tec/tex-last-delim-char"
(setq tec/tex-delim-dot-second nil)
(setq tec/tex-last-delim-char (read-char-exclusive "Opening deliminator, recognises: 9 ( [ { < | ."))
(when (eql ?. tec/tex-last-delim-char)
(setq tec/tex-delim-dot-second (read-char-exclusive "Other deliminator, recognises: 0 9 ( ) [ ] { } < > |"))))
(defun tec/tex-open-delim-from-char (&optional open-char)
"Find the associated opening delim as string"
(unless open-char (setq open-char (if (eql ?. tec/tex-last-delim-char)
tec/tex-delim-dot-second
tec/tex-last-delim-char)))
(case open-char
(?\( "(")
(?9 "(")
(?\[ "[")
(?\{ "\\{")
(?< "<")
(?| (if tec/tex-delim-dot-second "." "|"))
(t ".")))
(defun tec/tex-close-delim-from-char (&optional open-char)
"Find the associated closing delim as string"
(if tec/tex-delim-dot-second
(case tec/tex-delim-dot-second
(?\) ")")
(?0 ")")
(?\] "]")
(?\} "\\}")
(?\> ">")
(?| "|")
(t "."))
(case (or open-char tec/tex-last-delim-char)
(?\( ")")
(?9 ")")
(?\[ "]")
(?\{ "\\}")
(?< ")")
(?\) ")")
(?0 ")")
(?\] "]")
(?\} "\\}")
(?\> ">")
(?| "|")
(t "."))))
(defun tec/tex-next-char-smart-close-delim (&optional open-char)
(and (bound-and-true-p smartparens-mode)
(eql (char-after) (case (or open-char tec/tex-last-delim-char)
(?\( ?\))
(?\[ ?\])
(?{ ?})
(?< ?>)))))
(defun tec/tex-delim-yas-expand (&optional open-char)
(yas-expand-snippet (yas-lookup-snippet "_deliminators" 'latex-mode) (point) (+ (point) (if (tec/tex-next-char-smart-close-delim open-char) 2 1)))))
#+END_SRC
2020-03-14 16:26:06 +00:00
*** Editor visuals
2020-03-23 03:06:55 +00:00
Once again, /all hail mixed pitch mode!/
#+BEGIN_SRC emacs-lisp
(add-hook 'LaTeX-mode-hook #'mixed-pitch-mode)
#+END_SRC
2020-03-14 16:26:06 +00:00
Let's enhance ~TeX-fold-math~ a bit
#+BEGIN_SRC emacs-lisp
2020-04-09 18:28:04 +00:00
(after! latex
(setcar (assoc "⋆" LaTeX-fold-math-spec-list) "★")) ;; make \star bigger
2020-03-14 16:26:06 +00:00
(setq TeX-fold-math-spec-list
2020-04-09 18:06:28 +00:00
`(;; missing/better symbols
2020-03-14 16:26:06 +00:00
("≤" ("le"))
("≥" ("ge"))
("≠" ("ne"))
;; conviniance shorts -- these don't work nicely ATM
;; ("" ("left"))
;; ("" ("right"))
2020-03-14 16:26:06 +00:00
;; private macros
("" ("RR"))
("" ("NN"))
("" ("ZZ"))
("" ("QQ"))
("" ("CC"))
("" ("PP"))
("" ("HH"))
("𝔼" ("EE"))
("𝑑" ("dd"))
2020-03-16 13:28:37 +00:00
;; known commands
2020-03-14 16:26:06 +00:00
("" ("phantom"))
2020-04-14 15:23:36 +00:00
(,(lambda (num den) (if (and (TeX-string-single-token-p num) (TeX-string-single-token-p den))
(concat num "" den)
(concat "❪" num "" den "❫"))) ("frac"))
2020-04-09 18:06:28 +00:00
(,(lambda (arg) (concat "√" (TeX-fold-parenthesize-as-neccesary arg))) ("sqrt"))
(,(lambda (arg) (concat "⭡" (TeX-fold-parenthesize-as-neccesary arg))) ("vec"))
2020-03-14 16:26:06 +00:00
("{1}" ("text"))
2020-03-16 13:28:37 +00:00
;; private commands
2020-03-14 16:26:06 +00:00
("|{1}|" ("abs"))
("‖{1}‖" ("norm"))
("⌊{1}⌋" ("floor"))
("⌈{1}⌉" ("ceil"))
("⌊{1}⌉" ("round"))
2020-03-30 05:43:51 +00:00
("𝑑{1}/𝑑{2}" ("dv"))
("∂{1}/∂{2}" ("pdv"))
;; fancification
("{1}" ("mathrm"))
2020-04-09 18:06:28 +00:00
(,(lambda (word) (string-offset-roman-chars 119743 word)) ("mathbf"))
(,(lambda (word) (string-offset-roman-chars 119951 word)) ("mathcal"))
(,(lambda (word) (string-offset-roman-chars 120003 word)) ("mathfrak"))
(,(lambda (word) (string-offset-roman-chars 120055 word)) ("mathbb"))
(,(lambda (word) (string-offset-roman-chars 120159 word)) ("mathsf"))
(,(lambda (word) (string-offset-roman-chars 120367 word)) ("mathtt"))
2020-03-16 13:28:37 +00:00
)
TeX-fold-macro-spec-list
'(
;; as the defaults
("[f]" ("footnote" "marginpar"))
("[c]" ("cite"))
("[l]" ("label"))
("[r]" ("ref" "pageref" "eqref"))
("[i]" ("index" "glossary"))
("..." ("dots"))
("{1}" ("emph" "textit" "textsl" "textmd" "textrm" "textsf" "texttt"
"textbf" "textsc" "textup"))
;; tweaked defaults
("©" ("copyright"))
("®" ("textregistered"))
("™" ("texttrademark"))
("[1]:||►" ("item"))
("❡❡ {1}" ("part" "part*"))
("❡ {1}" ("chapter" "chapter*"))
("§ {1}" ("section" "section*"))
("§§ {1}" ("subsection" "subsection*"))
("§§§ {1}" ("subsubsection" "subsubsection*"))
("¶ {1}" ("paragraph" "paragraph*"))
("¶¶ {1}" ("subparagraph" "subparagraph*"))
;; extra
("⬖ {1}" ("begin"))
("⬗ {1}" ("end"))
2020-03-14 16:26:06 +00:00
))
2020-03-30 05:43:51 +00:00
(defun string-offset-roman-chars (offset word)
"Shift the codepoint of each charachter in WORD by OFFSET with an extra -6 shift if the letter is lowercase"
(apply 'string
(mapcar (lambda (c) (+ (if (>= c 97) (- c 6) c) offset)) word)))
2020-04-09 18:06:28 +00:00
(defun TeX-fold-parenthesize-as-neccesary (tokens &optional suppress-left suppress-right)
"Add ❪ ❫ parenthesis as if multiple LaTeX tokens appear to be present"
2020-04-14 15:23:36 +00:00
(if (TeX-string-single-token-p tokens) tokens
2020-04-09 18:06:28 +00:00
(concat (if suppress-left "" "❪")
tokens
(if suppress-right "" "❫"))))
2020-04-14 15:23:36 +00:00
(defun TeX-string-single-token-p (teststring)
"Return t if TESTSTRING appears to be a single token, nil otherwise"
(if (string-match-p "^\\\\?\\w+$" teststring) t nil))
2020-03-14 16:26:06 +00:00
#+END_SRC
2020-03-15 16:19:17 +00:00
Some local keybindings to make life a bit easier
#+BEGIN_SRC emacs-lisp
(after! tex
(map!
:map LaTeX-mode-map
:ei [C-return] #'LaTeX-insert-item
;; normal stuff here
:localleader
:desc "View" "v" #'TeX-view)
2020-03-15 16:19:17 +00:00
(setq TeX-electric-math '("\\(" . "")))
#+END_SRC
2020-03-14 16:26:06 +00:00
Maths deliminators can be de-emphasised a bit
#+BEGIN_SRC emacs-lisp
;; Making \( \) less visible
(defface unimportant-latex-face
'((t
2020-03-15 16:19:17 +00:00
:inherit font-lock-comment-face :family "Overpass" :weight light))
2020-03-14 16:26:06 +00:00
"Face used to make \\(\\), \\[\\] less visible."
:group 'LaTeX-math)
(font-lock-add-keywords
'latex-mode
`((,(rx (and "\\" (any "()[]"))) 0 'unimportant-latex-face prepend))
'end)
(font-lock-add-keywords
'latex-mode
`((,"\\\\[[:word:]]+" 0 'font-lock-keyword-face prepend))
'end)
#+END_SRC
And enable shell escape for the preview
#+BEGIN_SRC emacs-lisp
(setq preview-LaTeX-command '("%`%l \"\\nonstopmode\\nofiles\
\\PassOptionsToPackage{" ("," . preview-required-option-list) "}{preview}\
\\AtBeginDocument{\\ifx\\ifPreview\\undefined"
preview-default-preamble "\\fi}\"%' \"\\detokenize{\" %t \"}\""))
#+END_SRC
2020-03-15 16:19:17 +00:00
*** CDLaTeX
The symbols and modifies are very nice by default, but could do with a bit of
fleshing out. Let's change the prefix to a key which is similarly rarely used,
but more convenient, like =;=.
2020-03-15 16:19:17 +00:00
#+BEGIN_SRC emacs-lisp
(after! cdlatex
(setq ;; cdlatex-math-symbol-prefix ?\; ;; doesn't work at the moment :(
cdlatex-math-symbol-alist
'( ;; adding missing functions to 3rd level symbols
(?_ ("\\downarrow" "" "\\inf"))
(?2 ("^2" "\\sqrt{?}" "" ))
(?3 ("^3" "\\sqrt[3]{?}" "" ))
(?^ ("\\uparrow" "" "\\sup"))
(?k ("\\kappa" "" "\\ker"))
(?m ("\\mu" "" "\\lim"))
(?c ("" "\\circ" "\\cos"))
(?d ("\\delta" "\\partial" "\\dim"))
(?D ("\\Delta" "\\nabla" "\\deg"))
;; no idea why \Phi isnt on 'F' in first place, \phi is on 'f'.
(?F ("\\Phi"))
;; now just conveniance
(?. ("\\cdot" "\\dots"))
(?: ("\\vdots" "\\ddots"))
(?* ("\\times" "\\star" "\\ast")))
cdlatex-math-modify-alist
'( ;; my own stuff
(?B "\\mathbb" nil t nil nil)
(?a "\\abs" nil t nil nil))))
2020-03-15 16:19:17 +00:00
#+END_SRC
In a smilar vein to this, really whenever I have a number after a symbol (letter
or command) I want it as a subscript. *@yoavm448* did some lovely legwork to
provide this:
#+BEGIN_SRC emacs-lisp
(defun prvt/auto-number-subscript ()
(interactive)
(if (and (or (and (>= (char-before) ?a) (<= (char-before) ?z))
(and (>= (char-before) ?A) (<= (char-before) ?Z)))
(cl-digit-char-p (string-to-char (this-command-keys)))
(texmathp))
(insert "_" (this-command-keys))
(insert (this-command-keys))))
(map!
:after tex :map LaTeX-mode-map
:i "1" #'prvt/auto-number-subscript
:i "2" #'prvt/auto-number-subscript
:i "3" #'prvt/auto-number-subscript
:i "4" #'prvt/auto-number-subscript
:i "5" #'prvt/auto-number-subscript
:i "6" #'prvt/auto-number-subscript
:i "7" #'prvt/auto-number-subscript
:i "8" #'prvt/auto-number-subscript
:i "9" #'prvt/auto-number-subscript)
#+END_SRC
*** SyncTeX
#+BEGIN_SRC emacs-lisp
(after! tex
(add-to-list 'TeX-view-program-list '("Evince" "evince %o"))
(add-to-list 'TeX-view-program-selection '(output-pdf "Evince")))
#+END_SRC
2020-05-18 16:01:23 +00:00
*** Evilification
Let's face it. Being evil is fun, let's take it as far as we can.
#+BEGIN_SRC emacs-lisp
(use-package! evil-tex
:hook (LaTeX-mode . evil-tex-mode))
#+END_SRC
** Python
Since I'm using =mypyls=, as suggested in [[file:~/.emacs.d/modules/lang/python/README.org::*Language Server Protocol Support][:lang python LSP support]] I'll tweak the
priority of =mypyls=
#+BEGIN_SRC emacs-lisp
(after! lsp-python-ms
(set-lsp-priority! 'mspyls 1))
#+END_SRC
2020-01-09 18:03:42 +00:00
** R
*** Editor Visuals
#+BEGIN_SRC emacs-lisp
(after! ess-r-mode
(appendq! +pretty-code-symbols
2020-02-03 05:03:39 +00:00
'(:assign "⟵"
:multiply "×"))
2020-01-09 18:03:42 +00:00
(set-pretty-symbols! 'ess-r-mode
;; Functional
:def "function"
;; Types
:null "NULL"
:true "TRUE"
:false "FALSE"
:int "int"
:floar "float"
:bool "bool"
;; Flow
:not "!"
:and "&&" :or "||"
:for "for"
:in "%in%"
:return "return"
;; Other
2020-02-03 05:03:39 +00:00
:assign "<-"
:multiply "%*%"))
2020-01-09 18:03:42 +00:00
#+END_SRC
2020-02-03 05:04:00 +00:00
** hledger
~ledger-mode~ is great and all, but ~hledger~ seems to be more actively maintained.
For example, from 2018--2020, the most prolific contributor to ~ledger~ produced
31 commits. For ~hledger~ this statistic is 1800 commits. In addition, over the
last decade, ~ledger~ seems to have lost steam, while ~hledger~ seems as actively
developed as ever. From this basic comparison ~hledger~ looks to have a more
promising outlook. It also has a few extra niceties that ~ledger~ doesn't, but is
2020-02-17 08:16:56 +00:00
a little slower (~haskell~ vs. ~c++~).
2020-02-03 05:04:00 +00:00
Since this uses the same format, and ~ledger-mode~ is well integrated into emacs,
2020-02-17 08:16:56 +00:00
and produced by John Wiegley --- author of ~ledger~ and current Emacs maintainer
2020-02-03 05:04:00 +00:00
--- using this seems like a good idea. Thankfully we can, with a little modification.
#+BEGIN_SRC emacs-lisp
(setq ledger-mode-should-check-version nil
ledger-report-links-in-register nil
ledger-binary-path "hledger")
#+END_SRC
** Markdown
Let's use mixed pitch, because it's great
#+BEGIN_SRC emacs-lisp
(add-hook! (gfm-mode markdown-mode) #'mixed-pitch-mode)
#+END_SRC
Most of the time when I write markdown, it's going into some app/website which
will do it's own line wrapping, hence we /only/ want to use visual line wrapping. No hard stuff.
#+BEGIN_SRC emacs-lisp
(add-hook! (gfm-mode markdown-mode) #'visual-line-mode #'turn-off-auto-fill)
#+END_SRC
Since markdown is often seen as rendered HTML, let's try to somewhat mirror the
style or markdown renderes.
Most markdown renders seem to make the first three headings levels larger than
normal text, the first two much so. Then the fourth level tends to be the same
as body text, while the fifth and sixth are (increasingly) smaller, with the
sixth greyed out. Since the sixth level is so small, I'll turn up the boldness a notch.
#+BEGIN_SRC emacs-lisp
(custom-set-faces!
'(markdown-header-face-1 :height 1.25 :weight extra-bold :inherit markdown-header-face)
'(markdown-header-face-2 :height 1.15 :weight bold :inherit markdown-header-face)
'(markdown-header-face-3 :height 1.08 :weight bold :inherit markdown-header-face)
'(markdown-header-face-4 :height 1.00 :weight bold :inherit markdown-header-face)
'(markdown-header-face-5 :height 0.90 :weight bold :inherit markdown-header-face)
'(markdown-header-face-6 :height 0.75 :weight extra-bold :inherit markdown-header-face))
#+END_SRC
2020-02-03 05:04:00 +00:00
** Beancount
2020-02-14 17:25:59 +00:00
The [[https://bitbucket.org/blais/beancount/src/tip/editors/emacs/beancount.el][beancount package]] online has been put into ~./lisp~, we just need to load and
enable it for ~.beancount~ files.
2020-02-03 05:04:00 +00:00
#+BEGIN_SRC emacs-lisp
(use-package! beancount
2020-03-18 16:49:23 +00:00
:load-path "~/.config/doom/lisp"
:mode ("\\.beancount\\'" . beancount-mode)
:config
(setq beancount-electric-currency t)
2020-03-18 16:49:23 +00:00
(defun beancount-bal ()
"Run bean-report bal."
(interactive)
(let ((compilation-read-command nil))
(beancount--run "bean-report"
(file-relative-name buffer-file-name) "bal")))
2020-05-17 03:29:11 +00:00
(map! :map beancount-mode-map
:n "TAB" #'beancount-align-to-previous-number
:i "TAB" #'beancount-tab-dwim))
2020-02-03 05:04:00 +00:00
#+END_SRC
# Local variables:
# eval: (add-hook 'after-save-hook 'org-html-export-to-html t t)
# end: