** DONE Batteries included with Emacs :emacs:
CLOSED: [2020-11-17 Tue 20:50]
:EXPORT_FILE_NAME: batteries-included-with-emacs
#+html:<style type="text/css">
#+html: .center {
#+html:    margin-left: auto;
#+html:    margin-right: auto;
#+html:    display: block
#+html: }

.figure-number {
    display: none;

Emacs has a reputation for being borderline unusable out of the box, of being
bloated but somehow surprisingly bare.

This is largely a discoverability problem[fn:terrible-defaults]. The solution
the Internet has settled on seems to be "Emacs distributions" like Doom,
Spacemacs or Prelude that glue together dozens (sometimes hundreds) of addons to
deliver a batteries included, finely tuned and user-friendly experience from
first launch. While it's not for me, this does work
great [fn:emacs-distributions], and many of these packages will probably make
their way into the default Emacs experience in due time.

But while modern features like built-in LSP support, faster syntax highlighting
(through tree-sitter) and ligature support are still being debated in the
development mailing list, the long running, slow moving train of Emacs has
picked up many interesting passengers.

Emacs as shipped does a lot more than meets the eye, and external package
functionality often partially replicates built in behavior.

Here is a list of useful features in emacs I use regularly that I don't see
mentioned or recommended often online. Guidelines I used to populate this list:

- No packages, *stock Emacs only*.
- No steep learning curves--*learn each feature in under two minutes or bust*.
- *No gimmicks*. No doctor, tetris, snake, dunnet, zone or butterfly.
- *Just the deltas*: no commonly mentioned packages like flymake, doc-view,
  outline-minor-mode or eww/w3m. Nothing that Emacs brings up automatically or a
  nonspecific Google search gets you.
- Assume a modern Emacs, 26.3+.

The list is written in the language of Emacs' conventions. If you're new to
Emacs, here's some extra cognitive load for you:

# =M-x= means =Alt+x=, /i.e./ hold down =Alt= and press =x=. =C-x= is Control+x.
# A 'buffer' is a stream of text that may or may not be the contents of a file.
# A 'frame' is Emacs jargon for an application window, a 'window' is a viewport
# (or pane/split) inside an Emacs frame. A frame can have many windows, each of
# which displays a buffer.

| Emacs jargon    | Modern parlance                  |
| =M-x=           | Alt + x                          |
| =C-x=           | Ctrl + x                         |
| Frame           | Emacs window                     |
| Window          | split/pane                       |
| Buffer          | Contiguous chunk of text/data    |
| Active Region   | Text selection                   |
| Region          | Text selection (not highlighted) |
| Face            | Font, color and display properties |

OK? Let's go.

# Make videos using Neil Stephenson's In the Beginning Was the Command Line.
*** Artist mode (=M-x artist-mode=)
Turn Emacs into an Ascii art based paint program. Draw (poly-)lines, rectangles
and ellipses. Fill or spray.

<video style="center" width="700" autoplay loop>
 <source src="/img/artist-mode-demo.mp4" type="video/mp4">
Your browser does not support the video tag.

I'm not much of an (ascii) artist, but I do use =artist-mode= to draw boxes when
writing documentation or READMEs.

*** Pulse (=pulse.el=)
The included pulse library provides functions to flash a region of text. The
most useful general application is to flash the line the cursor is on as a
navigational aid or accessibility feature.

<video style="center" width="700" autoplay loop>
 <source src="/img/pulse-demo.mp4" type="video/mp4">
 Your browser does not support the video tag.

As is the annoying case with many things Emacs though, it provides all the
ingredients and lights the flame but leaves the cooking to you. Here's a simple

#+begin_src emacs-lisp
  (defun pulse-line (&rest _)
        "Pulse the current line."
        (pulse-momentary-highlight-one-line (point)))

  (dolist (command '(scroll-up-command scroll-down-command
                     recenter-top-bottom other-window))
    (advice-add command :after #'pulse-line))

Modify as needed. There's more than one external package
([[https://github.com/Malabarba/beacon][beacon]]) that does this and more, but
=pulse= is just fine.

*** Undo in region (=C-/=)
Limit your undoing to the active region:

# <video style="center" width="700" autoplay loop>
#  <source src="/img/undo-in-region-demo.gif" type="video/mp4">
#  Your browser does not support the video tag.
# </video>


There's nothing to set up or run here. This is the default behavior of undo in

*** Follow mode (=M-x follow-mode=)
Most monitors are much wider than they are tall. Most text files are much longer
than they are wide. That's a problem.

=follow-mode= shows a contiguous buffer paginated across multiple windows. The
cursor flows from one window to the next.

*** Selective display (=C-x $=)
If you code with rigid indentation, you can get a quick overview of your
document with =set-selective-display=. No mucking around with folding,
=outline-= or =hs-minor-mode= regexps.


Call the command with the prefix argument set to the column to hide. Call
without a prefix argument to disable.

*** Pretty symbols (=M-x prettify-symbols-mode=)
This one's mainly for LaTeX users. Display unicode versions of math operators,
greek symbols and more. =M-x prettify-symbols-mode= in a TeX buffer.

#+CAPTION: Before and after enabling =prettify-symbols-mode=

Other major modes will have to define the replacements explicitly to get this
behavior. Example with Python:

#+begin_src emacs-lisp
   (lambda ()
     (mapc (lambda (pair) (push pair prettify-symbols-alist))
           '(;; Syntax
             ("def" .      #x2131)
             ("not" .      #x2757)
             ("in" .       #x2208)
             ("not in" .   #x2209)
             ("return" .   #x27fc)
             ("yield" .    #x27fb)
             ("for" .      #x2200)
             ;; Base Types
             ("int" .      #x2124)
             ("float" .    #x211d)
             ("str" .      #x1d54a)
             ("True" .     #x1d54b)
             ("False" .    #x1d53d)
             ;; Mypy
             ("Dict" .     #x1d507)
             ("List" .     #x2112)
             ("Tuple" .    #x2a02)
             ("Set" .      #x2126)
             ("Iterable" . #x1d50a)
             ("Any" .      #x2754)
             ("Union" .    #x22c3)))))

#+caption: A =python-mode= buffer before and after enabling =prettify-symbols-mode=

(The equivalent in =org-mode= is =M-x org-latex-preview=.)

# *** Rainbow modes (=M-x rainbow-mode=)
# Color  

# There's also =rainbow-delimiters-mode= that colors adjacent parens or brackets
# differently so you can read the nesting, but this is pretty popular.
*** View mode (=M-x view-mode=)
Provide pager-like keybindings. Makes navigating read-only buffers a breeze.
Move down and up with =SPC= and =delete= (backspace) or =S-SPC=, half a page
down and up with =d= and =u=, and isearch with =s=.

This is my preferred way to read code or documents as I can avoid chorded
commands. (Note that =evil-mode= doesn't help here either, since paging is bound
to =C-u/d/f/b=.) To that end I just hook this into =read-only-mode=:

#+begin_src emacs-lisp
(add-hook 'read-only-mode-hook 'View-mode)

This is my favorite feature of the bunch, considering how much time I spend in
Emacs /reading/ things.

*** Cycle-spacing (=M-SPC=)
The =cycle-spacing= command is more versatile than it appears. By default, it
cycles between deleting all whitespace around cursor but one, deleting all
whitespace and restoring whitespace. But with a negative argument, it deletes
all blank lines around the cursor. (Calling it with a negative argument is fast:
Hold down Meta and hit minus and space in sequence.)

Put together, it's doing the job of (almost) three older commands:
=just-one-space=, =delete-horizontal-space= and
=delete-blank-lines=![fn:delete-blank-lines-vs-cycle-spacing] This opens up the
bindings =C-x C-o= and =M-\= for more useful functions.
*** Indirect buffers (=M-x make-indirect-buffer=)
One buffer. Two windows. Two states.

This one's for outline/org users. Do you want to see an overview of your
document /and/ the section you're working on? =M-x make-indirect-buffer= or =M-x

Here I clone an org buffer and narrow the original to get a makeshift TOC:

At this point we're a few lines of elisp away from writing a =toc-minor-mode=
for org files!

But the possibilities are much larger, because as the manual puts it:
The text of the indirect buffer is always identical to the text of its base
buffer; changes made by editing either one are visible immediately in the other.
But in all other respects, the indirect buffer and its base buffer are
completely separate. They can have different names, different values of point,
different narrowing, different markers, different major modes, and different
local variables.

*** Html-fontify (=M-x html-fontify-buffer=)
Reproduce the look of your emacs buffer as a html file with CSS. This is either
extremely useful or useless to you!

[[/share/htmlfontify-demo.html][Here]] is the html-fontified version of the
source file of this write-up.

*** DWIM commands (upcase, downcase  etc)
Modern versions of Emacs provide Do-What-I-Mean versions of various editing
commands: They act on the region when the region is active, and on an
appropriate semantic unit otherwise. Replace =upcase-word= and =downcase-word=
with =upcase-dwim= and =downcase-dwim= respectively, and you can safely eject
the bindings for =upcase-region= and =downcase-region=.[fn:graybeard-warning].

#+begin_src emacs-lisp
(global-set-key (kbd "M-u") 'upcase-dwim)
(global-set-key (kbd "M-l") 'downcase-dwim)

DWIM is standard behavior for emacs commands even when it doesn't say that in
the name. =count-words=, =query-replace=, the list goes on. Check to see if your
frequently used commands DWYM.

*** Unit conversion in calc (=M-x calc=)
It's =u c=. And ='= (quote) for algebraic entry: [[/img/calc-units-demo.gif]]
=calc= does a lot more with units. You can simplify, define new unit conversions
and more. Hit =u ?= to see your options.

*** Symbolic computation in calc (=M-x calc=)
We're skirting the "*learn each feature in under two minutes or bust*" rule with
this one, as it deserves its own write-up, or a perusal of the manual. The
general interaction paradigm is simple, though.

Let's find a Taylor expansion of the integral of the error function:

Access algebraic routines (root finding, symbolic manipulation) in calc under
the =a= prefix. Indefinite integration is =a i=, differentiation is =a d=,
solving algebraic equations is =a S= and so on. (Hit =a ?=)

*** Scroll lock mode (=scrollock=)
What it says on the tin. Move the buffer instead of the cursor when navigating.
Just press the scroll lock key or =M-x scroll-lock-mode=.

*** Tabs (=M-x tab-bar-mode=)
These are mentioned often, but rarely recommended. Most Emacs users find the
idea of tabs in Emacs to be redundant, but will happily recommend window
configuration registers, which provides similar functionality.

Tabs work great to separate projects, or work and email buffers. In principle
this is equivalent to popping up a new frame and letting the window manager
handle the separation, but on stacking window managers I find tabs to be much

Since there's never one way to do something in Emacs, a secondary
=tab-line-mode= is available that adds tabs to each window instead of frame.

*** Next time:
- =icomplete= and =fido=: Incremental completion systems
- =completion-styles=: Supercharge completion in the minibuffer
- =re-builder= and =rx=: Visual regular expressions
- =orgtbl-mode=: Easy table formatting everywhere
- =strokes-mode=: Control emacs with mouse gestures

... and more.
*** TODO Icomplete and Fido (=M-x icomplete-mode=, =M-x fido-mode=) :noexport:
Improves the other half of the default minibuffer experience: interacting with
selection candidates. The default completions buffer is too many key presses
away. =fido-mode= is Emacs 27+ only.

Of course, =ido= is also built in, but you know all about it.
*** TODO Minibuffer completion styles :noexport:
The default minibuffer experience is annoying enough to send anyone into the
arms of =ido=, =ivy= or =helm=. But Emacs does a lot better in the
tab-completions department than it lets on. The minibuffer can match by
substrings, regexps, initials and even (as of Emacs 27+) fuzzily, and it can do
all of them at once if you don't mind a giant pile of matches.

*** TODO Orgtbl minor mode (=M-x orgtbl-mode=) :noexport:
Org-mode is its own thing, a full fledged notetaking, publishing,
literate-programming, task tracking application with a growing ecosystem that's
parallel to Emacs'. But it does provide one handy tool that's useful everywhere:
Making tables.

With some work, you can export the table in place to html or LaTeX, but setting
this up would break the 3 minute rule. You can also use it as a spreadsheet,
which is beyond me.
*** TODO =re-builder= and =rx= :noexport:
*** TODO =newsticker= :noexport:
*** TODO Strokes (=M-x strokes-mode=) :noexport:
*** TODO Extra :noexport:
Another knock against Emacs is the old adage: good OS, needs an editor. I use
=evil-mode= myself but over a decade of working with the Emacs editing model
I've found this to be largely untrue. Emacs editing can be blazing fast and
efficient with just a few editing commands.