- [[#formats-and-languages][formats and languages]]
- [[#org-mode][org-mode]]
- [[#low-level-config-1][low-level config]]
- [[#buffer-interface][buffer interface]]
- [[#calfw][calfw]]
- [[#window-splitting][window splitting]]
- [[#exporting][exporting]]
- [[#project-management][project management]]
- [[#gtd-implementation][gtd implementation]]
- [[#gtd-next-generation][gtd next generation]]
- [[#tomato-mode][tomato mode]]
- [[#brain][brain]]
- [[#tools][tools]]
- [[#printing][printing]]
- [[#magit][magit]]
- [[#dired][dired]]
- [[#pdf-tools][pdf-tools]]
- [[#mu4e][mu4e]]
- [[#shell][shell]]
- [[#ediff][ediff]]
- [[#jupyter][jupyter]]
- [[#elfeed][elfeed]]
- [[#keybindings][keybindings]]
- [[#setup][setup]]
- [[#whichkey][whichkey]]
- [[#hydra][hydra]]
- [[#evil][evil]]
- [[#local][local]]
- [[#global][global]]
* overview
** features and use cases
- full [[https://en.wikipedia.org/wiki/Getting_Things_Done][GTD]] implementation with =org-mode= to help me stay organized
- unified interface for common linux tools (dired, shell, git, ediff)
- fully customizable email client with =mu4e=
- optimizations for some of my favorite languages (R, Lisp, Haskell, Lua, Python)
- document preparation with latex
** for new users
Feel free to take bits and pieces for your own configuration file. Like many things in emacs, the config file is quite self documenting; however, there are some useful ramblings that decribe why I made some design choices over others. As someone who learned from countless emacs configs of other experienced users, I thought it was extremely beneficial to see the thought process behind their workflow and code, and I hope my annotations pay that forward. Finally, please don't just blindly copy this config into your =~/.emacs.d=. I don't care if you do, but you will learn more if you build from scratch.
** config structure
The "config file" is actually two files.
The "root" is =init.el= which is the file explicitly loaded by emacs. Most users have their entire config in this file but I put most of my actuall settings in another file as explained in the next paragraph. Here =init.el= has minimum functionality, including setting the repositories, configuring =use-package= (which installs all other packages and ensures they are available, useful if I move this elsewhere), and load paths for other config file.
Once loaded, the =init.el= pulls in another file called =conf.el= with the function =org-babel-load-file=. =conf.el= is actually sourced from an [[https://en.wikipedia.org/wiki/Org-mode][org]] file called =conf.org=.
Using an org file like this offers several advantages. First, org files are foldable in emacs which makes navigation easy. Second, they allow code snippets (the bit that actually go into =conf.el=) which allows for explanatory prose to be written around them, making documentation easy and clear. Third, =org-mode= has an automatic table of contents through the =toc-org= package, which makes naviagation even easier. Fourth, github itself is awesome enough to recognize org files as valid markdown and will render all the text, code snippets, headers, and table of contents in the nice html that you are reading now if on github. The result is a nearly self-documenting, self-organizing configuration that is easy to maintain and also easy to view for other users. Using the =init.el= itself would just have plain eLisp, which gets cluttered quickly. Some people break the =init.el= down into multiple files to keep everything sane, but I personally think it is easier to use one giant file that itself can be folded and abstracted to reduce the clutter.
* library
This is code that is used generally throughout the emacs config
;; (setq command (concat (buffer-substring min max) "\n"))
;; ;; (with-current-buffer pbuff
;; ;; (goto-char (process-mark proc))
;; ;; (insert command)
;; ;; (move-marker (process-mark proc) (point)))
;; ;;pop-to-buffer does not work with save-current-buffer -- bug?
;; (process-send-string proc command)
;; (display-buffer (process-buffer proc) t)
;; (when step (goto-char max) (next-line))))
#+END_SRC
* user interface
The general look and feel, as well as interactive functionality
** theme
This theme has good functionality for many different modes without being over-the-top or overly complex. It also comes with an easy way to set custom colors.
Since I run emacs in [[https://www.gnu.org/software/emacs/manual/html_node/emacs/Emacs-Server.html][client/server]] mode, the loaded theme can change depending on if the client is a terminal or server (terminals have far fewer colors). This makes the theme reset when terminal is loaded before gui or vice versa.
#+BEGIN_SRC emacs-lisp
(defvar nd/theme 'spacemacs-dark)
(defvar nd/theme-window-loaded nil)
(defvar nd/theme-terminal-loaded nil)
;; required for emacsclient/daemon setup
(if (daemonp)
(add-hook 'after-make-frame-functions
(lambda (frame)
(select-frame frame)
(if (window-system frame)
(unless nd/theme-window-loaded
(if nd/theme-terminal-loaded
(enable-theme nd/theme)
(load-theme nd/theme t))
(setq nd/theme-window-loaded t))
(unless nd/theme-terminal-loaded
(if nd/theme-window-loaded
(enable-theme nd/theme)
(load-theme nd/theme t))
(setq nd/theme-terminal-loaded t)))))
(progn
(load-theme nd/theme t)
(if (display-graphic-p)
(setq nd/theme-window-loaded t)
(setq nd/theme-terminal-loaded t))))
#+END_SRC
** modeline
This modeline goes along with the =spacemacs-theme=. It also has nice integration with =evil-mode= (see keybindings below).
#+BEGIN_SRC emacs-lisp
(use-package spaceline
:straight t
:config
(require 'spaceline-config)
(setq powerline-default-separator 'arrow
spaceline-buffer-size-p nil
spaceline-buffer-encoding-abbrev-p nil)
(spaceline-spacemacs-theme))
(line-number-mode 1)
(column-number-mode 1)
#+END_SRC
*** delight
I like to keep the modeline clean and uncluttered. This package prevents certain mode names from showing in the modeline (it also has support for =use-package= through the =:delight= keyword)
#+BEGIN_SRC emacs-lisp
(use-package delight
:straight t)
#+END_SRC
** remove interface bars
Emacs comes with some useless garbage by default. IMHO (in my haughty opinion), text editors should be boxes with text in them. No menu bars, scroll bars, or toolbars (and certainly no ribbons).
#+BEGIN_SRC emacs-lisp
(tool-bar-mode -1)
(menu-bar-mode -1)
(scroll-bar-mode -1)
#+END_SRC
** startup screen
Default startup screen is silly
#+BEGIN_SRC emacs-lisp
(setq inhibit-startup-screen t)
#+END_SRC
Instead use a dashboard, and display days until predicted death...you know, as a pick-me-up ;)
Some modes like to make popup windows (eg ediff). This prevents that.
#+BEGIN_SRC emacs-lisp
(setq pop-up-windows nil)
#+END_SRC
*** ace-window
This is an elegant window selector. It displays a number in the corner when activated, and windows may be chosen by pressing the corresponding number. Note that spacemacs fails to make the numbers look nice so the theme code is a workaround to make them smaller and prettier.
#+BEGIN_SRC emacs-lisp
(use-package ace-window
:straight t
:config
(setq aw-background t)
(custom-set-faces '(aw-leading-char-face
((t (:foreground "#292b2e"
:background "#bc6ec5"
:height 1.0
:box nil))))))
#+END_SRC
** navigation
*** helm
One of the best packages for emacs. Helm is basically a search and completion engine (other exanples being =ido-mode= and =ivy-mode=) which is mainly used for finding files and selecting commands (which are obviously used often). It also integrates well with many other modes such as =evil-mode= and =org-mode=.
#+BEGIN_SRC emacs-lisp
(use-package helm
:straight t
:delight
:init
(helm-mode 1)
:config
(setq helm-autoresize-max-height 40
helm-M-x-fuzzy-match t
helm-buffers-fuzzy-matching t
helm-recentf-fuzzy-match t
helm-semantic-fuzzy-match t
helm-imenu-fuzzy-match t
helm-scroll-amount 8)
(add-to-list 'display-buffer-alist
`(,(rx bos "*helm" (* not-newline) "*" eos)
(display-buffer-in-side-window)
(inhibit-same-window . t)
(window-height . 0.4)))
(helm-autoresize-mode 1)
(require 'helm-config))
#+END_SRC
*** helm-swoop
#+BEGIN_SRC emacs-lisp
(use-package helm-swoop
:straight t)
#+END_SRC
*** avy
Allows jumping to any character in any window with a few keystrokes. Goodbye mouse :)
#+BEGIN_SRC emacs-lisp
(use-package avy
:straight t
:config
(setq avy-background t))
#+END_SRC
** cursor
This makes a nice glowy effect on the cursor when switching window focus. Very elegant way of saving time in finding where you left off.
#+BEGIN_SRC emacs-lisp
(use-package beacon
:straight t
:delight
:init
(beacon-mode 1))
#+END_SRC
** misc
*** line wrap
I don't like line wrap
#+BEGIN_SRC emacs-lisp
(set-default 'truncate-lines t)
#+END_SRC
*** smooth scrolling
This makes scrolling smoother
#+BEGIN_SRC emacs-lisp
(setq scroll-conservatively 100)
#+END_SRC
*** imagemagick
#+BEGIN_SRC emacs-lisp
(when (fboundp 'imagemagick-register-types)
(imagemagick-register-types))
#+END_SRC
*** yes-no prompt
Some prompts require literal "yes" or "no" to decide action. Life is short and I would rather not waste keystrokes typing whole words. This makes all "yes/no" prompts only require "y" or "n."
#+BEGIN_SRC emacs-lisp
(defalias 'yes-or-no-p 'y-or-n-p)
#+END_SRC
*** folding
#+BEGIN_SRC emacs-lisp
(use-package origami
:straight t
:config
;; weirdly, delight does not do this automatically
Saving files continuously is actually really annoying and clutters my disk. Turn it off.
#+BEGIN_SRC emacs-lisp
(setq make-backup-files nil)
(setq auto-save-default nil)
#+END_SRC
** async
Allows certain processes to run in multithreaded manner. For things like IO this makes sense.
#+BEGIN_SRC emacs-lisp
(use-package async
:straight t
:delight dired-async-mode
:init
(dired-async-mode 1))
#+END_SRC
* editing
For options that specifically affect programming or editing modes
** standardization
*** tabs and alignment
Who uses tabs in their programs? Make tabs actually equal 4 spaces. Also, alledgedly I could [[https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/][make more money]] if I use spaces :)
#+BEGIN_SRC emacs-lisp
(setq-default indent-tabs-mode nil
tab-width 4)
#+END_SRC
*** short column width
Alot of languages at least semi-adhere to the 80-characters-per-line rule. =fci-mode= displays a line as a guide for column width.
#+BEGIN_SRC emacs-lisp
(use-package fill-column-indicator
:straight t
:config
(setq fci-rule-use-dashes t)
:hook
(prog-mode . fci-mode))
#+END_SRC
*** spell checking
I use the built-in =flyspell-mode= to handle spellchecking. Obviously I am going to use =helm= when I spellcheck something.
#+BEGIN_SRC emacs-lisp
;; (use-package flyspell-correct-helm
;; :straight flyspell-correct
;; :after (helm flyspell))
(use-package helm-flyspell
:straight t
:after (helm flyspell))
#+END_SRC
This will spell-check comments in programming languages.
#+BEGIN_SRC emacs-lisp
(add-hook 'prog-mode-hook #'flyspell-prog-mode)
(setq flyspell-issue-message-flag nil)
#+END_SRC
Since flyspell mode is enabled in so many buffers, use a short modeline alias.
#+BEGIN_SRC emacs-lisp
(delight 'flyspell-mode "σ" "flyspell")
#+END_SRC
Additionally, I want to automatically highlight errors whenever =flyspell-mode= is enabled.
Flycheck will highlight and explain syntax errors in code and formatting. See each language below for external tools that need to be installed to make flycheck work to the fullest.
Company provides a dropdown of completion options. It has many backends which are configured in each language and format elsewhere.
#+BEGIN_SRC emacs-lisp
(use-package company
:straight t
:delight "κ"
:config
(setq company-idle-delay 0
company-minimum-prefix-length 3))
#+END_SRC
** undo
I find it weird that most programs do not have a tree-like tool to navigate undo information...because this is literally how most programs store this data.
=undo-tree= package adds a nice undo tree buffer to visualize history and also displays diffs to easily show what changed.
#+BEGIN_SRC emacs-lisp
(use-package undo-tree
:straight t
:delight
:config
(setq undo-tree-visualizer-diff t)
(global-undo-tree-mode))
#+END_SRC
** parenthesis matching
This color-codes matching parenthesis. Enable pretty much everywhere.
For me this means R but ess also supports S-plus, SAS, Stata, and other statistical black-magic languages. Note that ESS is not part of =prog-mode= so it must be added manually to hooks.
On Arch, all packages are dynamically linked (very bad for Haskell). The solution is to install [[https://docs.haskellstack.org/en/stable/README/][stack]] via the =stack-static= package through the AUR and then install all Haskell programs through stack using static linking.
This also provides GHC which is used by flycheck for syntax checking.
**** major mode
#+BEGIN_SRC emacs-lisp
(use-package haskell-mode
:straight t
:hook (haskell-mode . origami-mode)
:config
(setq haskell-interactive-popup-errors nil))
#+END_SRC
**** intero
Provides shell, autocomplete, and syntax checking. Requires the =intero= binary to be installed through stack (=stack install intero=).
#+BEGIN_SRC emacs-lisp
(use-package intero
:straight t
:after haskell-mode
:hook
(haskell-mode . intero-mode))
#+END_SRC
**** camelCase
The defacto style for haskell mandates camelcase, so use subword mode.
#+BEGIN_SRC emacs-lisp
(add-hook 'haskell-mode-hook #'subword-mode)
(delight 'subword-mode nil "subword")
#+END_SRC
**** hlint
Additional syntax checking can be enabled with the =hlint= program (=stack install hlint=).
For flycheck, install =luacheck= (from AUR on Arch).
#+BEGIN_SRC emacs-lisp
(use-package lua-mode
:straight t)
#+END_SRC
*** TeX
**** AUCTeX
Install auctex through emacs as this is OS independent and more automatic. Note that the Tex package libraries (eg TeXLive) still need to be installed to do anything useful.
#+BEGIN_SRC emacs-lisp
(use-package tex
:straight auctex
:hook
((LaTeX-mode . flycheck-mode)
(LaTeX-mode . flyspell-mode)
(LaTeX-mode . fci-mode)
;; sync tex buffer positions to output pdf
(LaTeX-mode . TeX-source-correlate-mode))
:config
(setq TeX-after-compilation-finished-functions
'(TeX-revert-document-buffer)))
#+END_SRC
**** external viewers
AUCTeX can launch external viewers to show compiled documents.
#+BEGIN_SRC emacs-lisp
(setq TeX-view-program-selection
'(((output-dvi has-no-display-manager) "dvi2tty")
((output-dvi style-pstricks) "dvips and gv")
(output-dvi "xdvi")
(output-pdf "PDF Tools")
(output-html "xdg-open")))
#+END_SRC
**** outline mode
***** folding
I like how =org-mode= folds with the TAB key, so bring the same thing to AUCTeX here with =outline-magic=.
#+BEGIN_SRC emacs-lisp
(use-package outline-magic
:straight t
:after outline
:hook
((LaTeX-mode . outline-minor-mode)))
#+END_SRC
***** fonts
The section fonts are too big by default. Now the fonts are all kept equal with hatchet, axe, and saw :)
#+BEGIN_SRC emacs-lisp
(setq font-latex-fontify-sectioning 'color)
#+END_SRC
**** auto completion
There are two backends which (kinda) complement each other. The =company-math= package should privide completion for math symbols and the =company-auctex= package should cover pretty much everything else.
I like having my lines short and readable (also easier to git). Turn on autofill here and also make a nice vertical line at 80 chars (=visual-line-mode=).
R-markdown is enabled via polymode, which allows multiple modes in one buffer (this is actually as crazy as it sounds). In this case, the modes are yaml, R, markdown, and others. Installing =poly-R= will pull in all required dependencies.
#+BEGIN_SRC emacs-lisp
(use-package poly-R
:straight t
:mode
(("\\.Rmd\\'" . poly-markdown+r-mode)
("\\.rmd\\'" . poly-markdown+r-mode)))
#+END_SRC
*** YAML
#+BEGIN_SRC emacs-lisp
(use-package yaml-mode
:straight t)
#+END_SRC
*** csv files
This adds support for csv files. Almost makes them editable like a spreadsheet. The lambda function enables alignment by default.
No custom code here, but flycheck needs =shellcheck= (a Haskell program). On Arch (or any other distro that loves dynamic binding) easiest way to install is via =stack install ShellCheck=
No custom code here, but flycheck needs =sqlint= (on Arch available through the AUR).
* org-mode
** low-level config
*** modules
Org has several extensions in the form of loadable modules. =org-protocol= is used as a backend for external programs to communicate with =org-mode=. =org-habit= allows the habit todoitem which is used as a more flexible recurring task.
#+BEGIN_SRC emacs-lisp
(org-set-modules 'org-modules
(list 'org-habit ; for habit viewing in agenda
'org-protocol)) ; for external captures
;; required for 9.2
;;'org-tempo)) ; for autocomplete src blocks
;; make sure everything else works that I have customly defined
(require 'org-agenda)
(require 'org-protocol)
(require 'org-habit)
(require 'org-clock)
;;(require 'org-tempo) ;; required for 9.2
#+END_SRC
*** directory
I keep all my org files in one place.
#+BEGIN_SRC emacs-lisp
(setq org-directory "~/Org")
#+END_SRC
*** autosave
Save all org buffers 1 minute before the hour.
#+BEGIN_SRC emacs-lisp
(defun nd/org-save-all-org-buffers ()
"Save org buffers without confirmation or message (unlike default)."
(save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
I often write long, lengthy prose in org buffers, so use =visual-line-mode= to make lines wrap in automatic and sane manner.
#+BEGIN_SRC emacs-lisp
(add-hook 'org-mode-hook #'visual-line-mode)
(delight 'visual-line-mode nil 'simple)
#+END_SRC
*** indentation
By default all org content is squished to the left side of the buffer regardless of its level in the outline. This is annoying and I would rather have content indented based on its level just like most bulleted lists. This is what =org-indent-mode= does.
#+BEGIN_SRC emacs-lisp
(setq org-startup-indented t)
(delight 'org-indent-mode nil "org-indent")
#+END_SRC
*** special key behavior
TODO: These don't work in evil mode (using the usual line commands).
#+BEGIN_SRC emacs-lisp
(setq org-special-ctrl-a/e t
org-special-ctrl-k t
org-yank-adjusted-subtrees t)
#+END_SRC
*** bullets
These are just so much better to read
#+BEGIN_SRC emacs-lisp
(use-package org-bullets
:straight t
:hook
(org-mode . org-bullets-mode))
#+END_SRC
*** font height
The fonts in org headings bug me; make them smaller and less invasive.
This is a nifty calendar...sometimes way faster than the agenda buffer for looking at long term things.
#+BEGIN_SRC emacs-lisp
(use-package calfw
:straight t
:config
(setq cfw:fchar-junction ?╋
cfw:fchar-vertical-line ?┃
cfw:fchar-horizontal-line ?━
cfw:fchar-left-junction ?┣
cfw:fchar-right-junction ?┫
cfw:fchar-top-junction ?┯
cfw:fchar-top-left-corner ?┏
cfw:fchar-top-right-corner ?┓))
(use-package calfw-org
:straight t
:after calfw
:config
(setq cfw:org-agenda-schedule-args
'(:deadline :timestamp)))
#+END_SRC
** window splitting
Org mode is great and all, but the windows never show up in the right place. The solutions here are simple, but have the downside that the window sizing must be changed when tags/capture templates/todo items are changed. This is because the buffer size is not known at window creation time and I didn't feel like making a function to predict it
*** todo selection
I only need a teeny tiny window below my current window for todo selection
#+BEGIN_SRC emacs-lisp
(defun nd/org-todo-position (buffer alist)
(let ((win (car (cl-delete-if-not
(lambda (window)
(with-current-buffer (window-buffer window)
(memq major-mode
'(org-mode org-agenda-mode))))
(window-list)))))
(when win
(let ((new (split-window win -4 'below)))
(set-window-buffer new buffer)
new))))
(defun nd/org-todo-window-advice (orig-fn)
"Advice to fix window placement in `org-fast-todo-selection'."
Use =latexmk= instead of =pdflatex= as it is more flexible and doesn't require running the process zillion times just to make a bibliography work. Importantly, add support here for BibTeX as well as the custom output directory (see below).
By default org export files to the same location as the buffer. This is insanity and clutters my org directory with =.tex= and friends. Force org to export to a separate location.
The default is XHTML for some reason (which few use and makes certain barbaric word processors complain). Use the much-superior html5.
#+BEGIN_SRC emacs-lisp
(setq org-html-doctype "html5")
#+END_SRC
** project management
[[https://github.com/taskjuggler/TaskJuggler][TaskJuggler]] is software that is most likely used by some super-intelligent alien species to plan their invasions of nearby planets and develop sophisticated means of social control.
Basically it is really complicated and powerful. For now I use it to make cute gantt charts.
Taskjuggler is provided by an external package that provides the command line tools (available in the AUR for Arch Linux). Org-mode has "native" export support through a contrib module. I maintain a separate package with extra functions with taskjuggler web interface support in a separate package loaded here.
This section is meant to be a big-picture overview of how GTD works in this setup. For specifics, see each section following this for further explanation and code. I should also say that most of the ideas for the code came from [[http://doc.norang.ca/org-mode.html#OrgFileStructure][Bernt Hansen's]] very detailed guide.
**** workflow
GTD as described in its [[https://en.wikipedia.org/wiki/Getting_Things_Done][original form]] is divided into five steps as explained further below. Here I attempt to explain how I implement each of these into =org-mode=.
***** collect
The whole point of GTD is to get stuff out of one's head, and this is purpose of the /collect/ step. Basically if a thought or task pops in my head or interrupts me, I record it somewhere. These thoughts can happen any time and anywhere, so it is important to keep them out of consciousness so that I can concentrate on whatever I am doing.
When =org-mode= is in front of me, I use =org-capture= (see below for =org-capture-templates=). The "things" that could be collected include anything from random ideas, things I remember to do, appointments I need to attend, etc. I also capture emails with =mu4e= (which links to =org-mode= through =org-protocol=). Everythign collected with =org-capture= gets sent to a dedicated file where I deal with it later (see /process/ step).
When =org-mode= is not in front of me, I record my thoughts in the Orgzly app on my android. It doesn't really sync so I transfer everything manually.
***** process
Collecting only records things; it doesn't make decisions. The point of the /process/ step is to decide if the task/note is worth my time and when. This involves several key questions.
The first question to ask is if the task is actionable. If yes, it gets moved to a project file or a general task file. If not, I ask it can either be moved to the "incubator" (a place for things I might do), be moved any number of reference files (for storing inportant information), or flat-out deleted if I think it is stupid or no longer relevant.
In =org-mode= these decisions are made and recorded by moving headings between files with =org-refile=. To facilitate this process I have an agenda view to filter out captured tasks. From there it is easy to refile to wherever the headers need to go.
This step happens daily along with /organize/ below.
***** organize
The /organize/ step is basically the second half of the /process/ step (I honestly think of these as a single task because that's how they are implemented in =org-mode=, but the original GTD workflow describes them seperately).
After refiling with =org-refile=, the next step is to add any remaining meta information to each task, which is later used to decide what to do and when. This information includes context, effort, delegation, and timestamps. In the case of projects this also includes choosing a NEXT tasks if one hasn't been chosen already.
Delegation (assingning something to someone else) is simple and is represented by a simple property which is filled with the initials of the person doing the work. It filter and view this with =org-columns= and =org-agenda-columns=.
When tasks don't have a specific date, GTD outlines a four-criteria model for deciding what to do: context, required time, available energy, and priority. Context describes required locations and resources for tasks, and I represent them with tags (see =org-tags-alist=). Required time is represented by the =Effort= property (see =org-default-properties= below). Available energy is subjective and not represented in =org-mode=. Priority is again represented with tags, here chosen from one of seven "life categories."
In assigning timestamps, =org-mode= offers several possibilities out of the box. Putting a plain active timestamp denotes an appointment (something at which I need to show up). A scheduled timestamp denotes a task that I want to work on starting at a certain time. A deadline denotes a task that must be finished by a certain time. I try to only use these for "hard" times as anything "soft" risks me not fulfilling to the timestamp and hence diminishing the value of timestamps in general.
I have three main agenda views for handling this. The first is a daily view that shows the tasks needed for today, including anything with a timestamp. The second has all tasks that are not timestamps (eg things that can be done at any time). The third is a project view that shows the top level headings for collections of tasks (this is where I find any projects that need a NEXT task).
The /organize/ step may seem like it requires alot of work but luckily =org-mode= allows enough automation that some of this meta information can be added in the /collect/ and /process/ phases. For instance, timestamps and tags can be added (forcibly) in =org-capture= depending on what template is used. Furthermore, the priority tag and some context tags are added when the task is refiled to its proper file or project; this happens via tag inheritance, defined at either the file level or a parent heading (for instance, a computer-related tasks may be filed under =environmental/computer= where =environment= has the =_env= tag and =computer= has the =#laptop= tag).
***** review
In order to keep the entire workflow moving smoothly, it is necessary to do a high-level /review/.
This happens weekly and involves several things.
- Scheduling important tasks and resolve conflicts. For this I use =calfw= (basically a calendar) to look at the next week and check if anything overlaps and move things around. I also "reload" repeater tasks using =nd/org-clone-subtree-with-timeshift=.
- Moving tasks to the archive as they are available. This keeps =org-mode= fast and uncluttered.
- Reviewing the incubator and moving tasks out that I actually decide to do.
- Reviewing reference material and moving it to appropriate tasks.
- Assessing projects based on their status (see below for the definition of "status"). Ideally all projects are "active," and if they are not I try to make them active by assigning NEXT.
I have specialized agenda views and commands for facilitating all of this.
***** execute
/Execute/ involves doing the predefined work laid out in the previous four steps. Generally I work through two agenda views (in order). The first being all my tasks that need to get done in the day, and the second being all tasks with no specific timestamp.
Besides physically doing the tasks here, the other special thing in =org-mode= that I use is clocking. In addition to tracking time spent, it also encourages clean breaks between tasks (eg no multitasking).
**** file hierarchy and structure
All org files are kept in one place (see =org-directory=). This is futher subdivided into directories for project (as per terms and definitions, these are any tasks that involve at least on subtask) and reference files. At the top level are files for incubated tasks, captured tasks, and catchall general tasks (which also includes small projects that don't fit anywhere else).
In order to make sorting easier and minimize work during processing, the files are further subdivided using tags at the file level and heading level that will automatically categorize tasks when they are refiled to a certain location. For example, some project may be to create a computer program, so I would set =#+FILETAGS: #laptop= because every task in this project will require a laptop. See the tags section below for more information on tags.
**** repetition
This deserves special attention because it comprises a significant percentage of tasks I do (and likely everyone does). I personally never liked the org's repeated task functionality. It is way too temporally rigid to be useful to me, and offers very little flexibility in mutating a task as it moves forward. Habits (which I use) are a partial fix for the first problem but do not aleviate the mutability problem.
My (somewhat convoluted) solution was to use =org-clone-subtree-with-time-shift=, which creates an easy way to make repeated tasks from some template, but also allows modification. The only problem with the vanilla implementation is that it lacks automation and agenda-block awareness (they all get treated as regular tasks which I don't want). This is partially fixed with my own =org-x-clone-subtree-with-time-shift= which automaticlly resets tasks which are cloned (eg clearing checkboxes and resetting todo state). The remainding problems I fixed by defining several properties to be applied to repeated groupings under a heading (see properties).
The first property is called =PARENT_TYPE= and has two values =iterator= and =periodical=. The first applies to repeated tasks and second which applies to timestamped headings such as appointments. These are mostly useful for agenda sorting, where I have views specifically for managing repeated tasks. The second property is =TIME_SHIFT=; =org-x-clone-subtree-with-time-shift= is aware of this value and automatically shifts cloned tasks accordingly if available.
In practice, I use this for tasks like workouts, paying bills, maintenance, grocery shopping, work meetings, GTD reviews, etc. These are all *almost* consistent but may change slightly in their timing, action items, effort, context, etc. If any of these change, it is easy enough to modify one heading without disrupting the rest.
The heart of this implementation is an army of block agenda views (basically filters on the underlying org trees that bring whatever I need into focus). These have become tailored enough to my workflow that I don't even use the built-in views anymore (I also have not found an "easy" way to turn these off). Besides projects, these agenda views are primarily driven using skip functions.
***** projects
When it comes to the agenda view, I never liked how org-mode by default handled "projects" (see how that is defined in "terms and definitions"). It mostly falls short because of the number of todo keywords I insist on using. The solution I implemented was to used "statuscodes" (which are just keywords in lisp) to define higher-level descriptions based on the keyword content of a project. For example a "stuck" project (with statuscode =:stuck=) is a project with only =TODO= keywords. Adding a =NEXT= status turns the statuscode to =:active=. Likewise =WAIT= makes =:waiting=. This seems straightforward, except that =NEXT= trumps =WAIT=, =WAIT= trumps =HOLD=, etc. Furthermore, there are errors I wish to catch to ensure subtrees get efficiently cleaned out, such as a project heading with =DONE= that still has a =TODO= underneath.
I used to take care of this problem with lots of skip functions, but it turned out to be unmaintainable and offered poor performance (eg if I wanted a block agenda for =N= statuscodes, I needed to scan the entire org tree =N= times). A far easier way to implement this was to embed the statuscodes in text properties in each agenda line, which could then be sorted and the prefix string formatted with the status code for identification in the block agenda view. Since this only requires one block, it only requires one scan, and is very fast.
***** repeaters
Similarly to projects, repeaters (eg iterators and periodicals) are assessed via a statuscode (after all they are a group of headings and thus depending on the evaluation of todo keywoards and timestamps in aggregate). These prove much simpler than projects as essentially all I need are codes for uninitialized (there is nothing in the repeater), empty (all subheadings are in the past and therefore irrelevant), and active (there are some subtasks in the future).
**** terms and definitions
These conventions are used throughout to be precise when naming functions/variables and describing their effects
***** headings
- heading: the topmost part after the bullet in an org outline. Org-mode cannot seem to make up it's mind in calling it a header, heading, or headline, so I picked heading
- todoitem: any heading with a todo keyword
- task: a todoitem with no todoitem children
- atomic: further specifies that the task is not part of a project
- project: a todoitem with that has todoitem children or other projects
- status(code): a keyword used to describe the overall status of a project. See skip functions in the block agenda section for their implementation.
***** time
- stale: refers to timestamps that are in the past/present
- archivable: further specifies that the timestamp is older than some cutoff that defines when tasks can be archived (usually 30 days)
- fresh: refers to timestamps that are in the future
*** todo states
**** sequences
These keywords are used universally for all org files (see below on quick explanation for each, they are all quite straightforward). Note that projects have a more specific meaning for these keywords in defining project status (see the library of agenda function). Also, it looks way better in the agenda buffer when they are all the same number of chars.
In terms of logging, I like to record the time of each change upon leaving any state, and I like recording information in notes when waiting, holding, or canceling (as these usually have some external trigger or barrier that should be specified).
#+BEGIN_SRC emacs-lisp
(setq org-todo-keywords
'((sequence
;; default undone state
"TODO(t/!)"
;; undone but available to do now (projects only)
"NEXT(n/!)" "|"
;; done and complete
"DONE(d/!)")
(sequence
;; undone and waiting on some external dependency
"WAIT(w@/!)"
;; undone but signifies tasks on which I don't wish to focus at the moment
"HOLD(h@/!)" "|"
;; done but not complete
"CANC(c@/!)")))
#+END_SRC
**** colors
Aesthetically, I like all my keywords to have bold colors.
I use tags for agenda filtering (primarily for GTD contexts, see below). Each tag here starts with a symbol to define its group (note, only the special chars "_", "@", "#", and "%" seem to be allowed; anything else will do weird things in the hotkey prompt). Some groups are mutually exclusive. By convention, any tag not part of these groups is ALLCAPS (not very common) and set at the file level.
#+BEGIN_SRC emacs-lisp
(setq org-tag-alist
;; (@) gtd location context
`((:startgroup)
("@errand" . ?e)
("@home" . ?h)
("@work" . ?w)
("@travel" . ?r)
(:endgroup)
;; (#) gtd resource context
("#laptop" . ?l)
("#tcult" . ?t)
("#phone" . ?p)
;; (%) misc tags
;; denotes reference information
("%note" . ?n)
;; incubator (the someday/maybe list)
("%inc" . ?i)
;; maybe (for things I might want to do, to be used with %inc)
("%maybe" . ?m)
;; denotes tasks that need further subdivision to turn into true project
("%subdiv" . ?s)
;; catchall to mark important headings, usually for meetings
The built-in =effort= is used as the fourth and final homonymous GTD context (the other three being covered above using tags). It is further restricted with =Effort_All= to allow easier filtering in the agenda.
Also here are the properties for repeated tasks and a few others (see comments in code).
As per Bernt's guide, capture is meant to be fast. The dispatcher is bound to =F2= (see keybindings section) which allows access in just about every mode and brings a template up in two keystrokes.
#+BEGIN_SRC emacs-lisp
(defun nd/org-timestamp-future (days)
"Inserts an active org timestamp DAYS after the current time."
(format-time-string (org-time-stamp-format nil)
(time-add (current-time) (days-to-time 1))))
(let ((capfile "~/Org/capture.org"))
(setq org-capture-templates
;; regular TODO task
`(("t" "todo" entry (file ,capfile)
"* TODO %?\n")
;; for useful reference information that may be grouped with tasks
("n" "note" entry (file ,capfile)
"* %?\n%U\n")
;; for non-actionable events that happen at a certain time
("a" "appointment" entry (file ,capfile)
"* %?\n%U\n%^t\n")
;; like appointment but multiple days
("s" "appointment-span" entry (file ,capfile)
"* %?\n%U\n%^t--%^t\n")
;; task with a deadline
("d" "deadline" entry (file ,capfile)
"* TODO %?\nDEADLINE: %^t\n")
;; for converting mu4e emails to tasks, defaults to next-day deadline
("e" "email" entry (file ,capfile)
"* TODO Respond to %:fromname; Re: %:subject :#laptop:\nDEADLINE: %(nd/org-timestamp-future 1)\n%a\n")
;; for interruptions that produce useful reference material
("m" "meeting" entry (file ,capfile)
"* meeting with%? :\\%note:\n%U\n")
;; TODO add entries here for asynchronously performed tasks
;; that can be tracked
;; target these to a specific headline in general.org
Refile (like capture) should be fast, and I search all org file simultaneously using helm (setting =org-outline-path-complete-in-steps= to =nil= makes search happen for entire trees at once and not just the current level). Refiling is easiest to do from a block agenda view (see below) where headings can be moved in bulk.
#+BEGIN_SRC emacs-lisp
(setq org-refile-targets '((nil :maxlevel . 9)
("~/Org/reference/idea.org" :maxlevel . 9)
(org-agenda-files :maxlevel . 9))
org-refile-use-outline-path t
org-outline-path-complete-in-steps nil
org-refile-allow-creating-parent-nodes 'confirm
org-indirect-buffer-display 'current-window)
#+END_SRC
Prevent accidental refiling under tasks with done keywords
Clocking is still new and experimental (I'm not a ninja like Bernt yet). I mostly use clocking now as a way to make clean breaks between tasks (eg to discourage "mixing" tasks which is a slippery multitasking slope). I bound =F4= to =org-clock-goto= as an easy way to find my current/last clocked task in any mode (see keybindigs).
#+BEGIN_SRC emacs-lisp
(setq org-clock-history-length 23
org-clock-out-when-done t
org-clock-persist t
org-clock-report-include-clocking-task t)
#+END_SRC
**** modeline
The modeline is a nice place to indicate if something is clocked in or out. Unfortunately, sometimes is is so crowded that I can't see the text for the currently clocked task. Solution, use colors.
#+BEGIN_SRC emacs-lisp
(defface nd/spaceline-highlight-clocked-face
`((t (:background "chartreuse3"
:foreground "#3E3D31"
:inherit 'mode-line)))
"Default highlight face for spaceline.")
(defun nd/spaceline-highlight-face-clocked ()
"Set the spaceline highlight color depending on if the clock is running."
Org mode has no way of detecting if conflicts exist. It also has no way of alerting someone if they have overbooked their schedule
**** extraction filters
These control which types of headlines are processed by org-cluster
#+BEGIN_SRC emacs-lisp
(defvar nd/org-cluster-filter-files t
"Set to t if files should be filtered in org-cluster.
This option does nothing unless `nd/org-cluster-filtered-files' is
also non-nil.")
(defconst nd/org-cluster-filtered-files
'("incubator" "peripheral")
"Files that should be excluded from org-cluster analysis.
These are pattern-matched so they do not need to be exact names
or paths.")
(defvar nd/org-cluster-filter-todo t
"Set to t if todo keywords should be filtered in org-cluster.
This option does nothing unless `nd/org-cluster-filtered-todo' is
also non-nil.")
(defconst nd/org-cluster-filtered-todo
'("CANC" "DONE")
"TODO keywords that should be filtered from org-cluster analysis.")
(defvar nd/org-cluster-filter-past t
"Set to t to exclude files from before now in org-cluster analysis.")
(defvar nd/org-cluster-filter-habit nil
"Set to t to exclude habits from org-cluster analysis.")
#+END_SRC
**** timestamp extraction and filtering
Conflicts and overloads begin with the same list to process, which is created using =org-element-parse-buffer= and a variety of filtering functions to extract relevent timestamps.
The main object that is passed around during extraction and processing is the timestamp-plist as described in =nd/org-cluster-make-tsp= below.
#+BEGIN_SRC emacs-lisp
(defun nd/org-cluster-make-tsp (unixtime range offset fp hardness
&optional type)
"Construct a timestamp plist to be used in further processing.
UNIXTIME is the unixtime of the timestamp as an integer, RANGE is the
duration of the timestamp (could be 0), OFFSET is the character offset
of the timestamp in the file represented with filepath FP, HARDNESS
is a boolean denoting if the timestamp is 'hard' (has minutes and
hours) or 'soft' (only a date). TYPE can be optionally supplied to
denote kinds of timestamps (only 'scheduled' for now)."
(list :unixtime (round unixtime)
:range (or range 0)
:offset offset
:type type
:hardness hardness
:filepath fp))
(defun nd/org-cluster-ts-hard-p (ts)
"Return non-nil if the timestamp TS has hours/minutes."
(org-element-property :hour-start ts))
(defun nd/org-cluster-parse-ts (ts hl fp)
"Parse a timestamp TS belonging to headline HL and filepath FP.
TS is an object as described in the org-element API. Only active
or active-range types are considered. Returns a new timestamp-plist
This algorithm builds a list of pairs, with each pair being a two tasks that conflict and should be O(n) (best case/no conflicts) to O(n^2) (worst case/everything conflicts).
Steps for this:
1. make a list of all entries containing timestamps (active and scheduled)
2. sort timestamp list
3. Walk through list and compare entries immediately after (sorting ensures that entries can be skipped once one non-conflict is found). If conflicts are found push the pair to new list.
"Return a list of cons cells representing conflict pairs.
Each member in the cons cell is a timestamp-plist."
(->>
(nd/org-cluster-get-unprocessed)
(--filter (plist-get it :hardness))
(--sort (< (plist-get it :unixtime) (plist-get other :unixtime)))
nd/org-cluster-build-conlist))
#+END_SRC
**** overload detection
Overloads are defined as days that have more than 24 hours worth of scheduled material. The algorithm is O(n) as it is basically just a bunch of filtering functions that walk through the list.
Steps for the algorithm:
1. filter only ranged entries (unranged entries have zero time)
2. maybe split timestamps if they span multiple days
3. sort from earliest to latest starting time
4. sum the range of timestamps in each day, keeping those that exceed 24 hours
#+BEGIN_SRC emacs-lisp
(defun nd/org-cluster-split-day-bounds (tsps)
"Split timestamp-plists in TSPS via daily boundaries.
Returns a new timestamp-plist with equal or greater length depending
on how many members needed splitting."
(letrec
((new
(lambda (start end tsp)
(nd/org-cluster-make-tsp start
(- end start)
(plist-get tsp :offset)
(plist-get tsp :filepath)
(plist-get tsp :hardness)
(plist-get tsp :type))))
;; need to temporarily offset the epoch time so day
"Return list of lists of timestamp-plists grouped by day.
Anything present represents all the tasks in a single day if that day
is overloaded. If a day is not overloaded there will be nothing for it
in the returned list."
(->>
(nd/org-cluster-get-unprocessed)
(--filter (< 0 (plist-get it :range)))
nd/org-cluster-split-day-bounds
(--sort (< (plist-get it :unixtime) (plist-get other :unixtime)))
nd/org-cluster-daily-split
(--filter (nd/org-cluster-overloaded-p it))))
#+END_SRC
**** frontend
I could just fetch the org headings and throw them into a new buffer. But that's boring, and quite limiting. I basically want all the perks of an agenda buffer...tab-follow, the nice parent display at the bottom, time adjust hotkeys, etc. So the obvious and hacky solution is to throw together a quick-n-dirty agenda buffer.
#+BEGIN_SRC emacs-lisp
(defun nd/org-cluster-headline-text (ts-entry)
"Return string with text properties representing the org header for
These are just some options to enable/disable some aesthetic things.
#+BEGIN_SRC emacs-lisp
(setq org-agenda-dim-blocked-tasks nil
org-agenda-compact-blocks t
org-agenda-window-setup 'current-window
org-agenda-start-on-weekday 0
org-agenda-span 'day
org-agenda-current-time-string "### -- NOW -- ###")
#+END_SRC
Based on my screen size and usage patterns, this seems to be a good value to enable the maximum habit history to be shown without compromising aesthetics.
#+BEGIN_SRC emacs-lisp
(setq org-habit-graph-column 50)
#+END_SRC
**** bulk actions
These add to the existing bulk actions in the agenda view.
#+BEGIN_SRC emacs-lisp
(setq org-agenda-bulk-custom-functions
'((?D org-x-agenda-delete-subtree)))
#+END_SRC
**** holidays and birthdays
If I don't include this, I actually forget about major holidays.
GTD is great but has many limitations...mostly due to the fact that it was originally made on paper. This is meant to extend the GTD workflow into a comprehensive tracking engine that can be used and analyze and project long-term plans and goals.
*** logging
**** drawer
I prefer all logging to go in a seperate drawer (aptly named) which allows easier navigation and parsing for data analytics.
#+BEGIN_SRC emacs-lisp
(setq org-log-into-drawer "LOGBOOK")
#+END_SRC
**** events
Events are nice to record because it enables tracking of my behavior (eg how often I reschedule, which may indicate how well I can predict when things should happen).
#+BEGIN_SRC emacs-lisp
(setq org-log-done 'time
org-log-redeadline 'time
org-log-reschedule 'time)
#+END_SRC
**** repeated tasks
In these cases, it is nice to know what happened during each cycle, so force notes.
#+BEGIN_SRC emacs-lisp
(setq org-log-repeat 'note)
#+END_SRC
*** sqlite backend
Org mode is great and all, but in many cases, text files just won't cut it. Hardcore data analysis is one of them, so make functions to shove org files (specifically archive files) into a sqlite database
For some reason there is no default way to get a "print prompt." Instead one needs to either install some third-party helper or make a function like this.
#+BEGIN_SRC emacs-lisp
(defun nd/helm-set-printer-name ()
"Set the printer name using helm-completion to select printer."
By default the included gnus-dired package does not understan mu4e, so override the existing =gnus-dired-mail-buffers= function to fix. This allows going to a dired buffer, marking files, and attaching them interactively to mu4e draft buffers.
By default dired uses =ls -whatever= to get its output. This does not have recursive directory contents by default. This nitfy package solves this. This is not on default because navigation is much slower and the du output adds very little in many situations (toggle when needed).
#+BEGIN_SRC emacs-lisp
(use-package dired-du
:straight t
:config
(setq dired-du-size-format t))
#+END_SRC
*** mounted devices
If dired is to replace all other file managers it must handle devices. This function assumes all my devices are mounted on =/media/$USER= and that udevil is installed. It provides mount and mount/follow ops for all usb removable media and follow/unmount for all mounted devices (note the latter includes things that are not mounted here such as samba drives, which I normally hotkey to my window manager). This /almost/ replicates the functionality of gvfs that I actually use without the bloat; the only missing piece is MPT for android (which will come later).
#+BEGIN_SRC emacs-lisp
(defun nd/helm-devices ()
"Mount, unmount, and navigate to removable media using helm."
For the sake of my sanity, all bindings go here. Note this means I don't use =:bind= in use-package forms.
** setup
Most of my modifiers are reloacted using xkb and xcape. Below is a summary where each item is in the form <original key> -> <new key action> (<key release action if used>)
- tab -> l_super (tab)
- backslash -> r_super (backslash)
- caps -> l_ctrl (escape)
- return -> r_ctrl (return)
- l_ctrl -> l_hyper
- l_super -> iso_l3_shift (xf86search)
- space -> r_alt (space)
- r_alt -> r_hyper
- r_ctrl -> caps
** whichkey
Everyone forgets keybindings. When typing a key chord, this will display a window with all possible completions and their commands.
#+BEGIN_SRC emacs-lisp
(use-package which-key
:straight t
:delight
:init
(which-key-mode))
#+END_SRC
** hydra
#+BEGIN_SRC emacs-lisp
(use-package hydra
:straight t)
;; TODO C-g is a bad combo because it is used to exit things
(defvar nd/hydra-standard-interactive-map
'(("M-i" :exit t)
(:send-line "M-i")
(:send-line-step "I" :exit nil)
(:send-line-follow "C-i")
(:send-group "p")
(:send-group-step "P" :exit nil)
(:send-group-follow "C-p")
(:send-region "r")
(:send-region-step "R" :exit nil)
(:send-region-follow "C-r")
(:send-buffer "b")
(:send-buffer-follow "C-b")
(:shell-start "z")
(:shell-start-follow "C-z")
(:shell-kill "k")
(:shell-kill-all "K"))
"Standard hydra keymap for interactive REPL workflow.")
(defvar nd/hydra-standard-navigation-map
'(("M-n" :exit t)
(:def-at "M-n")
(:def-at-new-win "N")
(:asgn-at "a")
(:asgn-at-new-win "A")
(:ref-at "r")
(:ref-at-new-win "R")
(:pop-marker-stack "b")
(:doc-at "d")
(:doc-at-new-win "D")
(:type-at "t")
(:type-at-new-win "T"))
"Standard hydra keymap for navigation and information workflow.")
Some of these commands just get in the way of being evil (which really means that I keep pressing them on accident). Rather than nullifying them completely, tuck them away in the emacs state map in case I actually want them.
This is somewhat strange because all I really care about is moving between lines and to the beginning and end as normal. However, I like the idea of thinking of paragraphs as one line (eg df. deletes a sentence even if on multiple lines). Opinion subject to change.
Since I use vi mode in my terminal emulator, need to preserve the escape key's raw behavior
#+BEGIN_SRC emacs-lisp
(evil-define-key 'insert term-raw-map
(kbd "<escape>") 'nd/term-send-raw-escape
(kbd "C-<escape>") 'evil-normal-state
(kbd "C-k") 'nd/term-send-raw-up
(kbd "H-k") 'nd/term-send-raw-up
(kbd "C-j") 'nd/term-send-raw-down
(kbd "H-j") 'nd/term-send-raw-down)
#+END_SRC
**** lisp
#+BEGIN_SRC emacs-lisp
(evil-define-key 'normal emacs-lisp-mode-map
"gh" #'lispy-left
"gl" #'lispy-flow
"gj" #'lispy-down
"gk" #'lispy-up)
#+END_SRC
** local
These are for mode-specific bindings that can/should be outside of the evil maps above (there are not many, and these may be merged with their evil bretheren in the future).
*** org-mode
#+BEGIN_SRC emacs-lisp
(add-hook 'org-mode-hook
(lambda ()
;; use the hyper keys/vim arrows with the shifters instead of shift/arrows
(local-set-key (kbd "H-k") 'org-shiftup)
(local-set-key (kbd "H-l") 'org-shiftright)
(local-set-key (kbd "H-j") 'org-shiftdown)
(local-set-key (kbd "H-h") 'org-shiftleft)
;; this is just a useful function I made (actually I think I stole)
The function keys are nice because they are almost (not always) free in every mode. Therefore I use these for functions that I need to access anywhere, but not necessary extremely often (because they are out of the way and harder to reach).