UP | HOME
Impaktor

Impaktor

Inject Emacs intravenously

My .emacs
Published on Jun 08, 2021 by Impaktor.

bitches-dont-know-emacs.jpg

Figure 1: Chad warning!

With great power comes great responsibility

Peter Parker

1. A Few Words

Emacs was created in 1983, as “Editing MACroS” for the MIT AI-lab’s editor named TECO (“Text Editor and COrrector”). (See pdf 2020 for history).

So many people found the macro innovations useful and had incorporated it into their own TECO programs that the TECO editor had become secondary to the macro mania it inspired. “We started to categorize it mentally as a programming language rather than as an editor,” Stallman says. Users were experiencing their own pleasure tweaking the software and trading new ideas

[…]

In the course of developing a standard system of macro commands, Stallman and Steele had to traverse a political tightrope. In creating a standard program, Stallman was in clear violation of the fundamental hacker tenet-“promote decentralization.” He was also threatening to hobble the very flexibility that had fueled TECO’s explosive innovation in the first place.

“On the one hand, we were trying to make a uniform command set again; on the other hand, we wanted to keep it open ended, because the programmability was important,” recalls Steele.

To solve the problem, Stallman, Steele, and fellow hackers David Moon and Dan Weinreib limited their standardization effort to the WYSIWYG commands that controlled how text appeared on-screen. The rest of the Emacs effort would be devoted to retaining the program’s Tinker Toy-style extensibility.

from chapter 6 of O’reilly and “Emacs the Full Screen Editor” (1987).

My emacs configuration file, consisting of various hacks, some copy pasted, others modified/written by me. Much taken from emacs-fu, emacs rocks, and emacswiki]]. Note that most of the descriptions/explanations to the code are in the code blocks as comments. For learning lisp, structural interpretation of programs (SICP) is considered the “bible” (there are also pdf]] and lecture videos), although Scheme dialect differs from elisp, it’s similar in concept. There’s also an introduction elisp here.

I’m using varius other modes (file.el-files) that I have in my load-path. I’ll link to the source where possible. (Almost?) all are available through emacs wiki or the emacs package mannager, (the built, elpa, or el-get)

Experts use Emacs:

Emacs and Vim users significantly outperform the users of other editors in their interviews. Emacs users performed over twice as well as its nearest competitor.

Those who are concerned enough about efficiency and creating workflows that are as frictionless as possible tend to choose the best tools possible—not the prettiest ones—and be willing to put in the time to master their them.

From http://irreal.org/blog/?p=7675

There are few pieces of software as widely misunderstood as Emacs. Emacs is frequently advertised and discussed as a text editor, but please be clear on this: Emacs is not just a text editor.

Emacs is a platform for developing end-user applications with a text-based core. This idea of a text-based core is something I’ll return to in a later article when I get the time. It’s a brilliant idea, and certainly not unique to Emacs.

From (good read): https://two-wrongs.com/why-you-should-buy-into-the-emacs-platform

editor_performance.png

Figure 2: Performance of interview subject, shown for which editor they preferred

https://triplebyte.com/blog/editor-report-the-rise-of-visual-studio-code

Hacker News - Resources to grok Emacs and use it well?

(Any vim user might want to read From Vim to Emacs in Fourteen Days)

Table of Contents

1.1. Emacs keybindings   KEY BINDINGS KEYBINGDINGS SHORTCUTS

The underlying rationale of Emacs keybindings might at first glance seem incomprehensible, but there is a clear and simple logic behind them, as outlined in the Key-Binding-Conventions, and as summarized in this reddit post. Most importantly to remember:

  • C-x reserved for Emacs native essential keybindings: buffer, window, frame, file, directory, etc.
  • keys <F5>-<F9> reserved for user.
  • C-c reserved for user and major mode:
    • C-c <letter> reserved for user.
    • C-c C-<letter> reserved for major mode.
    • C-c <{,},<,>,:,;}> reserved for major mode.
    • C-c <other ASCII punctuation> reserved for minor (and/or major) modes
  • Don’t rebind C-g, C-h and ESC.

You can allways see which function (and its documentation) a sequence is bound to by prefixing it with C-h k (“help key”), in the same way you get help for functions or variables with C-h f, or C-h v, respectivley. C-h b runs describe-binding which is also pretty awseome, as it lists all keys currently bound in the buffer/mode you’re in.

When using the kbd macro, all function keys and directinal keys must be enclosed in “<>”, like so: <f5>, <home>, <next>, <left>. This is not needed for normal keys like C-c e is: (kbd “C-c e”)

see: mastering emacs

Also, it’s seriously recommended to remap Ctrl to some more sane key, usually to capslock, as this key is worthles (Emacs has M-u, M-l, M-c for upper, lower, and capitalize letter, respectively).

1.1.1. help keys

Emacs is self documenting, and all documentation/help starts with the key C-h. C-h r brings up the Emacs manual, and C-h i brings up the info index. M-x info-display-manual is an easy way to get to the right section (with tab completion) in the info manual.

C-h k <key sequence> is excellent when ever I want to know what function a <key sequence> is bound to.

Table 1: Help keys
Key Action
C-h i info manual
C-h r Emacs section of the info manual
C-h k describe-key
C-h f describe-function
C-h c describe-command
C-h v describe-variable
C-h a describe-apropos (search)
C-h m list all keys assoiciated wth current modes.
C-h n list all news in this version of emacs.
C-h e show Message buffer (echo area)
prefix C-h list all keys belonging to the prefix,
C-x r C-h example of above code. List all keys with that prefix

Furthermore, to find relevant elisp source code there are several very useful functions:

  • M-x find-library
  • M-x find-function
  • M-x find-variable
;; bind useful function to C-h C-l, and C-h C-i
(define-key 'help-command (kbd "C-l") 'find-library)
(define-key 'help-command (kbd "C-i") 'info-display-manual)

1.1.2. basic usage

For hard-core navigation using just the emacs way, remove arrow keys by evaluating: (mapc 'global-unset-key [[up] [down] [left] [right]])

Table 2: Basic emacs keys
Key Action
C-g Most important key: abort/escape. When ever in doubt: C-g
C-x h mark whole buffer
   
C-x u undo
C-_ undo
   
M-u convert whole word in front of point to upper case
M-l convert whole word in front of point to lower case
M-c convert character infront of point to upper case
   
C-t transpose characters i.e. ab -> ba
M-t transpose word i.e. abc def -> def abc
C-x C-t transpose lines
   
C-M-[N] N = number, sending a number as arg. to command.
C-[N] Same as above.
M-[N] Same as above.
   
M-- invert following command. e.g. M– M-l “lower case backward”

1.1.3. basic cursor movement and editing

Table 3: Movement and editing
Key Action
C-a Move to beginning of line
C-e Move to end of line
   
M-a Move to sentence beginning
M-e Move to sentence end
   
C-k Kill Line from point
C-S-BKSPC Kill whole Line
   
M-q fill paragraph (i.e. break paragraph in hard line breaks)
C-x f set fill column (how many columns a line is before line break)
   
C-up move up paragraph/code block
C-down move down paragraph/code block
C-left same as M-b (backward word)
C-right same as M-f (forward word)

1.1.4. basic scrolling in buffers

Table 4: Buffer scrolling
Key alt key Action
C-v PgDwn page down
M-v PgUp page up
M-PgD   page down in other window (if buffer split in two)
M-PgUp   page up in other window (if buffer split in two)
     
C-M-S-v   scroll other buffer up
C-M-v   scroll other buffer down
     
C-l   toggle between marker in center, top or bottom of screen.
M-C-l   toggle marker to context (e.g. try it when in a function)
     
M-< C-HOME Move to top of buffer
M-> C-END Move to end of buffer

1.1.5. registers and rectangular marking / editing

Set mark at upper left corner, and then lower right then do any of the following, (except for C-x r y no marking is needed):

GNU-manual

Table 5: Register / rectangular regions
Key Action
C-x r k kill text (save to “last killed rectangle”)
C-x r d Delete the text of the region-rectangle
C-x r y Yank the last killed rectangle with its upper left corner at point
C-x r t str Replace rectangle contents with string on each line
C-x r N Insert line numbers along the left edge of the region-rectangle.
   
C-x r o Insert blank space to fill the space of the region-rectangle
C-x r c Clear the region-rectangle by replacing all of its contents with spaces
Table 6: save rectangular region
object store retrieve notes
normal region C-x r s R C-x r i R save region (selection) into register R /insert R
rectangle region C-x r r R C-x r i R save rectangle into register R (see working with rectangular selections, and insert it);
buffer/position C-x r <SPC> R C-x r j R save buffer/position in register R, and jump back to it
window C-x r w R C-x r j R save window configuration in register R, and jump back to it. Note that what emacs calls a window is called a window pane elsewhere, see emacs terminology)
frame C-x r f R C-x r j R save frame configuration in register R, and jump back to it. Note that what emacs calls a frame is called a window elsewhere, see emacs terminology

Alternatively there’s the cua-mode rectangles, with useful functions: cua-sequence-rectangle (M-n, when the region is active) which asks for start value and increment, and format.

1.1.6. registers:

By setting registers one bookmarks a line in a file (C-x r SPC 42), so that one can easily return/jump to it at a later point (C-x r j 42).

With registers you can also copy text into multiple “slots”, and retrieve them.

Key Action
C-x r SPC set register mark (with a number)
C-x r j jump to register mark (with a number)
   
C-x r s save selection to register
C-x r i load selection from register
   
C-x r m add bookMark
C-x r b visit bookmark
C-x r l list bookmarks

1.1.7. font-size

C-x C-+ Increase font size C-x C– Decrease font size

1.1.8. search and replace   SEARCH REPLACE

A blog post on search & replace

Powerful:

  • M-x occur (search in buffer, ’e’ to enter edit mode, C-c C-c to commit)
  • M-x multi-occur (searches in many buffers, ’e’ to edit, same as occur)
  • M-x multi-occur-in-matching-buffers
  • M-x list-matching-lines
Table 8: Search and replace
Key Action
C-s searach forward
C-r search backward
   
C-M-s regexp searach forward
C-M-r regexp search backward
   
M-s . search symbol under cursor. Note: if “foo”, will not match 1foo2
M-s w search word, ignore underscore, hyphen or space
   
M-% query replace (i.e. search and replace)
  y or SPC replace this
  n or DEL don’t replace
  q or RET quit replace
  ! replace all occurrences
  . replace this and exit
   
M-C-% query replace regexp
   
M-s o occur: similar to grep. Show hits in separate buffer, with
  syntax highlighting preserved. (r in occur-buffer renames it)
  Lines can be edited in place(!) in the occur buffer, with ’e’
  M-g M-n move next hit from source buffer
  M-g M-p move prev hit from source buffer
  C-c C-f toggle follow mode on/off
  C-c C-c save changes made in edit mode of occur-buffer
   
  g rerun/re-read in dired, compile, occur, grep buffers.
  Can be started from within isearch with M-s o!
Table 9: While searching (in minibuffer):
Key Action
C-w add word at point to search
C-y yank/paste into minibuffer
M-e edit search entry in mini-buffer
M-c toggle case sensitivity
M-r regexp
M-SPC Match spaces
C-s repeat most recent search
M-n next search in history
M-p previous search in history

1.1.9. Emacs window frames

Table 10: Splitting / moving between Emacs panalized
Key Action
C-x 0 undo previous window split
C-x 1 one window
C-x 2 split window horizontally
C-x 3 split window vertically
C-x + Balance window (same size)
C-x o jump to other window

1.1.10. Keyboard macros!

The Power! To record and play back keyboard sequences. Awesome when doing the same thing on data/text with a pattern.

Table 11: Keyboard macros are the shit!
Key Description
C-x ( start (same as F3)
C-x ) stop (same as F4)
C-x e run macro (same as F4)
C-u N C-x e repeat N number of times
C-u 0 C-x e repeat until end of buffer is reached (macro must reach the end, else C-g).
C-x C-k r apply macro to each line in region. (macro does not have to move to next line)
C-x C-k n name and save macro (for this emacs session) use again with M-x name-of-macro
C-x C-k b bind to key, reserved by default: C-x C-k [0-9,A-Z]
C-x C-k e edit-kbd-macro: M-x name-of-macro pull upp a buffer where we can edit the macro
   
C-x C-k C-n next in keyboard macro ring
C-x C-k C-p previous in keyboard macro ring
C-x C-k C-k execute / select macro
   
C-x C-k C-c set counter, (set initial state, do before running the macro, default: 0)
C-x C-k C-a N add N to the counter
C-x C-k C-i add counter (adds one to each execution)
C-x C-k C-f set format of counter, default: %d
   
C-x q ask user for input

M-x insert-kbd-macro take a named macro and return elisp code.

1.1.11. Code navigation:

Table 12: Navigate in code
Key Action
C-M-a Move to start of function
C-M-e Move to end of function
   
C-M-f Move one syntax forward. i.e. jump to matching closing parenthesis/bracket/quote
C-M-b Move one syntax backward. i.e. jump to matching opening parenthesis/bracket/quote
   
M-m back to indentation (like doing C-a M-f)
   
C-M-u move up in hirarcy/list
C-M-d move down in hirarcy/list
   
C-up move up paragraph/code block
C-down move down paragraph/code block
C-left same as M-b (backward word)
C-right same as M-f (forward word)
   
M-; comment/uncoment region, or insert comment to the right if no active region

Note: to treat camelCased words as two, set M-x subword-mode

1.1.12. Goto line:

Table 13: line navigation
Key Action
M-g g goto line
M-g M-g goto line
M-g c goto char
M-g TAB goto column
   
M-g n goto next compilation error (next-error)
M-g p goto previous compilation error (previous-error)
   
M-g M-n goto next compilation error
M-g M-p goto previous compilation error

1.1.13. Tags:

Easy navigation in code. This requires that the the command etags *.{h,cpp} has been run, to generate a TAGS file. After this is done you can easily jump from where a function is used to where it’s defined.

M-. goto where it’s definied
M-, goto where it’s used
M-* return to previous position

1.1.14. Other keys

Table 14: Misc
Key Action
C-o insert line above mark
M-q adjust paragraph
M-r move cursor to center of screen
C-l move buffer & mark to center/top/bottom of screen
M-/ dynamic expand (dabbrev-expand).
M-= count words

1.2. Useful functions   SEARCH REPLACE

Some stuff I keep handy for myself.

Table 15: Useful functions for Searching
key action
M-x list-matching-lines useful for searching one buffer
M-x grep -nH -e useful for searching dired of files
M-x grep-find for recursive searching through folders
M-x occur Can edit with e in emacs 24.1
M-x multi-occur  
Table 16: Misc
key action
M-x locate-library Where is that damn elisp-file?
M-x check-paren For finding unmatched parenthesis:
M-x phase-of-moon For gigs and laughs
M-x butterflies For gigs and laughs
M-x re-builder regexp-builder
C-u 0 M-x byte-recompile-directory recursive bytecomp. all files and subfolders

1.3. Compile Emacs from source   COMPILING

Extract source to build directory somewhere, then:

./configure  --prefix=/home/usr \
--without-tiff --without-toolkit-scroll-bars --without-gconf \
--without-gsettings --with-gif=no  --with-xft

(I also used to have

--with-x=no --with-x-toolkit=no

when I had GTK2, or otherwise it would kill my emacs server when GTK2 crashed. Not need now.

or for running just in terminal, make it even smaller, no images, no noth’n:

./configure  --prefix=/home/me/usr --without-tiff --without-toolkit-scroll-bars --without-gconf --without-gsettings --with-gif=no  --with-xft --without-gif --without-jpeg --without-png --without-xpm --with-gnutls=no

(run make distclean if I need to reconfigure.) Then compile, test run and install:

make
src/emacs -Q
make install

Problem with w3m? Install from el-get.

1.4. emacs regexp   REGEXP

The following copied from effective-emacs

  • You need to double-escape (“\\”) regexp metacharacters in strings in elisp code, but you single-escape them when entering regexps at the minibuffer.
  • Emacs code does so much matching of parens that Emacs regexps reverse the paren character and metacharacter. In an Emacs regexp, “(” and “)” match actual parens, while “\(" and "\)” create matching groups.
  • In the replacement string, use \1, \2, etc. for inserting match-groups from the regexp.
  • If you enter in a regexp and it doesn’t work, undo the result if the command actually changed anything. Then type the command again, and when it prompts you, use the arrow keys to scroll up and down to find your regexp and replacement string, and modify them in place. This can save you a lot of typing and frustration.
  • You can yank text into the middle of a regexp you’re typing out with most regexp commands, but NOT in the isearch-*-regexp commands. Yank does weird things in those. I’d love to know how to fix this.

2. INITIALIZATION

Must set up paths (load-path) for lisp-files first. This is the most important line, and should be at the top of any configuration file.

“custom-file” hack was taken from here.

Neat note: emacs has a built in profiler, M-x profiler-start, M-x profiler-report.

Note: M-: evaluates code. Write in variables here to check what their value is. (or use scrach buffer for same thing, and C-x C-e at end of name)

;; -*- emacs-lisp -*-
;; Time-stamp: <Last changed 2012-11-30 19:31:12 by Art Vandelay, vandelay>
(message "Reading configuration file...")

;; speeds up loading time, by increasing garbage collection buffer to 100MB
;; https://www.reddit.com/r/emacs/comments/3kqt6e/2_easy_little_known_steps_to_speed_up_emacs_start/
(set gc-cons-threshold 100000000)       ; default: 800k

;;Initialize files----------------------------
;; Where to find external lisp-files, for modes, etc. I put my *el
;; files in "~/.emacs.d/elisp/" where ~/.emacs.d/ is the
;; user-emacs-directory
(add-to-list 'load-path (expand-file-name "elisp" user-emacs-directory))
;;--------------------------------------------

;; For the built in customization UI in emacs that no one uses. If
;; some package tries to use it, at least have the decency to keep
;; this config file clean.
(setq custom-file "~/.emacs.d/custom.el")
(load custom-file 'noerror)

2.1. Message buffer

Have this in the beginning of .emacs, to see which libraries are loaded on start up. Change as much as possible to auto-load.

;;keep message buffer complete.
(setq message-log-max t)

3. PACKAGE MANAGEMENT

3.1. package management

From masteringemacs.org “By default, all installed packages are loaded and activated automatically when Emacs starts up. To disable this, set `package-enable-at-startup’ to nil. To change which packages are loaded, customize `package-load-list’.”

Update list: M-x package-refresh-contents Open list: M-x package-list-packages

Table 17: Keys in package-list.
key descirption
U Update all installed
? info on package
h help: show keys in minibuffer

You can pinn (short version) packages allowing emacs which repository to use for a certain package.

Regarding which repositories to use ELPA is the original one, but no longer maintained; GNU is the official maintained one and should always work, but isn’t updated that often. Marmalade is a repo where you can upload packages, and what the community is most hopeful about. It was unmaintained a recent while, but is back on track. Melpa builds packages automatically from URL’s from github or emacswiki, so it’s never more than 1 day behind the repositories it tracks, and is surprisingly stable. Melpa stable tracks fewer packages, and has a time lag, to allow for bugfixes in the upstream repositories.

;; Note: Don't (require ...) packages prior to loading them with the
;; emacs package system ("elpa"), as it is not meaningful, doesn't
;; serve any purpose, nor semantically correct. Packages loaded in the
;; package system are autoloaded when visiting files where they're
;; needed (if well written).

(require 'package)

;; Since emacs 24 there's a very neat package system.
(when (>= emacs-major-version 24)
  (setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
                           ("melpa" . "http://melpa.org/packages/")
                           ("melpa-stable" . "http://stable.melpa.org/packages/")
                           ("org" . "https://orgmode.org/elpa/")
                           ;;; Old, and no longer maintained:
                           ;;("ELPA" . "http://tromey.com/elpa/")
                           ;;("marmalade" . "http://marmalade-repo.org/packages/")
                           )))
;; packages are now loaded before reading configuration file
(when (< emacs-major-version 27)
  (package-initialize))

3.2. pinn package source

If a package is available in multiple archives, we can set which ones to use for which package. I’m not using this, but might be useful.

;; Check if we're on Emacs 24.4 or newer, if so, use the pinned package feature
(when (boundp 'package-pinned-packages)
  (setq package-pinned-packages
        '((smex               . "melpa-stable")
          (zenburn-theme      . "melpa-stable") ; a nice theme
          (anti-zenburn-theme . "melpa-stable") ; a nice theme (brighter)
          (zen-and-art-theme  . "marmalade")    ; a nice theme (darker)
          ;;(htmlize            . "marmalade")
          ;;(rainbow-delimiters . "melpa-stable")
          ;; "unstable" package
          ;;(icicles            . "melpa")
          )))

3.3. Package auto-install

If running emacs on a new computer for the first time, then auto-install my packages. Source: stackoverflow.

Note: there is a package that does use same, that’s called use-package, which is very popular, but I want to see the nuts and bolts, so I prefer this way.

;;Auto-install missing packages ---------------

;; packages I use all the time, which _must_
;; be installed on all my emacs-machines:
(setq my-must-have-packages
      '(auctex                          ; a must for LaTeX
        avy                             ; awesome for jumping / navigating cursor on screen
        anzu                            ; better isearch/regex-search/replace (count matches)
        bbcode-mode                     ; for editing forum-posts
        beacon                          ; show whre the cursor is when jumping between buffers & frames
        blacken                         ; for auto refactoring python code
        browse-kill-ring                ; a must! C-y (and M-y) on steroids!
        cider                           ; clojure environment ("M-x cider-jack-in" when visiting file)
        cmake-mode                      ; for CMake files
        color-theme-sanityinc-tomorrow  ; blue version is nice (doesn't need the old color-theme package)
        command-log-mode                ; log pressed keys to buffer (e.g. useful for presentations)
        company                         ; for auto-complete variables/functions (with drop down menu)
        company-quickhelp               ; adds documentation string in the autocompletion window
        company-auctex                  ; auto-complete for latex
        company-jedi                    ; auto-complete for python (requires python-jedi installed)
        counsel                         ; part of the swpier/counsel/ivy trifector of power
        cython-mode                     ; for cython high lighting + C-c C-c for compile
        dtrt-indent                     ; awesome: automagically guess indentation style of file
        dired-filetype-face             ; set different faces in dired based on filetype
        define-word                     ; M-x define-word at point
        dictionary                      ; to lookup words
        diminish                        ; suppress/shorten mode line mode indicators
        dockerfile-mode                 ; syntax highlighting for "Dockerfile"
        elfeed                          ; RSS reader
        erc-hl-nicks                    ; colour names on IRC
        eww-lnum                        ; number links in EWW, like in Conkeror
        ;;emms                          ; emacs multimedia system
        ;;emms-player-mpv
        ;;ess                           ; Emacs Speaks Statistics, for R-mode
        flycheck                        ; check code sanity while I type
        geiser                          ; the Scheme lisp mode providing REPL, etc.
        ;;git-gutter-fringe             ; show +/- in left fringe for changes in git controlled file
        gnuplot                         ; gnuplot-mode
        gnuplot-mode                    ; for org-babel-gnuplot
        git-timemachine                 ; m-x git-timemachine, n/p to navigate history
        goto-chg                        ; navigate in buffer by using undo-history
        pkgbuild-mode                   ; for arch linux build scripts
        graphviz-dot-mode               ; because syntax highlight in graphviz scripts is nice
        green-phosphor-theme            ; a color theme, as the name suggests
        htmlize                         ; render current buffer face and syntax highlight to html
        ivy                             ; part of the swpier/counsel/ivy trifector of power
        lua-mode                        ; at least gives syntax highlight for Lua-code
        magit                           ; powerful git-interface
        material-theme                  ; fancy schmancy theme with some cleverness, apparently
        matlab-mode                     ; yuck! when you must, you must
        markdown-mode                   ; markdown-mode for github posts
        mediawiki                       ; mode for editing mediawiki-buffers
        ;;multiple-cursors                ; a lightweight, more interactive complement to keyboard macros
        nov                             ; epub reader/renderer
        calendar-norway                 ; add norwegian holidays
        org                             ; use a more recent than default emacs
        ob-ipython                      ; org mode babel for ipython + jupyter kernels
        ox-mediawiki                    ; org mode exporter for mediawiki, needs a (require ..) as well
        ox-gfm                          ; org mode exporter for github flavour markdown
        paredit                         ; excellet for lisp, but steep lerning, for parenthesis manegement
        pov-mode                        ; for editing pov-ray files, (raytracer)
        ;; pylint                          ; python lint checker, (combine with configuration for less verbose)
        pydoc                           ; syntax highligted python documentation
        pkgbuild-mode                   ; For arch linux PKGBUILD scripts
        rainbow-mode                    ; Colour hex rgb values, e.q. "#00ff00" in it's colour
        ;;slime-company install in quicklisp?
        ;;slime                           ; NOTE: install this through quicklisp instead!
        ;;smartparens                   ; better parenthesis management: insert/delete/replace pairs
        smex                            ; smarter "M-x"
        synosaurus                      ; Synonym lookup tool, e.g. for wordnet
        sml-modeline                    ; I use it to replaces scrollbar, show info in modeline instead
        stumpwm-mode                    ; I'm not actually using this, but for my WM
        undo-tree                       ; neat but a bit complicated way, of getting all undo-history
        volatile-highlights             ; slightly shade just pasted region
        ;;wanderlust                      ; email-client
        which-key                       ; smarter when half finished key combo
        with-editor                     ; make emacs default $EDITOR
        yasnippet                       ; auto-complete templates (e.g. if, for, do ...)
        yasnippet-snippets              ; yasnippet no longer comes with the actual snippet library, need this
        yaml-mode                       ; yaml mode, good for configuration files
        zenburn-theme                   ; low contrast theme
        ))

;; install any packages in my-must-have-packages,
;; if they are not installed already
(let ((refreshed nil))
  (when (not package-archive-contents)
    (package-refresh-contents)
    (setq refreshed t))
  (dolist (pkg my-must-have-packages)
    (when (and (not (package-installed-p pkg))
               (assoc pkg package-archive-contents))
      (unless refreshed
        (package-refresh-contents)
        (setq refreshed t))
      (package-install pkg))))

(defun package-list-unaccounted-packages ()
  "Like `package-list-packages', but shows only the packages that
  are installed and are not in `my-must-have-packages'.  Useful for
  cleaning out unwanted packages."
  (interactive)
  (package-show-package-list
   (remove-if-not (lambda (x) (and (not (memq x my-must-have-packages))
                                   (not (package-built-in-p x))
                                   (package-installed-p x)))
                  (mapcar 'car package-archive-contents))))
;;---------------------------------------------

4. THEMES & (NO)TOOLBAR

Set theme so emacs doesn’t hurt my eyes anymore.

Sample Gallery of popular emacs theme can be seen on github.io/emacs-theme-gallery and emacsthemes.com.

Useful tip for the hacker: If you see some text that has some unexpected color, and you wonder why that is, move the cursor there, and call M-x describe-face.

Prior to emacs 24, one used the color-theme package to theme emacs (all themes prefixed with color-theme-...). However, since Emacs 24 a native theme system is now included. For the old color-theme packages converted to the new system check out this link.

4.1. For Emacs 24: Choose theme

Wombat is nice. Or zenburn, (there’s an older alternative version by emacs-fu, but out of date now).

M-x customize-themes lists custom themes which can be enabled. Unlike just doing repeated M-x load-theme this actually unloads the previous one, so good for resetting, thus no lingering colors from previous theme. Note that emacs looks in custom-theme-directory followed by a built-in theme directory named “themes/” in data-directory.

;; Where to find Emacs24 themes for M-x load-theme
(when (>= emacs-major-version 24)
  ;; only if not installed through MELPA:
  (add-to-list 'custom-theme-load-path "~/.emacs.d/themes")

  ;;(load-theme 'sanityinc-tomorrow-blue t nil)
  ;; (load-theme 'material t)              ; a very fancy theme with bells and whistles
  (load-theme 'zenburn t nil))

4.2. For pre-Emacs 24: Choose theme

This chooses the theme for the emacsclient daemon depending on if I attach to it using

(when (require 'color-theme nil 'noerror)
  (setq color-theme-is-cumulative nil)

  ;;if using daemon mode / emacsclient
  (defun mb/pick-color-theme (frame)
    (select-frame frame)
    (let ((color-theme-is-global nil))
      (if (window-system frame)
          (cond ((require 'zenburn nil 'noerror)
                 (message "Choosing color theme zenburn.")
                 (color-theme-zenburn))
                (t
                 (message "Cant find zenburn, inverting face.")
                 (invert-face 'default))))))
  (add-hook 'after-make-frame-functions 'mb/pick-color-theme)

  ;; For when started with emacs or emacs -nw rather than emacs --daemon
  (let ((color-theme-is-global nil))
    ;;(color-theme-initialize)              ;;what is this? Do I need it?
    (if window-system                       ;;if running in x...
        (if (require 'zenburn nil 'noerror) ;;..and if we find color theme
            (eval-after-load "color-theme"
              '(color-theme-zenburn))       ;;...load it. (why must it be "eval-after-load"?)
          (invert-face 'default)))))        ;; if in x, but no theme, invert colors.
;;---------------------------------------------

4.3. TODO Graphical environment, X11 vs CLI

Find out if we are in tty or graphical environment, and set pertinent variables. This worked well, until I started using emacsclient (as server) instead of emacs. Thus the commented region.

;;--------------------------------------------
(tool-bar-mode -1)                        ;;never have a retarded tool-bar at top
(menu-bar-mode -1)                        ;;never have a retarded menu-bar at top
(scroll-bar-mode -1)                      ;;never have a retarded scrill-bar at side
(setq-default indicate-empty-lines t)     ;;show (in left margin) marker for empty lines

;;NOTE: not good when in daemon mode...
;; (cond ((eq window-system 'x)
;;        ;;Put properties for emacs in Xorg here:
;;        (message "Running in X")
;;        (setq-default indicate-empty-lines t))
;;       (t
;;        ;; Put properties for emacs in CLI here
;;        (message "Running in terminal")
;;        ;;(menu-bar-mode 0)
;;        ))
;;--------------------------------------------

4.4. Mode-line

http://www.emacswiki.org/emacs/sml-modeline.el

;;Modline-------------------------------------
(line-number-mode t)                        ;; show line numbers
(column-number-mode t)                      ;; show column numbers
;;(size-indication-mode t)                    ;; show file size (emacs 22+)

;;(when (> (display-color-cells) 16)          ;if not in CLI
(if (require 'sml-modeline nil 'noerror)  ;; use sml-modeline if available
    (progn
      (sml-modeline-mode 1)               ;; show buffer pos in the mode line
      (scroll-bar-mode -1))               ;; turn off the scrollbar
  (scroll-bar-mode -1))                   ;; otherwise, still don't show a scrollbar...
;;--------------------------------------------

5. EMAIL

5.1. Notmuch configuration

Put my configuration in .emacs.d/notmuch-config.el

Stolen configuration from (also has config for org-notmuch): https://wwwtech.de/articles/2016/jul/my-personal-mail-setup

Address autocompletion https://notmuchmail.org/emacstips#index13h2

Video demonstration by project creator https://www.youtube.com/watch?v=pBs_P_1--Os&t=34m35s

Search examples:

tag -inbox before:"1 month ago"
(tag:announce AND (tag:important OR tag:family)) AND NOT tag:foo
*

Note: some flags are special and will be synchronized through maildir: (“draft”, “flagged”, “passed”, “replied”, “unread”). Note: gmail has it’s own “starred” and “important” (latter is set automatically by some algorithm).

There’s also other tags like “replied”, “attachment”, “signed”, “encrypted”, “unread”, “inbox”.

Table 18: Notmuch mode key bindings
Key Function
m start new message
r reply
C-c ? help, in message-mode
a archive, i.e. remove inbox tag, move to next message
* tag all (remove or add)
. v open mail in external browser
   

Send email: install msmtp,

  1. fetch/sync email with mbsync
    • (some have offlineimap running continously in a screen session)
    • others have systemd.timer execute it
  2. tag emails, e.g.

    notmuch tag -inbox +ghc-devs to:ghc-devs@haskell.org tag:inbox
    

    remove inbox tag and add ghc-devs tag of messages found in inbox

    This is typically done through a postsync.sh script, (that mbsync runs?)?

  1. notmuch tag +flagged +bill from:serviziweb@trenta.it tag:inbox

Sending email from gmail using smtpmail (emacs builtin?) http://chrisdone.com/posts/emacs-mail

https://kkatsuyuki.github.io/notmuch-conf/

5.2. Notmuch in .emacs file

As the documentation states, notmuch should be installed through the systems package manager, so that notmuch is in synch with the systems xapian-package.

It is best to use a separate configuration file for notmuch, that is loaded at the end of when notmuch.el is loaded, or else one needs to wrap notmuch configuration in (with-eval-after-load 'notmuch-show ...) calls.

Thus in my ~/.emacs I only have two lines:

;; Make emacs aware of notmuch email client, and put rest of
;; notmuch config in ~/.emacs.d/notmuch-config.el
;;(add-to-list 'load-path "/usr/share/emacs/site-lisp/")
(autoload 'notmuch "notmuch" "notmuch mail" t)

5.3. Notmuch main configuration

Make sure to have /usr/bin/mail, for me, this is provided by s-nail package (Arch Linux).

(message "Loading notmuch-config.el")
(setq

 ;; don't accumulate message buffers after sending/finishing them, kill them
 message-kill-buffer-on-exit t

 ;; message-citation-line-format "On %a, %d %b %Y, %f wrote:"
 message-citation-line-format "On %Y-%m-%d %a, %N wrote:"
 message-citation-line-function 'message-insert-formatted-citation-line

 ;; message-sendmail-f-is-evil nil

 ;; define which mail delivery package I want to use
 mail-user-agent 'message-user-agent

 ;; tell the message mode to derive the envelope address from the From header of the mail
 message-sendmail-envelope-from 'header

 mail-specify-envelope-from 'header
 mail-envelope-from 'header

 ;; is the default:
 ;; message-send-mail-function 'message-send-mail-with-sendmail

 ;; mime-edit-pgp-signers '("C84EF897")
 ;; mime-edit-pgp-encrypt-to-self t
 ;; mml2015-encrypt-to-self t
 ;; mml2015-sign-with-sender t
 ;; notmuch-crypto-process-mime t

 ;; ;;for debug, want the default later: "sendmail"
 ;;sendmail-program "/bin/echo" ;; "~/dev/mail/msmtp-enqueue.sh"

 ;; tells Emacs to report sending errors back to me and not let the MTA take care of this.
 ;; mail-interactive t

 ;; don't show all uninteresting junk-parts of the e-mail:
 ;; notmuch-show-all-multipart/alternative-parts nil

 ;; search newest first
 notmuch-search-oldest-first nil

 ;; prompt for the sender address when composing or forwarding a message
 notmuch-always-prompt-for-sender t

 ;; store them locally, relative to base mail folder.
 notmuch-draft-folder "drafts"

 ;; define indentation for threading
 notmuch-show-indent-messages-width 4)

 ;; Choose FCC header based on regexp on "From" address of current message
 ;; TO-DO: check correct sent folders for gmail
(setq notmuch-fcc-dirs '(("initech.com" . "\"initech/Sent Items\" -unread -inbox +sent")
                         ;;("gmail.com" . "\"gmail/Sent Mail\" "-unread -inbox") ;; using gmailieer
                         ("university.com" . "\"university/Sent\" -unread -inbox +sent")))

(setq sendmail-program "/usr/bin/msmtp")
(setq send-mail-function 'sendmail-send-it)

5.4. TODO notmuch - unused

This is stuff I don’t use, but keeping it for documentation / future exploration:

;; message-mode configuration:
;; from: https://kkatsuyuki.github.io/notmuch-conf/
;; setup the mail address and use name
(setq user-mail-address "Accountname@gmail.com"
      user-full-name "Accountname")

(setq notmuch-hello-hide-tags (quote ("killed")))

;Crypto Settings
;; (add-hook 'message-setup-hook 'mml-secure-sign-pgpmime)
;; (setq epg-gpg-program "/usr/bin/gpg2")

;; add Cc and Bcc headers to the message buffer
(setq message-default-mail-headers "Cc: \nBcc: \n")
;; postponed message is put in the following draft directory
(setq message-auto-save-directory "~/.mail/draft")
;; change the directory to store the sent mail
(setq message-directory "~/.mail/")

;; From anarcat at #notmuch@irc.freenode.net
;; most SMTP servers expect a FQDN on HELO and (system-name) returns
;; only the short hostname since Emacs25, fallback to hostname -f
(when (>= emacs-major-version 25)
  (setq smtpmail-local-domain (car (split-string (shell-command-to-string "hostname -f")))))

5.5. Notmuch - tweaks

Some customization to notmuch. Much copied from the documentation.

;; Warning prompt if text speaks of an attachment and there's nothing attached.
;; gotten from anarcat at #notmuch@irc.freenode.net
(defvar my/notmuch-attach-regex
  "\\b\\(attache\?ment\\|attached\\|jointe?\\)\\b"
  "What is considered a reference to an attachment in an email
  body by the attachment detection hook")

(defun my/notmuch-check-attach ()
  (save-mark-and-excursion ;; this fails somehow: point is at the end of the buffer on error
    (goto-char (point-min))
    (if (re-search-forward my/notmuch-attach-regex nil t)
        (progn
          (goto-char (point-min))
          (unless (re-search-forward "<#part [^>]*filename=[^>]*>" nil t)
            (or (y-or-n-p "Email seem to refer to attachment, but nothing attached, send anyways?")
                (error "No attachment found, aborting")))))))
(add-hook 'message-send-hook 'my/notmuch-check-attach)

;; notmuch hello window, set cursor in first search field, insead of
;; top left corner.
(add-hook 'notmuch-hello-refresh-hook
          (lambda ()
            (if (and (eq (point) (point-min))
                     (search-forward "Saved searches:" nil t))
                (progn
                  (forward-line)
                  (widget-forward 1))
              (if (eq (widget-type (widget-at)) 'editable-field)
                  (beginning-of-line)))))

;; set to pre-version 0.12 behaviour
(define-key notmuch-show-mode-map "r" 'notmuch-show-reply)
(define-key notmuch-show-mode-map "R" 'notmuch-show-reply-sender)
(define-key notmuch-search-mode-map "r" 'notmuch-search-reply-to-thread)
(define-key notmuch-search-mode-map "R" 'notmuch-search-reply-to-thread-sender)
;; Until this becomes the default, does what "=" does:
(define-key notmuch-search-mode-map "g" 'notmuch-refresh-this-buffer)

(setq notmuch-address-save-filename "~/.emacs.d/notmuch_addresses")

;; access these through "j a", or "j i", etc.
(setq notmuch-saved-searches '((:name "all mail" :query "not (tag:draft or tag:sent)" :key "a")
                               (:name "inbox" :query "tag:inbox" :key "i")
                               (:name "unread" :query "tag:unread" :key "u")
                               (:name "flagged" :query "tag:flagged" :key "f")
                               (:name "drafts" :query "tag:draft" :key "d")
                               (:name "sent" :query "tag:sent" :key "t")))

;; toggle deleted tag for displayed message
(define-key notmuch-show-mode-map "D"
  (lambda ()
    "toggle deleted tag for message"
    (interactive)
    (if (member "deleted" (notmuch-show-get-tags))
        (notmuch-show-tag (list "-deleted"))
      (notmuch-show-tag (list "+deleted")))))

;; also work from search buffer
(define-key notmuch-search-mode-map "D"
  (lambda (&optional beg end)
    "mark thread as deleted"
    (interactive (notmuch-search-interactive-region))
    (notmuch-search-tag (list "+deleted" "-inbox") beg end)))

5.6. Message-templ

Allow multiple user profiles. message-templ is found in marmalede repo, and author can be found in #notmuch channel. http://pivot.cs.unb.ca/git?p=message-templ.git;a=blob_plain;f=example.emacs.el;hb=HEAD

(define-key message-mode-map "\C-cs" 'message-templ-select)
(setq message-templ-alist '(("initech"
                             ("From" . "I-Firstname Lastname <firstname.Lastname@initech.com>")
                             (notmuch-draft-folder . "Nothing.To.Hide")
                             (notmuch-fcc-dirs "initech.com" . "\"initech/Sent Items\" -unread -inbox"))
                            ("gmail"
                             ("From" . "G-Firstname Lastname <name@gmail.com>")
                             (notmuch-draft-folder . "Nothing.To.Hide")
                             (notmuch-fcc-dirs "\"gmail/Sent Items\" -unread -inbox"))
                            ("university"
                             ("From" . "T-Firstname Lastname <name@university.com>")
                             (notmuch-draft-folder . "Nothing.To.Hide")
                             (notmuch-fcc-dirs "\"university/Sent\" -unread -inbox"))))

6. RSS/Atom-reader:

6.1. Elfeed RSS Reader

This is a much faster alternative to newsticker, elfeed downloads and manages feeds far better, and it’s built on notmuch / xapian.

“Elfeed maintains a list of arbitrary tags – symbols attached to an entry. The tag unread is treated specially by default, with unread entries appearing in bold.”

M-x elfeed-update

For web browser interface to database at http://localhost:8080/elfeed/ :

M-x elfeed-web-start

(see blog for using “Tiny Tiny RSS” for syncing elfeed between multiple computers)

Useful for soundcloud RSS-feed URLs: http://getrssfeed.com/

Table 19: Elfeed keys
Key Action
g refresh view
G elfeed-update, fetch new feeds from servers
s update search filter
   
b open URL of selected entries in browser
y copy URL of selected entries to clipboard
r/u mark/unmark selected entries as read/unread
+/- add/remove tag to selected entries
= search on the feed’s url or name
@ specify time range
  • Any component of the search string beginning with a + or a - is treated like a tag. + means the tag is required, - means the tag must not be present.
  • A component beginning with a @ indicates a (max) age. E.g. @2-days-old
  • A component beginning with a ! is treated as an “inverse” regular expression. This means that any entry matching this regular expression will be filtered out.
  • A component beginning with a # limits number to show. E.g. #20 shows max 20 entries.
  • A component beginning with a = is a regular expression matching the entry’s feed source (title or URL).
  • E.g. press s, then:

    @6-months-ago +unread
    
  • Or show feeds newer than

    @3-days-ago
    @2018-06-01
    
  • Or show time interval

    @2018-06-01--2018-07-15
    @5-days-ago--1-day-ago
    
(setq elfeed-feeds
      '(("https://www.archlinux.org/feeds/news/" archlinux)
       ("http://www.abandonia.com/en/rss.xml" abandonia retro)
       ;; ("http://www.whdload.de/news.xml" whdload amiga retro)
       ("http://planet.emacsen.org/atom.xml" planetemacsen emacs)
       ("http://pragmaticemacs.com/feed/" pragmatic emacs)
       ;; ("https://feeds.feedburner.com/XahsEmacsBlog" xahlee emacs)
       ("http://rss.slashdot.org/Slashdot/slashdot" slashdot nerd)
       ("http://news.ycombinator.com/rss" hn nerd)
       ("http://www.angryforeigner.net/news?format=rss" angryforeigner eabt politik)
       ;; ("https://argblattetalar.blogspot.com/feeds/posts/default" eabt)
       ;; ("http://www.javligtgott.se/feed/" javligtgott mat)
       ("http://www.smbc-comics.com/rss.php" smbc comic)
       ("https://www.xkcd.com/rss.xml" xkcd comic)
       ("http://laserbrainstudios.com/feed/" laserbrain retro)
       ;; ("http://feeds.bbci.co.uk/news/science_and_environment/rss.xml" sci bbc)
       ("http://emacsrocks.com/atom.xml" emacsrocks emacs)
       ;; ("http://feeds.feedburner.com/blabbermouth" blabbermouth music metal)
       ("https://petterssonsblogg.se/feed/" pettersson politik)
       ("https://bubb.la/rss/nyheter" bubbla nyheter)
       ("https://phys.org/rss-feed/breaking/space-news/space-exploration/" space rymd sci)
       ("http://www.affarsvarlden.se/?service=rss" affarsvarlden ekonomi)
       ("http://www.rssmix.com/u/8264011/rss.xml" kvartal politik)
       ("https://kvartal.se/artiklar/feed" kvartal politik)
       ("http://ledarsidorna.se/feed/" ledarsidorna politik)
       ("http://nyheteridag.se/feed/" ni politik nyheter)
       ("http://samnytt.se/feed/" samnytt politik nyheter)
       ("http://www.friatider.se/rss.xml" ft politik nyheter)
       ;;("http://www.recepten.se/feed/blog_rss2.xhtml" recepten mat)
       ("https://anchor.fm/s/a807b2c/podcast/rss" herrklubben pod)
       ("https://anchor.fm/s/bf2febc/podcast/rss" tyckonom pod)
       ("https://feeds.acast.com/public/shows/sistamaltiden" sista pod)
       ("https://feeds.acast.com/public/shows/panshirikyeyuneamid" panshiri pod)
       ;; Funkar inte av någon anledning
       ;;("http://feeds.soundcloud.com/users/soundcloud:users:763209220/sounds.rss" panshiri pod)
       ("https://25minuter.libsyn.com/rss" 25min pod)
       ("http://feeds.macrovoices.com/MacroVoices" macrovoices pod)
       ("https://feed.podbean.com/smartermarkets/feed.xml" smarter pod)
       ("https://anchor.fm/s/340deeac/podcast/rss" antiloop pod)
       ("http://feeds.soundcloud.com/users/soundcloud:users:251537747/sounds.rss" sannmin pod)
       ("http://feeds.soundcloud.com/users/soundcloud:users:148013457/sounds.rss" mm pod)
       ;; ("http://feeds.soundcloud.com/users/soundcloud:users:404886336/sounds.rss" outsiders pod)
       ("https://feeds.soundcloud.com/users/soundcloud:users:599634777/sounds.rss" pod kung)
       ("http://feeds.soundcloud.com/users/soundcloud:users:60292654/sounds.rss" bp pod)
       ("http://feeds.soundcloud.com/users/soundcloud:users:428642424/sounds.rss" godton pod)
       ("http://feeds.soundcloud.com/users/soundcloud:users:197875983/sounds.rss" dekonstruktiv pod)
       ("https://www.youtube.com/feeds/videos.xml?user=screenjunkies" screenjunkies film youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=gurskit8" northice youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=simonthedragon" simonsmith youtube)
       ;; ("https://www.youtube.com/feeds/videos.xml?user=failarmy" failarmy youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=EnArgBlatteTalar" angryforeigner politik youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=ThuleanPerspective" thuleanperspective politik youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=UCt9FkOndvcBQsGCc3F3K8ew" thuleanperspective politik youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=techguruuk" danwood amiga retro youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=phreakindee" lgr retro youtube)
       ("https://www.youtube.com/feeds/videos.xml?channel_id=UCDJQkQHL7uC1DeiTZdwuCJQ" youtube trumpwave NimblemadmanBob)
       ("https://www.youtube.com/feeds/videos.xml?channel_id=UCTNnTDH_dfQRcaLaR52JY2w" youtube trumpwave DreadIlk)
       ("https://www.youtube.com/feeds/videos.xml?channel_id=UCQmwkvc1eVuIfxjIq6JvWtg" politik hk youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=JordanPetersonVideos" jbp youtube)
       ("https://www.youtube.com/feeds/videos.xml?user=adric22" 8bitguy retro youtube)))

       ;; From https://noonker.github.io/posts/2020-04-22-elfeed/
       (defun yt-dl-it (url)
         "Downloads the URL in an async shell"
         (let ((default-directory "~/Downloads"))
           (async-shell-command (format "youtube-dl %s" url))))

       (defun elfeed-youtube-dl (&optional use-generic-p)
         "Youtube-DL link"
         (interactive "P")
         (let ((entries (elfeed-search-selected)))
           (cl-loop for entry in entries
                    do (elfeed-untag entry 'unread)
                    when (elfeed-entry-link entry)
                    do (yt-dl-it it))
           (mapc #'elfeed-search-update-entry entries)
           (unless (use-region-p) (forward-line))))

       (define-key elfeed-search-mode-map (kbd "d") 'elfeed-youtube-dl)

6.2. Newsticker RSS reader

Newsticker is the built in RSS-reader and Atom aggregator that comes with Emacs. M-x newsticker-show-news. There are two display types, treeview (use multiple split buffers), and plainview (one buffer).

Newsticker provides several commands for reading headlines, navigating through them, marking them as read/unread, hiding old headlines etc. Headlines can be displayed as plain text or as rendered HTML.

Table 20: Newsticker keys
Key Action
N Next, unread
P Previous, unread
n next
p previous
O  
o  
v open in browser
b  
q quit

RSS feeds for youtube channels named say xxx can be gotten through: https://gdata.youtube.com/feeds/api/users/xxx/uploads https://www.youtube.com/feeds/videos.xml?user=xxx

(setq
 ;; newsticker-heading-format "%t"
 ;; newsticker-item-format "%t"
 ;; newsticker-desc-format "%d\n%c"
 ;; newsticker-hide-old-items-in-newsticker-buffer t
 newsticker-html-renderer 'shr-render-region
 ;; newsticker-frontend 'newsticker-plainview
 ;; newsticker-use-full-width nil
 newsticker-treeview-treewindow-width 40
 newsticker-treeview-listwindow-height 20
 newsticker-url-list-defaults nil  ;remove default list (i.e. emacswiki)
 newsticker-retrieval-interval 0   ;don't fetch when I'm not reading RSS
 newsticker-automatically-mark-items-as-old nil
 newsticker-url-list '(
                       ;;("emacs-fu" "http://emacs-fu.blogspot.com/feeds/posts/default" nil nil nil)
                       ;;("abandonia" "http://www.abandonia.com/en/rss.xml" nil nil nil)
                       ("whdload" "http://www.whdload.de/news.xml" nil nil nil)
                       ("arch linux" "https://www.archlinux.org/feeds/news/" nil nil nil)
                       ("Planet Emacsen" "http://planet.emacsen.org/atom.xml" nil nil nil)
                       ("slashdot" "http://rss.slashdot.org/Slashdot/slashdot" nil nil nil)
                       ;;("Jävligt gott" "http://www.javligtgott.se/feed/" nil nil nil)
                       ;;("Kmandla" "http://kmandla.wordpress.com/feed/" nil nil nil)
                       ;;("mojäng" "http://www.mojang.com/feed" nil nil nil)
                       ("SMBC" "http://www.smbc-comics.com/rss.php" nil nil nil)
                       ("xkcd" "https://www.xkcd.com/rss.xml" nil nil nil)
                       ("laserbrain" "http://laserbrainstudios.com/feed/" nil nil nil)
                       ;;("imdb" "http://rss.imdb.com/daily/poll" nil nil nil)
                       ;;("rotten" "https://www.rottentomatoes.com/syndication/rss/top_news.xml" nil nil nil)
                       ;;("BBC World" "http://feeds.bbci.co.uk/news/world/rss.xml" nil nil nil)
                       ("BBC Sci" "http://feeds.bbci.co.uk/news/science_and_environment/rss.xml" nil nil nil)
                       ;;("Coursera" "http://blog.coursera.org/rss" nil nil nil)
                       ;;("stallman" "http://www.stallman.org/rss/rss.xml" nil nil nil)
                       ;;("emacs rocks" "http://emacsrocks.com/atom.xml" nil nil nil)
                       ("endlessparentheses" "http://endlessparentheses.com/atom.xml" nil nil nil)
                       ("space exploration news" "https://phys.org/rss-feed/breaking/space-news/space-exploration/" nil nil nil)
                       ("EABT" "https://argblattetalar.blogspot.com/feeds/posts/default" nil nil nil)
                       ;;("blabbermouth" "http://feeds.feedburner.com/blabbermouth" nil nil nil)
                       ;;("sds" "http://www.sydsvenskan.se/rss.xml" nil nil nil)
                       ;;("di" "http://di.se/rss" nil nil nil)
                       ("affärsvärlden" "http://www.affarsvarlden.se/?service=rss" nil nil nil)
                       ("börspodden" "http://borspodden.se/feed/" nil nil nil)
                       ;;("veckans aktie" "http://feeds.soundcloud.com/users/soundcloud:users:2000425/sounds.rss" nil nil nil)
                       ;;("dividend mantra" "http://feeds.feedburner.com/DividendMantra/" nil nil nil)
                       ("nyheteridag" "http://nyheteridag.se/feed/" nil nil nil)
                       ("samnytt" "http://samnytt.se/feed/" nil nil nil)
                       ("recepten" "http://www.recepten.se/feed/blog_rss2.xhtml" nil nil nil)
                       ;;("Hacker News" "http://news.ycombinator.com/rss" nil nil nil)
                       ("screen junkies" "https://www.youtube.com/feeds/videos.xml?user=screenjunkies" nil nil nil)
                       ("Matte Northice" "https://www.youtube.com/feeds/videos.xml?user=gurskit8" nil nil nil)
                       ("Simon Smith" "https://www.youtube.com/feeds/videos.xml?user=simonthedragon" nil nil nil)
                       ("failarmy" "https://www.youtube.com/feeds/videos.xml?user=failarmy" nil nil nil)
                       ("thuleanperspective" "https://www.youtube.com/feeds/videos.xml?user=ThuleanPerspective" nil nil nil)
                       ("danwood" "https://www.youtube.com/feeds/videos.xml?user=techguruuk" nil nil nil)
                       ("LGR" "https://www.youtube.com/feeds/videos.xml?user=phreakindee" nil nil nil)
                       ;; ("business" "http://www.cnbc.com/id/10001147/device/rss/rss.html" nil nil nil)
                       ;; ("earnings" "http://www.cnbc.com/id/15839135/device/rss/rss.html" nil nil nil)
                       ;; ("economy" "http://www.cnbc.com/id/20910258/device/rss/rss.html" nil nil nil)
                       ;; ("finance" "http://www.cnbc.com/id/10000664/device/rss/rss.html" nil nil nil)
                       ))

7. TOR

Setting up a tor circuit is very easy on arch. simply install package, and add to systemctl.

https://www.emacswiki.org/emacs/ErcProxy

When that is done:

(setq socks-override-functions 1)
(setq socks-noproxy '("localhost"))
(require 'socks)

Also, for the fantastic keyboard driven emacs-like conkeror browser:

session_pref("network.proxy.socks", "localhost");
session_pref("network.proxy.socks_port", 9050);
session_pref("network.proxy.type", 1);
session_pref("network.proxy.socks_remote_dns", true);

8. BUFFERS / SWITCHING

Controlling the buffer behavior.

8.1. Ivy mode

Excellent write up of ivy/counsel/swiper, with gif animations is here, and manual

Important note:

  • M-x -> counsel-M-x
  • C-x C-f -> counsel-find-file? (replaces ido, and ffap)
  • C-s -> swiper (replaces isearch)
  • You still want smex installed, but remove all configuration for it. Ivy will use it to sort command list after use frequency.

But it works fine with other “i-things”, like ibuffer (C-x C-b)

https://oremacs.com/2015/04/16/ivy-mode/

crash with icomplete? iswitchb?

Also note, counsel-find-file replaces the ffap-command (find file or URL), now use C-x C-f M-n instead, since M-n in emacs predicts the future.

Notes on usage:

  • To expand further into a folder when non-unique auto-completion: C-j (or TAB TAB), (ivy-alt-done), as RET will open the marked folder in dired.
  • M-o (ivy-dispatching-done) shows valid actions, is same as RET or C-m (ivy-done) if only one action available.
  • C-M-j (ivy-immediate-done) for exiting with what has been written, useful/needed when using C-x C-f to create a new file, with non-unique start of file name.
  • C-’ (ivy-avy) gives an avy-mode/ace-jump-like jumping to option in list.
  • TODO: when using tramp, how do I get past the “user@host:“ part if I want to edit that? Pressing ‘~’ or ‘/’ switches root foler to home, or root; so that’s one way.
(ivy-mode t)
(setq ivy-use-virtual-buffers nil)
(setq ivy-count-format "%d/%d ")

;; (setq enable-recursive-minibuffers t)

;;(global-set-key (kbd "C-s") 'swiper)
(global-set-key (kbd "M-x") 'counsel-M-x)
(global-set-key (kbd "C-x C-f") 'counsel-find-file)
(global-set-key (kbd "C-h f") 'counsel-describe-function)
(global-set-key (kbd "C-h v") 'counsel-describe-variable)

(define-key minibuffer-local-map (kbd "C-r") 'counsel-minibuffer-history)

;; magit needs this to get full power:
(setq magit-completing-read-function 'ivy-completing-read)

8.2. Revert buffers

If many files changes on disk while emacs has them opened as buffers, we can either revert every buffer independently, or call the command defined below.

(defun revert-all-buffers ()
  "Refreshes all open buffers from their respective files."
  (interactive)
  (dolist (buf (buffer-list))
    (with-current-buffer buf
      (when (and (buffer-file-name) (not (buffer-modified-p)))
        (revert-buffer t t t) )))
  (message "Refreshed open files."))

8.3. Uniquify

When several buffers have the same name, make the name uniqe by including part of path in name.

;;Uniquify-buffers ----------------------------
(when (require 'uniquify nil 'noerror)  ;; make buffer names more unique
  (setq
   uniquify-buffer-name-style 'post-forward
   uniquify-separator ":"
   uniquify-after-kill-buffer-p t       ;; rename after killing uniquified
   uniquify-ignore-buffers-re "^\\*"))  ;; don't muck with special buffers
;;---------------------------------------------

8.4. Auto remove/kill Completion buffer when done

This is my own hack. For a more complete solution there’s popwin-el, which allows C-g to close any pop-up buffer like \*Help\* or \*Completions\* etc.

;;Remove/kill completion buffer when done-----
;;could use ido-find-file instead, since it never uses *Completions*
;;Note that ido-mode affects both buffer switch, &  find file.
(add-hook 'minibuffer-exit-hook
          '(lambda ()
             (let ((buffer "*Completions*"))
               (and (get-buffer buffer)
                    (kill-buffer buffer)))
))
;; TODO: Kill: *dictem buffer*, *Apropos, *Help*
;; kill them when you leave the buffer, like: C-x o
;;--------------------------------------------

8.5. Winner-mode (for window/buffer layout)

Useful to switch between different/previous buffer-layouts, or buffer history, but I don’t actually use this though (Winner-mode is in Emacs since v.20).

There’s also ace-window for moving between many windows.

;;Winner-mode---------------------------------
;; cycle through window layouts/contents
;; winner conflicts with org, use C-c left/right instead
(when (require 'winner nil 'noerror)
  (setq winner-dont-bind-my-keys t)
  (global-set-key (kbd "<C-c left>")  'winner-undo)
  (global-set-key (kbd "<C-c right>") 'winner-redo)
  (global-set-key (kbd "<XF86Back>")    'winner-undo)
  (global-set-key (kbd "<XF86Forward>") 'winner-redo)
  (winner-mode t))
;;--------------------------------------------

8.6. Dired

Dired is the directory view-mode built into emacs. C-x d, or just C-x C-f on a directory. When visiting a file, C-x C-j opens its folder (“dired-jump”).

  • if you want to mark all HTML files, type: “* .”, then type “html”.
  • As described in oremacs, mark the files to operate on, and & will let you execute shell command where * is replaced for list of marked files. E.g.

    tar -czf ~/tmp/path/foo.tar.gz *
    

Tip: w - copies file name (or file names if several marked) to kill ring M-0 w - copies absolute path C-u w - copies path relative to dired buffer

There are many dired hacks

Table 21: Dired keys
Key Command
m mark a file
RET open file/or dir in new buffer
a open file/dir in current buffer
o open file/dir in other window
v visit/open file, in read only mode
n/p next/previous if visiting an image
q close the dir
C Copy file(s)
R Rename (or move) file(s)
D delete file(s)
+ create a new dir
Z compress/decompress the file(s) by gzip
c compress marked files to single tar-archive
   
( toggle between long/short list format
t toggle marked/unmarked
u unmark
U unmark all marked
% m mark by file name extension
% m mark by pattern (regex)
g refresh dir listing
“^” go to parent dir
C-x C-j in a file brings up dired buffer
C-x C-q enter wdired mode
& shell command, where * are the marked files

Other examples:

*.jpg RET

will mark all jpg-files

https://cestlaz.github.io/posts/using-emacs-38-dired/ http://xahlee.org/emacs/file_management.html http://www.emacswiki.org/emacs/DiredTweaks

dired-x is pretty nifty to execute commands on several files. Easier than using find | xargs. Especially when wanting to pass several files (in different folders) to a script, either all at once, or one at a time.

Emacs by default does not delete non-empty dir. To set it to do so, put the following in your emacs init file:

;;Dired-Stuff----------------------------------
;;Dired is emacs own file manager. Allow dired to be able to delete or
;; copy a whole dir. "always" = no asking. "top" = ask once. Any
;; other symbol means ask each and every time for a dir and subdir.

(eval-after-load "dired"
  '(progn
     (setq dired-recursive-copies   (quote always))
     (setq dired-recursive-deletes  (quote top))
     ;;When pressing C, copy from one dired dir to the next dired dir shown in a split window
     (setq dired-dwim-target        t)

     ;;Have dired open html-files in my predefined browser:
     (add-hook 'dired-mode-hook
               (lambda ()
                 (define-key dired-mode-map "b" 'my-browser-find-file)))

     (defun my-dired-browser-find-file ()
       "Dired function to view a file in a web browser"
       (interactive)
       (browse-url (browse-url-file-url (dired-get-filename))))
     ))

;; don't open a new dired-buffer for every folder, when using RET
;; (I could just use "a" instead of RET, e, or f)
;; http://www.emacswiki.org/emacs/DiredReuseDirectoryBuffer


;; dired-x is pretty good
(add-hook 'dired-load-hook
          (lambda ()
            (load "dired-x")))

(eval-after-load "dired"
  '(progn
     (put 'dired-find-alternate-file 'disabled nil)
     ;; Swap a and RET, so default is to reuse dired buffer when
     ;; opening folder with RET (i.e. C-m)
     (define-key dired-mode-map (kbd "C-m") 'dired-find-alternate-file)
     (define-key dired-mode-map (kbd "a") 'dired-find-file)
     ))
;;---------------------------------------------

8.7. Dired-face

By default dired colors files with one of two colors, depending on if it’s a folder or not. We can do better: screenshot, EW-source, git-source

(eval-after-load 'dired '(progn (require 'dired-filetype-face)))

8.8. ibuffer

Replace the normal list buffers command, (C-x C-b) with ibuffer.

Table 22: ibuffer frequently used keys
Key  
m Mark
u Unmark
*u Mark unsaved
S Save marked buffer
D Close marked buffers
t Invert marked/unmarked buffers.
* * Unmark all marked buffers.
* M Mark buffers by major mode.
* s Mark special buffers
* / mark dired buffers
* e mark dissociated buffers
* h mark help buffers
* m mark modified buffers
* r mark read only buffers
* u mark unsaved buffers
* z mark compressed file buffers
s f Sort the buffers by the file name.
s v Sort the buffers by last viewing time.
s s Sort the buffers by size.
s m Sort the buffers by major mode.
/ m Add a filter by major mode.
/ n Add a filter by buffer name.
/ c Add a filter by buffer content.
/ e Add a filter by an arbitrary Lisp predicate.
/ / Remove all filtering currently in effect.
“=” View the differences between this buffer and its
% f mark by file name regexp
% m mark by mode regexp
% n mark by name regexp

M-s a C-s ibuffer-do-isearch “Do an incremental search in the marked buffers. This is so awesome that you have to try it right this instant. Select two or more buffers, hit the hotkey, search for something that occurs in all these buffers. These two features alone are enough to make me a lifelong fan of IBuffer.”

Q ibuffer-do-query-replace

M-s a C-s - Do incremental search in the marked buffers. M-s a C-M-s - Isearch for regexp in the marked buffers. U - Replace by regexp in each of the marked buffers. Q - Query replace in each of the marked buffers. I - As above, with a regular expression.

8.8.1. filter

Group the open buffers in a list according to these rules:

  ;;---------------------------------------------
  ;; pressing S saves all unsaved buffers, try hitting SPC at [Org]-label.
  ;; See what happens
  ;; RET folds a filter (like folders and hierarchies)

  (require 'ibuffer)

  ;;replace default with ibuffer. Open i other window, and take me there.
  (global-set-key (kbd "C-x C-b") 'ibuffer-other-window)

  ;;sort on major-mode
  (setq ibuffer-default-sorting-mode 'major-mode)

  (setq ibuffer-saved-filter-groups
        (quote (("default"
                 ("Org" ;; all org-related buffers
                  (mode . org-mode))
                 ;; ("equfitter"
                 ;;  (filename . "equationfitter/"))
                 ("Programming C++" ;; prog stuff not already in MyProjectX
                  (or
                   (mode . c-mode)
                   (mode . c++-mode)
                   ))

                 ("Source Code" ;; non C++ related stuff.
                  (or
                   (mode . python-mode)
                   (mode . emacs-lisp-mode)
                   (mode . shell-script-mode)
                   (mode . f90-mode)
                   (mode . scheme-mode)
                   ;; etc
                   ))

                 ("LaTeX"
                  (or
                   (mode . tex-mode)
                   (mode . latex-mode)
                   (name . ".tex")
                   (name . ".bib")
                   ))

                 ("Text" (name . ".txt"))

                 ("Mail"
                  (or  ;; mail-related buffers
                   (mode . message-mode)
                   (mode . mail-mode)
                   (mode . mime-mode)
;;                   (mode . MIME-mode)

                   ;; etc.; all your mail related modes
                   ))

                 ("Web" (or (mode . html-mode)
                            (mode . css-mode)))

                 ("ERC"   (mode . erc-mode))

                 ;; ("Subversion" (name . "\*svn"))
                 ;; ("Magit" (name . "\*magit"))

                 ("Emacs-created"
                  (or
                   (name . "^\\*")))
                 ))))

  (add-hook 'ibuffer-mode-hook
            (lambda ()
              ;;(ibuffer-auto-mode 1)   ;auto update the buffer-list
              (ibuffer-switch-to-saved-filter-groups "default")))

  ;;Don't show (filter) groups that are empty.
  (setq ibuffer-show-empty-filter-groups nil)
  ;;(autoload 'ibuffer "ibuffer" "List buffers." t)

  ;; keep from warning, twice, about deleting buffers.
  ;; only warn about deleting modified buffers.
  (setq ibuffer-expert t)

  ;; ;; Switching to ibuffer puts the cursor on the most recent buffer
  ;; (defadvice ibuffer (around ibuffer-point-to-most-recent) ()
  ;;   "Open ibuffer with cursor pointed to most recent buffer name"
  ;;   (let ((recent-buffer-name (buffer-name)))
  ;;     ad-do-it
  ;;     (ibuffer-jump-to-buffer recent-buffer-name)))
  ;; (ad-activate 'ibuffer)
  ;;---------------------------------------------

8.8.2. Restore window layout/configuration after selecting a buffer

When invoking ibuffer-other-window (which I’ve bound to C-x C-b) ibuffer pops up in a split buffer, which goes away when pressing “q”. But it should also go away if I open a buffer from the ibuffer list. This does that: (or just use C-u RET)

;;---------------------------------------------
(define-key ibuffer-mode-map [remap ibuffer-visit-buffer]
  '(lambda () (interactive)
     (ibuffer-visit-buffer t)))
;;---------------------------------------------

8.8.3. compare marked buffers

;;---------------------------------------------
(defun ibuffer-ediff-marked-buffers ()
  (interactive)
  (let* ((marked-buffers (ibuffer-get-marked-buffers))
         (len (length marked-buffers)))
    (unless (= 2 len)
      (error (format "%s buffer%s been marked (needs to be 2)"
                     len (if (= len 1) " has" "s have"))))
    (ediff-buffers (car marked-buffers) (cadr marked-buffers))))

(define-key ibuffer-mode-map "e" 'ibuffer-ediff-marked-buffers)
;;---------------------------------------------

8.9. icomplete / iswitchb

Auto completion in minibuffer, with list sorted by most recently visited buffer. Can auto complete any part of file name to get it unique. Another nice feature: the list can be scrolled through with C-s and C-r.

;;buffer switching ----------------------------
;;better C-x b  (ido does the same for C-x C-f)
(iswitchb-mode t) ;; obsolete by icomplete-mode!
;;---------------------------------------------

icomplete’s advantage over ido is that it works with files, buffers, and variables, fuctions, etc.

ido only works with buffers and files, I think; at least not with variables and functions.

C-. and C-, cycles through the list, and C-j (or RET) selects the buffer, but I prefer the backwards/forwards search C-r/s keys.

(icomplete-mode 1)
(define-key icomplete-minibuffer-map [?\C-s]
            'icomplete-forward-completions)
(define-key icomplete-minibuffer-map [?\C-r]
            'icomplete-backward-completions)

Or, just do:

(ido-mode 'buffers)

8.10. Occur

occur write up

Occur is awesome. Do M-s o to search for a word in current buffer and show list of all occurrences in a separate buffer.

M-x   multi-occur-in-matching-buffers

is where the real power is, since this lets you search all open buffers matching the regexp you give it, and show hits in a new buffer, which behaves just like the compile buffer.

(eval-when-compile
  (require 'cl))

(defun get-buffers-matching-mode (mode)
  "Returns a list of buffers where their major-mode is equal to MODE"
  (let ((buffer-mode-matches '()))
    (dolist (buf (buffer-list))
      (with-current-buffer buf
        (if (eq mode major-mode)
            (add-to-list 'buffer-mode-matches buf))))
    buffer-mode-matches))

(defun multi-occur-in-this-mode ()
  "Show all lines matching REGEXP in buffers with this major mode."
  (interactive)
  (multi-occur
   (get-buffers-matching-mode major-mode)
   (car (occur-read-primary-args))))

;; global key for `multi-occur-in-this-mode' - you should change this.
;;(global-set-key (kbd "C-<f2>") 'multi-occur-in-this-mode)

8.11. find-file-at-point (ffap)

Update I now use excellent ivy-mode/counsel insead, see ivy/councel, but I’m leaving this to document how I used to do it (in ivy-mode C-x C-f M-n):

It’s in emacs. When doing C-x C-f use information at point (your cursor) to open file or URL. I.e. if your cursor is on a file path, or URL, it defaults to that filled in the minibuffer.

;;find-file-at-point, smarter C-x C-f when point on path or URL
(ffap-bindings)

8.12. auto completion for M-x

Update I now use excellent ivy-mode/counsel insead, see ivy/councel, but you should still have smex installed, (ivy uses it to sort your commands after most used), but no configuration needed; I’m leaving this to document how I used to do it:

This can be done in many ways. I used to use:

(icomplete-mode t)

It worked, but smex is more powerful.

The commands are displayed in an Ido (part of emacs since verison 22) completion buffer, ordered by relevance. The 7 most recently executed commands come first, the rest are sorted by frequency of use, command length and in alphabetical order.

;;smex - A smarter M-x completion ------------
(with-eval-after-load "smex"
  (smex-initialize)
  (global-set-key (kbd "M-x") 'smex)
  (global-set-key (kbd "M-X") 'smex-major-mode-commands)
  (setq smex-save-file "~/.emacs.d/smex-items"))         ; don't save state to "~/.smex-items"
;;---------------------------------------------

9. MAIN EMACS HACKS   main

9.1. arch linux pkgbuild-mode:

(autoload 'pkgbuild-mode "pkgbuild-mode.el" "PKGBUILD mode." t)
(setq auto-mode-alist (append '(("/PKGBUILD$" . pkgbuild-mode)) auto-mode-alist))

9.2. abbrevs

Abbrev lets you replace an abreviation with a full string after you press SPC (or punctuation). See example below, and/or see blog-post.

Abrevs can be saved with “C-x a i g” (abbrev inverse global) with point at end of expanded full word.

C-x a g Define new (mode) global abbrev C-x a l Define new (mode) local abbrev

To not expand what you just typed into the abbrev: C-q before hitting SPC (or punctuation).

(setq abbrev-file-name                ;; tell emacs where to read abbrev
      "~/.emacs.d/abbrev_defs.el")    ;; definitions from...
(setq save-abbrevs t)                 ;; (ask) save abbrevs when files are saved
(setq-default abbrev-mode t)          ;; turn it on for all modes

;; don't show it in modeline (assuming diminish is installed)
(eval-after-load "abbrev" '(diminish 'abbrev-mode))

;; (when (file-exists-p abbrev-file-name)
;;   (quietly-read-abbrev-file))          ;;  don't tell
;; (add-hook 'kill-emacs-hook             ;; write when ...
;;           'write-abbrev-file)          ;; ... exiting emacs

9.2.1. example

My global abrevs are prefixed by 8 due to utf8 key sequence in emacs C-x 8 C-h.

The following is in my file “~/.emacs.d/abbrev_defs.el”, and replaces the string in the list like so: when typing “8alpha” SPC it is replaced by the correct character.

(define-abbrev-table 'global-abbrev-table '(
    ("8alpha"   "α")
    ("8beta"    "β")
    ("8gamma"   "γ")
    ("8Delta"   "Δ")
    ("8delta"   "δ")
    ("8theta"   "θ")
    ("8lambda"  "λ")
    ("8mu"      "µ")
    ("8nu"      "ν")
    ("8pi"      "π")
    ("8Sigma"   "Σ")
    ("8sigma"   "σ")
    ("8tau"     "τ")
    ("8phi"     "φ")
    ("8psi"     "ψ")
    ("8Omega"   "Ω")
    ("8omega"   "ω")
    ("8in"      "∈")
    ("8nin"     "∉")
    ("8inf"     "∞")
    ))

9.3. anzu

An improvement over built in isearch, and search and replace functions (git).

not sure when/if to use this?

(when (require 'anzu)
  (global-anzu-mode +1)

  ;; ;; I think global-anzu-mode already does the below re-mapping:
  ;; (global-set-key [remap query-replace] 'anzu-query-replace)
  ;; (global-set-key [remap query-replace-regexp] 'anzu-query-replace-regexp)
  ;; (define-key isearch-mode-map [remap isearch-query-replace]  #'anzu-isearch-query-replace)
  ;; (define-key isearch-mode-map [remap isearch-query-replace-regexp] #'anzu-isearch-query-replace-regexp)
  (setq anzu-mode-lighter "") ; change mode line text
  )

9.4. Various one line commands/configurations

;;One-Line commands---------------------------
(defalias 'yes-or-no-p 'y-or-n-p)     ;;answer "y/n" rather than "yes/no"
(delete-selection-mode t)             ;;delete region at key press, (not needed due if using cua-mode nil (in rectangle))
(setq visible-bell t)                 ;;blink instead of beep
(setq inhibit-startup-message t)      ;;Don't show start up message/buffer
(file-name-shadow-mode t)             ;;be smart about file names in mini buffer
(global-font-lock-mode t)             ;;syntax highlighting on...
(setq font-lock-maximum-decoration t) ;;...as much as possible
(setq frame-title-format '(buffer-file-name "%f" ("%b"))) ;;titlebar=buffer unless filename

(setq-default indent-tabs-mode nil)   ;;use spaces instead of evil tabs

(setq tetris-score-file "~/.emacs.d/tetris-scores") ;;keep home-folder clean

;; Instead of C-u C-SPC C-u C-SPC to pop mark twice, do: C-u C-SPC C-SPC
(setq set-mark-command-repeat-pop t)
;;--------------------------------------------

9.5. Miscellaneous

Inconsolata is nice open source font for programming.

For other fonts, see for instance: Lesser Known Coding Fonts.

;;miscellaneous--------------------------------
;;set the font to use:

;; Now using emacsclient, must use this format instead:
(add-to-list 'default-frame-alist '(font . "Inconsolata-12"))
;;(add-to-list 'default-frame-alist '(font . "Inconsolata-16"))
;; or:
;;(setq default-frame-alist '((font . "Inconsolata-11")))

;; pre-using emacsclient:
;;(set-frame-font "Inconsolata-11")
;;(set-frame-font "DejaVu Sans Mono-9")
;;(set-default-font "7x13")


;; Make URLs in comments/strings clickable, (emacs > v22)
(add-hook 'find-file-hooks 'goto-address-prog-mode)

;; Make shell scrips executable on save. Good!
(add-hook 'after-save-hook 'executable-make-buffer-file-executable-if-script-p)

(setq initial-scratch-message ";; scratch buffer created -- happy hacking\n")

;;Emacs is a text editor, make sure your text files end in a newline
(setq require-final-newline 'query)

;; set default mode for unknown files
;; (setq-default major-mode 'org-mode)

;;no extra whitespace after lines
;; http://emacsredux.com/blog/2013/05/16/whitespace-cleanup/
;;'whitespace-cleanup is better than delete-trailing-whitespace
;;(add-hook 'before-save-hook 'delete-trailing-whitespace)
(add-hook 'before-save-hook 'whitespace-cleanup)
;; In case I want to do a non-destructive edit to a f*ed up file, eval this:
;; (remove-hook 'before-save-hook 'whitespace-cleanup)

;;--------------------------------------------

9.6. Allow use of some advanced commands

;;--------------------------------------------
;;Enable disabled command:
(put 'upcase-region 'disabled nil)    ;; same as M-u but on whole regions C-x C-u
(put 'downcase-region 'disabled nil)  ;; same as M-l but on whole regions C-x C-l
;;--------------------------------------------

9.7. Global Key-Bindings

;;Key-Bindings--------------------------------
(global-set-key (kbd "M-#")   'sort-lines)            ;;sort lines with Alt-#
(global-set-key (kbd "C-#")   'sort-paragraphs)       ;;sort paragraphs Ctrl-#

(global-set-key [(control tab)] 'hippie-expand)       ;;Ctrl-Tab, word-completion

;;(global-set-key (kbd "C-v")   'yank)                ;;closer on keyboard than "C-y"
;;(global-set-key (kbd "C-z")   'undo)                ;;better than "C-_"?

(global-set-key (kbd "<f7>")  'toggle-truncate-lines)       ;;line wrapping on/off
;;(global-set-key (kbd "<f8>")  'comment-or-uncomment-region) ;; comment/un-comment region
(global-set-key (kbd "<f9>")  'compile)                     ;; compile

;;Learn to use default: M-next / M-prior (i.e. M-PgUp/M-PgDwn)
;;(global-set-key (kbd "<C-M-next>")  'scroll-other-window)
;;(global-set-key (kbd "<C-M-prior>") 'scroll-other-window-down)

;; a better C-h i is C-h C-i which has tab completion on info sections
;; http://emacsredux.com/blog/2014/11/13/quickly-open-an-info-manual/
(define-key 'help-command (kbd "C-i") 'info-display-manual)

(global-set-key (kbd "C-x w") 'write-region)   ;;save marked region as a file

(global-set-key (kbd "M-SPC ") 'cycle-spacing)   ;;Since Emacs 24: a better way of M-SPC

(global-set-key "\C-ct" 'untabify)               ;;replace all evil TAB to SPC nice!
(global-set-key "\C-ci" 'indent-region)          ;;Indent row/marked region
;;(global-set-key "\C-ca" 'mark-whole-buffer)    ;;same as C-x h

;; C-pgup goes to the start, C-pgdw goes to the end:
(global-set-key(kbd "<C-prior>")(lambda()(interactive)(goto-char(point-min))))
(global-set-key(kbd "<C-next>") (lambda()(interactive)(goto-char(point-max))))

;;If you find yourself setting and unsetting selective-display as often as i do,
;; next thing will be defining a handy keyboard shortcut, right?
(defun jao-toggle-selective-display ()
  (interactive)
  (set-selective-display (if selective-display nil 1)))
(global-set-key [f12] 'jao-toggle-selective-display)

;;navigatoin-menu on right mouse button. Used by ref-TeX, and Org-mode.
(global-set-key [down-mouse-3] 'imenu)

;;--------------------------------------------

9.8. ediff mode

Ediff is awesome, but has some stupid defaults, with separate useless control window. Be a buffer instead! Wisdom from here

ediff-current-file
useful for diffing unsaved changes in buffer.
ediff-buffers
useful if you have two frames open with different buffers.
ediff-buffers
same as ediff-buffers, but on files.
Table 23: Keys useful in ediff. (Possible some are for when using ediff in magit?)
Key Function
n next
p previous
q quit
a ediff-copy-A-to-B
b ediff-copy-B-to-A
;;Don't use strange separate control-window.
(customize-set-variable 'ediff-window-setup-function 'ediff-setup-windows-plain)

;;Side by side comparison is easier than vertical split
;;(tob-bottom-stacked) window
(customize-set-variable 'ediff-split-window-function 'split-window-horizontally)

;; ;; To ignore white space. Note: not good for Python
;; (csetq ediff-diff-options "-w")

;; reset the window configuration after ediff is done
;;(winner-mode)
;;(add-hook 'ediff-after-quit-hook-internal 'winner-undo)

9.9. htmlize

File for converting Emacs fontification (colours, italics, etc) into HTML. Handy to convert parts or whole buffers to html, with syntax highlighting. Like saving ERC logs, or code. It’s included in emacs-goodies-el.deb on Debian.

Check out http://www.emacswiki.org/emacs/PrintWithWebBrowser.

;;htmlize--------------------------------------
;; convert buffer (with type face, and syntax highlighting) to *.html
;; htmlize; http://fly.cc.fer.hr/~hniksic/emacs/htmlize.el.html
(autoload 'htmlize-region "htmlize" "htmlize the region" t)
(autoload 'htmlize-buffer "htmlize" "htmlize the buffer" t)
;;---------------------------------------------

9.10. beacon-mode

A minor mode that indicates the position of your cursor in the buffer, by a short flash, whenever it moves, so that you don’t loose it. Install it from melpa. Official soruce on github. Also mention by endlessparentheses.

;;beacon --------------------------------------
;; When cursor jumps, flash it's new position, so we don't loose it
(when (functionp 'beacon-mode)
  (beacon-mode 1)

  ;; don't show symbol in modeline (assuming diminish is installed)
  (diminish 'beacon-mode)

  ;; only flash on window/buffer changes...
  (setq beacon-blink-when-window-changes t)
  ;; ... don't be excessive:
  (setq beacon-blink-when-window-scrolls nil)
  (setq beacon-blink-when-point-moves nil)
  (setq beacon-blink-duration .2)       ; default .3
  (setq beacon-blink-delay .2)          ; default .3
  (setq beacon-size 8))                 ; default: 40
;;---------------------------------------------

9.11. TAB-completion

9.11.1. Hippie expand

I believe this tries to expand the word at point by going through a list of many different methods, dabbrevs is one of them:

“HippieExpand looks at the word before point and tries to expand it in various ways including expanding from a fixed list (like ”expand-abbrev“), expanding from matching text found in a buffer (like ”dabbrev-expand“) or expanding in ways defined by your own functions. Which of these it tries and in what order is controlled by a configurable list of functions.”

By default M-/ is bound to dabbrev-expand dynamic abbrev. M-/ cycles through different completions, based on what you have written before point, and after.

;; hippie-expand ------------------------------
(setq hippie-expand-try-functions-list
      '(try-expand-dabbrev-visible
        try-expand-dabbrev
        try-expand-dabbrev-all-buffers
        try-expand-dabbrev-from-kill
        try-complete-file-name-partially
        try-complete-file-name
        ;; yas has TAB, and abbrevs has SPC, so not needed here
        ;; try-expand-all-abbrevs
        ;; yas/hippie-try-expand
        ;;
        ;;         try-expand-list
        ;;         try-expand-line
        ;;        try-complete-lisp-symbol-partially
        ;;        try-complete-lisp-symbol
        ))

;;preserve case on expand with dabbrev
;;(setq dabbrev-case-replace nil)

;;---------------------------------------------

9.11.2. Yasnippet

First emacs had it’s abrevs. Then Textmate was jealous and came up with even more powerful TAB-completion/templates with query-fields. With Emacs being easily extendable, it was a no brainer to port that back to emacs and make it even more powerful. It uses same/similar syntax as textmate, so import was simple. Plus you can write your own easily but save them elsewhere*. Can easily be installed through the emacs package system, but for reference: git-soruce (for the official yasnippet elisp code) git-source-snippets (for the templates/snippets used by yasnippet)

Now yasnippet only loads snippets on demand, so (yas/load-directory ...) is no longer needed, which gives faster starup.

*When looking for snippets the variable that holds the snippets is read. This can be set e.g. (setq yas-snippet-dirs '("~/emacs.d/mysnippets" "~/Downloads/interesting-snippets")). By default it looks for the users personal snippets in “~/.emacs.d/snippets”, and the bundled ones as a subdirectory relative to the location of yasnippet.el.

;;Yasnippet ----------------------------------
;; set location of snippets
;; M-x yas-reload-all if you've started YASnippet already.
(setq yas-snippet-dirs
      '("~/.emacs.d/snippets"                 ;; personal snippets
        ;;"/path/to/yasnippet/yasmate/snippets" ;; the yasmate collection
        ))

(with-eval-after-load 'yasnippet (yas/global-mode 1))
(add-hook 'prog-mode-hook #'yas-minor-mode)
(add-hook 'org-mode-hook #'yas-minor-mode)
;;--------------------------------------------

9.12. Copy/Paste buffers across X11

The code below works fine for me. However, there’s a recent blog post addressing the clipboard mayhem, including MacOSX: ZSH, tmux, Emacs and SSH: A copy-paste story

;;Copy-Paste----------------------------------
;;(work with both terminal (S-INS) and X11 apps.):
(when (> (display-color-cells) 16)         ;if not in CLI
  (setq x-select-enable-clipboard t        ;copy-paste should work (default in emacs24)
        interprogram-paste-function        ; ...with ...
        'x-cut-buffer-or-selection-value)) ; ...other X-clients
;;--------------------------------------------

9.13. Encryption

Automatically decrypt/encrypt *.gpg-files. Works like a charm. For instance, a file my_passwords.org.gpg gets loaded in org-mode, by default.

However, I haven’t been able to get the password promt to be in the minibuffer. I’ve tried everything at How to use a non-graphical password prompt for gpg.

You may also encrypt just part of a text in org-mode, using org-crypt. See org-section for further details.

;;Encryption-------------------------------
;;Setup for transparent, automatic encryption and decryption:
;;(does naught... ?)
(when (require 'epa-file nil 'noerror)
  (epa-file-enable)

  ;; t      to always ask for user
  ;; nil    to ask for users unless specified
  ;;'silent to use symmetric encryption:
  (setq epa-file-select-key 'silent)

  ;;Note: if you have an instance of seahorse running, then the environment
  ;;variable GPG_AGENT_INFO=/tmp/seahorse-nDQm50/S.gpg-agent:6321:1, which
  ;;causes emacs to start a GUI for password, instead of using mini-buffer.

  (setenv "GPG_AGENT_INFO" nil)
  ;; Note: another form is:
  ;;(setenv (concat "GPG_AGENT_INFO" nil))
  )
;;---------------------------------------------

Turn off any auto-saving function or backup for gpg-files, since they are saved as plain text. src

;;Turn off backup for gpg-files ---------------
(define-minor-mode sensitive-mode
  "For sensitive files like password lists. It disables backup
creation and auto saving.

With no argument, this command toggles the mode. Non-null prefix
argument turns on the mode. Null prefix argument turns off the
mode."
  ;; The initial value.
  nil
  ;; The indicator for the mode line.
  " Sensitive"
  ;; The minor mode bindings.
  nil
  (if (symbol-value sensitive-mode)
      (progn
        ;; disable backups
        (set (make-local-variable 'backup-inhibited) t)
        ;; disable auto-save
        (if auto-save-default
            (auto-save-mode -1)))
    ;; resort to default value of backup-inhibited
    (kill-local-variable 'backup-inhibited)
    ;;resort to default auto save setting
    (if auto-save-default
        (auto-save-mode 1))))

(setq auto-mode-alist
      (append '(("\\.gpg$" . sensitive-mode))
              auto-mode-alist))
;;---------------------------------------------

9.14. Effective Emacs

:noexport: Once one have taken a shine to Emacs, it's well worth optimizing it: https://sites.google.com/site/steveyegge2/effective-emacs

(…although I acutally don’t use anything that’s in there)

;; Rebind M-x to C-x C-m, for ergonomics
(global-set-key "\C-x\C-m" 'execute-extended-command)
(global-set-key "\C-c\C-m" 'execute-extended-command)

;; nicer on the fingers, if using M-x, since using non-US-keyboard.
(defalias 'qrr 'query-replace-regexp)

9.15. EWW - Emacs Web Wowser

As of emacs 24.4, there is now a built in text based web browser, or “html to text converter”, here’s a short intro

9.15.1. Link numbering - for Conkeror like navigation

Install eww-lnum from MELPA, or get code from github

(eval-after-load "eww"
  '(progn (define-key eww-mode-map "f" 'eww-lnum-follow)
          (define-key eww-mode-map "F" 'eww-lnum-universal)))

9.15.2. EWW Toggle images

Toggle images in buffer on/off with “I” (src):

(defun my/eww-toggle-images ()
  "Toggle whether images are loaded and reload the current page fro cache."
  (interactive)
  (setq-local shr-inhibit-images (not shr-inhibit-images))
  (eww-reload t)
  (message "Images are now %s"
           (if shr-inhibit-images "off" "on")))

(define-key eww-mode-map (kbd "I") #'my/eww-toggle-images)
(define-key eww-link-keymap (kbd "I") #'my/eww-toggle-images)

;; minimal rendering by default
(setq-default shr-inhibit-images t)   ; toggle with `I`
(setq-default shr-use-fonts nil)      ; toggle with `F`

9.16. Auto compile LISP files on save

Very handy! Auto compiles .emacs if changes (and saved), if there is a byte compiled version of it from before. I actually don’t have any byte compiled version of my .emacs anymore since I’m running emacsclient.

;;Auto compile *.elc-files on save -----------
(defun auto-byte-recompile ()
  "If the current buffer is in emacs-lisp-mode and there already exists an `.elc'
file corresponding to the current buffer file, then recompile the file on save."
  (interactive)
  (when (and (eq major-mode 'emacs-lisp-mode)
             (file-exists-p (byte-compile-dest-file buffer-file-name)))
    (byte-compile-file buffer-file-name)))
(add-hook 'after-save-hook 'auto-byte-recompile)
;;--------------------------------------------

9.17. Bookmarks

TODO: I’ve never used bookmarks. I just use register marks instead. C-x r SPC/j.

;;Bookmarks-----------------------------------
;; C-x r m ('make') will create a new bookmark, defaulting to the current file.
;; Jump to an existing bookmark with C-x r b ('bookmark')
;; You can see the list of your bookmarks with C-x r l ('list').
(setq
  bookmark-default-file "~/.emacs.d/bookmarks" ;; keep ~/ clean from .files
  bookmark-save-flag 1)                        ;; auto save changes
;;--------------------------------------------

9.18. register

Registers are super useful in emacs. It’s what prefixed by “C-x r”. Allows storing of rectangular selections, copy, paste, multiple cut/paste, etc, and remember positions in a buffer (for that session).

Set register (bookmark) with C-x r SPC [number], and jump to it with C-x r j [number].

;;Recenter after jump-to-register--------------
;;When jumping, put mark on top of screen, not bottom, as is default
(defadvice jump-to-register
  (after jump-to-register-recenter-top)
  "Recenter point to top of window after jumping to a register."
  (recenter 0))
(ad-activate 'jump-to-register)
;;---------------------------------------------
;; Useful to display list of the registers
(when (require 'list-register nil 'noerror)
 (global-set-key (kbd "C-x r v") 'list-register))

9.19. avy-mode

avy (src) is best described as an improved ace-jump (video) that is more well maintained, and works for links (info-mode, help-mode, eww-mode), and windows as well. Also, it supports two char input! (blog)

(global-set-key (kbd "C-c SPC") 'avy-goto-word-1)
(global-set-key (kbd "M-g w") 'avy-goto-word-1)
(global-set-key (kbd "M-g c") 'avy-goto-char)
(global-set-key (kbd "M-g M-w") 'avy-goto-word-1)
(define-key (current-global-map) [remap goto-line] 'avy-goto-line)

;; When org-mode starts it (org-mode-map) overrides this binding.
(add-hook 'org-mode-hook
          (lambda ()
            (local-set-key (kbd "C-c SPC") 'avy-goto-char)))

;; Use the home keys on a qwety keyboard
(setq avy-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))

;; Put overlay ontop (obscuring) the text, since this doesn't shift the line
;; 'at = single char at target; 'pre = before target; 'post = after target
(setq avy-style 'at-full)

;; Bind o to jump link in info-mode, help-mode, and eww-mode
;;(ace-link-setup-default)

9.20. goto-chg

Very useful. Go to the place where you last changed something. I actually find myself sometimes undoing something just to get to where I made a change and then undo the undo. With goto-chg, no more! It jumps the marker to the last place of a change.

Note for keybinding, “M-.” will conflict with etags navigation in code, and “C-.” will conflict with flyspell-mode, both of which I use a lot. Time to cash in on actually having extra letters in the alphabet.

(when (require 'goto-chg nil 'noerror)
  (global-set-key (kbd "C-ä") 'goto-last-change)
  (global-set-key (kbd "C-M-ä") 'goto-last-change-reverse))

9.21. zap-to-char

To delete everything from marker up to (and including) character: M-z. But excluding the character, we can rebind M-z from here.

(autoload 'zap-up-to-char "misc"
  "Kill up to, but not including ARGth occurrence of CHAR.")
(global-set-key (kbd "M-z") 'zap-up-to-char)

9.22. which-key

After 1 second of an unfinished key-press, show the documentation of the sub-keys available in the key sequence. See source page for screenshots.

(when (require 'which-key nil 'noerror)
  (which-key-mode))
(eval-after-load "which-key" '(diminish 'which-key-mode "wk"))

9.23. Moving lines or regions up/down

This (EW) allows you to easily drag lines or regions around in the buffer. Alternative code from emacs-rocks.

;;Move lines up/down---------------------------
;; If move-text not installed, then define some of it:
(when (not (require 'move-text nil 'noerror))
  (defun move-text-down ()
    (interactive)
    (let ((col (current-column)))
      (save-excursion
        (forward-line)
        (transpose-lines 1))
      (forward-line)
      (move-to-column col)))

  (defun move-text-up ()
    (interactive)
    (let ((col (current-column)))
      (save-excursion
        (forward-line)
        (transpose-lines -1))
      (move-to-column col))))

(global-set-key (kbd "<C-S-down>") 'move-text-down)
(global-set-key (kbd "<C-S-up>") 'move-text-up)
;;---------------------------------------------

9.24. save history

A must for sane behavior of emacs. Thank you emacs-fu.

;;Save History--------------------------------
;;Save mode-line history between sessions. Very good!
(setq savehist-additional-variables    ;; Also save ...
  '(search-ring regexp-search-ring)    ;; ... searches
  savehist-file "~/.emacs.d/savehist") ;; keep home clean
(savehist-mode t)                      ;; do this before evaluation
;;--------------------------------------------

9.25. save places (position/point)

Save the position I was in each file, i.e. no scrolling down to paragraph N or function foo when I reopen my files.

;; Save point position between sessions
(require 'saveplace)
(setq-default save-place t)
(setq save-place-file (expand-file-name "save-point-places" user-emacs-directory))

9.26. Rectangular highlighting

Initially I found this most excellent! Sure you could use the “old-school” emacs way of C-x r followed by k (kill) or y (yank) or M-w (copy, since Emacs 24.3) keys to do the same, which also works in tty/terminal, but this gives visible (actual rectangular) marking, so one can see the result “live”.

However, C-RET is used in other modes, and I find myself actually preferring the “old-school” way. But when new to Emacs, this was very neat:

Note: removes moving marker with C-v / M-v (now they are just page up/dwn). Also removes delete selected text

;;Rectangular markings-----------------------
;;COOL! C-RET gives rectangular marking for copy/paste, extremely useful
;;for tables. NOTE, second line needed for rectangle, but also gives
;; (transient-mark-mode t) = visualize C-SPC-marking (i.e. highlight)
(setq cua-enable-cua-keys nil) ;;only for rectangle, don't use C-x/c/v for copy/paste
(cua-mode t)                   ;;gives rectangle + same as "(pc-selection-mode)" (=shift+arrow highlights)
;;--------------------------------------------

9.27. awesome copy/paste!

This is super-amazing hack by emacs-fu.

;;Awesome copy/paste!----------------------
;;My most used hack! If nothing is marked/highlighted, and you copy or cut
;;(C-w or M-w) then use column 1 to end. No need to "C-a C-k" or "C-a C-w" etc.
(defadvice kill-ring-save (before slick-copy activate compile) "When called
  interactively with no active region, copy a single line instead."
  (interactive
   (if mark-active (list (region-beginning) (region-end))
     (message "Copied line")
     (list (line-beginning-position)
           (line-beginning-position 2)))))

(defadvice kill-region (before slick-cut activate compile)
  "When called interactively with no active region, kill a single line instead."
  (interactive
    (if mark-active (list (region-beginning) (region-end))
      (list (line-beginning-position)
        (line-beginning-position 2)))))
;;--------------------------------------------

9.28. parenthesis matching

Another must have for sanity reasons.

;;Parantes-matchning--------------------------
;;Match parenthesis through highlighting rather than retarded jumps. Good!
(when (fboundp 'show-paren-mode)
  (show-paren-mode t)
  (setq show-paren-style 'parenthesis))
;;--------------------------------------------

9.29. volatile-highlight

Highlight the latest changes in the buffer (like text inserted from: yank, undo, etc.) until the next command is run. Nice, since it lets me see exactly what was changed. Get it here.

(when (require 'volatile-highlights nil 'noerror)
  (volatile-highlights-mode t))
(eval-after-load "volatile-highlights" '(diminish 'volatile-highlights-mode))

9.30. browse-Kill-Ring

Requires “browse-kill-ring.el” which is a part of emacs-goodies-el.deb on Debian. It’s one of those esential packages, that everyone should use.

;;Browse-Kill-Ring----------------------------
;;this makes M-y activate the kill-ring IF the previous command
;;was not a yank. (C-y)
(when (require 'browse-kill-ring nil 'noerror)
  (browse-kill-ring-default-keybindings)
  (setq browse-kill-ring-quit-action 'save-and-restore))
;;--------------------------------------------

9.31. narrow to region

Lets you reduce a buffer to show only what is currently needed for editing purpose. Combined with indirect buffers it lets you use several different modes (one for each panel) all operating on the same buffer. Useful for:

  • Writing an email, with some code in it. E.g. C++.
  • Editing HTML, with embedded CSS and/or javascript.

    Split frame in several panels. Select region, run narrow-to-region. This narrows in all panels, which is not what we want (mode-line will say “Narrow”). Thus we use “indirect buffers”.

    “An indirect buffer shares the text of some other buffer, which is called the base buffer of the indirect buffer. In some ways it is a buffer analogue of a symbolic link between files.”

    Given a file, split the buffer into as many panels as wanted. Run clone-indirect-buffer on each panel, then narrow-to-region again, and each panel can have its own major mode.

    Also: http://nathanielknight.ca/articles/reading_code_with_emacs_controlling_display.html#coming-soon

Table 24: Narrow to region keys
Key Command
C-x n n narrow to region
C-x n p narrow to page
C-x n s narrow to subtree (for org-mode)
C-x n w widen (i.e. un-narrow)
;;C-x n n disabled by default:
(put 'narrow-to-region 'disabled nil)
(put 'narrow-to-defun  'disabled nil)
(put 'narrow-to-page   'disabled nil)
;; open an indirect buffer, and narow to region
(defun narrow-to-region-indirect (start end)
  "Restrict editing in this buffer to the current region, indirectly."
  (interactive "r")
  (deactivate-mark)
  (let ((buf (clone-indirect-buffer nil nil)))
    (with-current-buffer buf
      (narrow-to-region start end))
      (switch-to-buffer buf)))

Alternative code: http://paste.lisp.org/display/135818

9.32. thin marker

;; NOTE! This causes PDF's to flicker, when viewing them in Emacs.
;;
;;Modifiera Markören--------------------------
;;Normal mode:              Cursor is a yellow vertical bar
;;Overwrite mode (ins-key): Cursor is a red block
;;Read-only mode:           Cursor is gray vertical bar
;; http://www.emacswiki.org/emacs/ChangingCursorDynamically
(defun djcb-set-cursor-according-to-mode ()
  "change cursor color and type according to some minor modes."
  (cond
    (buffer-read-only
      (set-cursor-color "gray")
      (setq cursor-type 'hbar))
    ;; valid values are t, nil, box, hollow, bar, (bar . WIDTH), hbar,
    ;; (hbar. HEIGHT); see the docs for set-cursor-type
    (overwrite-mode
      (set-cursor-color "red")
      (setq cursor-type 'box))
    (t
      (set-cursor-color "yellow")
      (setq cursor-type 'bar))))

;;TODO: only activate this setup if not in doc-view-mode:
(add-hook 'post-command-hook 'djcb-set-cursor-according-to-mode)

;; (add-hook 'post-command-hook
;;           (lambda () (interactive)
;;             (unless (member
;;                      major-mode '(pdf-docs doc-view-mode)
;;                      (djcb-set-cursor-according-to-mode)))))
;;--------------------------------------------

9.33. web browser

Every fan of Emacs should use Conkeror. No exceptions.

Post script: As of the release of Firefox 57, conkeror is discontinued due to Firefox dropping breaking their API. Several new one-man projects have popped up to replace it:

an alternative, could be:

  • qutebrowser (QT web engine, Python 3, supports adblocking, what Vim community uses)

(see difference with webmacs)

;;--------------------------------------------
;;Use the awesome conkeror to open url's
(setq browse-url-browser-function (quote browse-url-generic))
(setq browse-url-generic-program "conkeror")
;;--------------------------------------------

9.34. word lookup

Testing this at the moment.

(defun lookup-word-definition ()
  "Look up the current word's definition in a browser.
If a region is active (a phrase), lookup that phrase."
  (interactive)
  (let (myWord myUrl)
    (setq myWord
          (if (region-active-p)
              (buffer-substring-no-properties (region-beginning) (region-end))
            (thing-at-point 'symbol)))

    (setq myWord (replace-regexp-in-string " " "%20" myWord))
    (setq myUrl (concat "http://www.answers.com/main/ntquery?s=" myWord))

    (browse-url myUrl)
    ;; (w3m-browse-url myUrl) ;; if you want to browse using w3m
    ))

(global-set-key (kbd "<f6>") 'lookup-word-definition)

9.35. scroll softly

  ;;Scroll--------------------------------------
  ;;Soft scroll, no spastic jumps
  (setq scroll-margin 0                ;;start scrolling when marker at top/bottom
        scroll-conservatively 100000   ;;marker distance from center (don't jump to center)
;        scroll-up-aggressively 0     ; doesn't work in 24.4 todo xxx yyy C-h n scroll-up-line
;        scroll-down-aggressively 0
        scroll-preserve-screen-position 1) ;;try to keep screen position when PgDn/PgUp
  ;;--------------------------------------------

9.36. scroll up/down (S-up/down) keep cursor

Behave like the terminal, S+Up/Down, scrolls up but keeps the cursor (vertically) centered on the screen. (keybinding is overwritten in org-mode)

Note: this also disables highlighting/marking with shift. Use C-SPC instead, there are not enough keys for emacs to waste S-Arrow on.

;;---------------------------------------------
(defun scroll-down-keep-cursor ()
  ;; Scroll the text one line down while keeping the cursor
  ;; at the same position relative the window frame
  (interactive)
  (scroll-down 1)  ; move window
  (next-line 1))   ; move cursor back, to keep it on the same line

(defun scroll-up-keep-cursor ()
   ;; Scroll the text one line up while keeping the cursor
   (interactive)
   (scroll-up 1)
   (previous-line 1))

;;Bind the functions to the /-key and the *-key (on the numeric keypad) with:
;;(global-set-key [kp-divide] 'scroll-down-keep-cursor)
;;(global-set-key [kp-multiply] 'scroll-up-keep-cursor)

(global-set-key [S-up]   'scroll-down-keep-cursor)
(global-set-key [S-down] 'scroll-up-keep-cursor)
;;---------------------------------------------

9.37. shell-term

M-x shell, starts a buffer that is like a normal emacs buffer, but you can type shell commands in it. It does not play nice with top, etc.

For a “real” terminal buffer use ansi-term, or multi-term.

;;When compiling from shell, display error result as in compilation
;;buffer, with links to errors.
(add-hook 'shell-mode-hook 'compilation-shell-minor-mode)

9.38. auto-insert-mode

For automatically inserting useful stuff into new *.tex, *.cpp, *.gnu files. Put skeleton files in ~/.emacs.d/auto-insert/ directory.

;;Auto-insert-mode---------------------------
;;(auto-insert-mode t)
(require 'autoinsert)
(auto-insert-mode)                                     ;; Adds hook to find-files-hook
(setq auto-insert-directory "~/.emacs.d/auto-insert/") ;; Or use custom, *NOTE* Trailing slash important
;;(setq auto-insert-query nil)                         ;; If you don't want to be prompted before insertion
(define-auto-insert "\.tex" "latexmall.tex")
(define-auto-insert "\.cpp" "cppmall.cpp")
;;--------------------------------------------

9.39. multiple cursors

This is truly awesome, check out the emacs rocks video. Documentation on project’s git repo.

Note:

  • That number of cursors are displayed in mode line
  • “If you get out of multiple-cursors-mode and yank - it will yank only from the kill-ring of main cursor. To yank from the kill-rings of every cursor use yank-rectangle, normally found at C-x r y.”

BTW, I highly recommend adding mc/mark-next-like-this to a key binding that’s right next to the key for er/expand-region.

Key description
C-’ toggle hide/show all lines without a cursor
C-v / M-v center on each cursor up/down
(require 'multiple-cursors)
(global-set-key (kbd "C-S-c C-S-c") 'mc/edit-lines)
(global-set-key (kbd "C->") 'mc/mark-next-like-this)
(global-set-key (kbd "C-<") 'mc/mark-previous-like-this)
(global-set-key (kbd "C-c C-<") 'mc/mark-all-like-this)

;;or set multiple cursors with mouse!
(global-unset-key (kbd "M-<down-mouse-1>"))
(global-set-key (kbd "M-<mouse-1>") 'mc/add-cursor-on-click)

9.40. backups

Backups are mostly just annoying, but will save your life one day. Thus I want all of them in the same folder.

There are two different mechanisms. First is auto-save to save unsaved changes to file “filename” every 300 characters, to “#filename#” in the same folder. It is removed when you actually save the file.

Second is to make backups files to specific backup directory, and keep several versions. I don’t like the “file~” method as it clutters up, instead stick them all in a common folder.

;;Backups-------------------------------------
(defconst my-backup-dir
  (expand-file-name (concat user-emacs-directory "backups")))

(setq make-backup-files t ;; make backup first time a file is saved
      version-control t   ;; number and keep versions of backups
      backup-by-copying t ;; and copy (don't clobber symlinks) them to...
      backup-directory-alist `(("." . ,my-backup-dir)) ;; ...here
      kept-new-versions 2
      kept-old-versions 5
      delete-old-versions t ;; don't ask about deleting old versions
      ;;vc-make-backup-files t ;; even backup files under version control (git/svn/etc.)
      ;;make-backup-files nil      ;;No annoying "~file.txt"
      ;;auto-save-default nil      ;;no auto saves to #file#
      ;;auto-save-interval 300     ;; Auto save "file" to "#file#" every 300 (default)
      )

;; if no backup directory exists, then create it:
(if (not (file-exists-p my-backup-dir))
    (mkdir my-backup-dir t))
;;--------------------------------------------

9.41. Dictionary (dict)

Most useful if one has the dict server installed, together with some dictionaries, like Webster, WordNet, and the like.

On the importance of using dictionary in your writing, NYT, “draft#4

For thesaurus there is synosaurus and powerthesaurus. I use the former, and have wordnet-cli installed, i.e. the dictionary, and the program “wn”.

synosaurus-lookup synosaurus-choose-and-replace

small and simple: https://github.com/abo-abo/define-word more advanced dictionary, I think: https://github.com/myrkr/dictionary-el/

for dictionary

dictionary-search
dictionary-match-words
dictionary-lookup-definition

Specify which dictionary for tool-tip mouse over, (want only one, for smallness sake)

(setq dictionary-tooltip-dictionary "eng-deu")
(dictionary-tooltip-mode 1)
sudo systemctl enable dictd.service
;; Install dictd and dictd-gcide (GNU CIDE = Webster 1913 + some of WordNet)
(setq dictionary-server "localhost")

Note: in dictionary buffer, press “h” for help.

Webster’s dictionary took him 26 years to finish. It ended up having 70,000 words. He wrote it all himself, including the etymologies, which required that he learn 28 languages, including Old English, Gothic, German, Greek, Latin, Italian, Spanish, Dutch, Welsh, Russian, Aramaic, Persian, Arabic, and Sanskrit. He was plagued by debt to fund the project; he had to mortgage his home.

I’d been using Webster’s dictionary for about a year; I kept looking words up, first there, then in whatever modern dictionary was closest to hand, and seeing this awful difference, evidence of a crime that kept piling up in my mind, the guilt building: so many people were getting this wrong impression about words, every day, so many times a day.

(Note that the modern Merriam-Webster, even though it does derive directly from Webster’s original, has been revised so much that it’s actually less similar, content-wise, than some of the impostors. It, too, is one of the “wrong” dictionaries.)

From: http://jsomers.net/blog/dictionary

;; use wordnet (needs to be installed), or openthesaurus
(setq synosaurus-backend 'synosaurus-backend-wordnet)

;; either ido (fuzzy matching), popup (needs library popup.el),
;;or default (minibuffer)
(setq synosaurus-choose-method 'ido)

Old unused code, use ’dictionary’ from MELPA instead.

;;Dictionary (dict)---------------------------
;;(when (require 'dictem nil 'noerror)
(when (locate-library "dictem")
  (autoload 'dictem-run-define "dictem" "define word at point" t)

  ;; ;; Code necessary to obtain database and strategy list from DICT
  ;; ;; server. As of version 0.90, dictem runs this function from
  ;; ;; dictem-select-database and dictem-select-strategy if an
  ;; ;; initialization was not completed or failed previously, that is
  ;; ;; running dictem-initialize is optional
  ;; (dictem-initialize)
  ;; ;; Assigning hot keys for accessing DICT server

  ;; ;; SEARCH = MATCH + DEFINE
  ;; ;; Ask for word, database and search strategy
  ;; ;; and show definitions found
  ;; (global-set-key "\C-cs" 'dictem-run-search)

  ;; ;; MATCH
  ;; ;; Ask for word, database and search strategy
  ;; ;; and show matches found
  ;; (global-set-key "\C-cm" 'dictem-run-match)

  ;; DEFINE
  ;; Ask for word and database name
  ;; and show definitions found
  (global-set-key "\C-cd" 'dictem-run-define)

  ;;Hyperlinks:
  ;;...........
  ;; For creating hyperlinks on database names
  ;; and found matches.
  ;; Click on them with mouse-2
  (add-hook 'dictem-postprocess-match-hook
            'dictem-postprocess-match)

  ;; For highlighting the separator between the definitions found.
  ;; This also creates hyperlink on database names.
  (add-hook 'dictem-postprocess-definition-hook
            'dictem-postprocess-definition-separator)

  ;; For creating hyperlinks in dictem buffer
  ;; that contains definitions.
  (add-hook 'dictem-postprocess-definition-hook
            'dictem-postprocess-definition-hyperlinks)

  ;; For creating hyperlinks in dictem buffer
  ;; that contains information about a database.
  (add-hook 'dictem-postprocess-show-info-hook
            'dictem-postprocess-definition-hyperlinks)
  )
;;--------------------------------------------

9.42. Time-stamp files with “Time-stamp: <>” in header

;;Time-stamp-----------------------------------
;; when there is a "Time-stamp: <>" in the first 10 lines of the file,
;; emacs will write time-stamp information there when saving the file.
(setq time-stamp-active t          ; do enable time-stamps
      time-stamp-line-limit 10     ; check first 10 buffer lines for Time-stamp: <>
      time-stamp-format "Last changed %Y-%02m-%02d %02H:%02M:%02S by %L, %u") ; date format
(add-hook 'write-file-hooks 'time-stamp) ; update when saving
;;--------------------------------------------

9.43. Printing to ps-files

Don’t use M-x print-buffer. Rather, use M-x ps-print-buffer or M-x ps-print-region

;;Printing --------------------------------
;; 2 column landscape size 7 prints column 0-78, lines 1 to 70
(setq ps-paper-type 'a4
      ps-font-size 7.0
      ps-print-header nil
      ps-print-color-p t
      ps-landscape-mode nil    ; for two pages per page: t
      ps-number-of-columns 1)  ; for two pages per page: 2
;;-----------------------------------------

9.44. Tramp

Tramp (Transparent Remote Access, Multiple Protocols) is used to access files remotely on another computer, and edit them in your current local emacs session. Very handy. (This guide on general ssh usage is probably most useful write up). Also, the FAQ is worth a read.

Use C-x C-f to find files over ssh.

  • Normally: C-x C-f /path/to/file
  • Through ssh: C-x C-f /ssh:username@myhost.univ:/path/to/file
  • Or shorter: C-x C-f /ssh:myhost:/path/to/file
  • Using sudo: C-x C-f /su::/etc/hosts
  • Using sudo: C-x C-f /sudo::/etc/hosts
  • specify port:C-x C-f /ssh:usr@host#2222:/etc/hosts
  • bypass remote shell setting: C-x C-f /sshx:username@myhost.univ:/path/to/file
  • connect to B from A: C-x C-f /ssh:user@hostA|ssh:user@hostB:/path
  • connect to B as sudo from A: C-x C-f /ssh:user@hostA|sudo:user@hostB:/path

Always use sudo:hostname: or su:hostname: with remote hosts, instead of sudo::, don’t use :: when mutli-hopping.

/sudo:: is an alias for /sudo:localhost: which is an alias for /sudo:root@localhost:

Since I’m using zsh with some fancy propt stuff, it will hang tramp, so I reset the tramp-shell-prompt-pattern to deal with the [] and such. Works for the zsh promp I’m using now.

Alternativley one could do:

(eval-after-load 'tramp '(setenv "SHELL" "/bin/bash"))

but this changes the SHELL for the remainder of the emacs session.

What I actually use looks like:

;;Tramp---------------------------------------
;;Open files remotley through ssh; or open in su(do).
;;(eval-after-load "tramp"                     ;;run once we actually use tramp
(when (require 'tramp nil 'noerror)            ;;run if tramp exists && not loaded yet.
  (setq tramp-shell-prompt-pattern             ;;to work with zsh prompt
        "^[^$>\n]*[#$%>] *\\(\[[0-9;]*[a-zA-Z] *\\)*")
  (setq tramp-default-method "sshx")           ;;faster, as is "scp"

  ;; takes seconds to save files
  ;; (setq tramp-auto-save-directory "/tmp")      ;; actually, I'd like to disable auto save  xxx todo

  ;; this code supposedly disables auto-backup for tramp?
  ;; https://www.gnu.org/software/emacs/manual/html_node/tramp/Auto_002dsave-and-Backup.html
  (add-to-list 'backup-directory-alist
               (cons tramp-file-name-regexp nil))

  ;; disable version control, better seeed,
  ;; (I use magit instead)
  (setq vc-ignore-dir-regexp
        (format "\\(%s\\)\\|\\(%s\\)"
                vc-ignore-dir-regexp
                tramp-file-name-regexp))

;; lower tramp verbose level, from default 3, when not hunting bugs /
;; connectivity issues:
(setq tramp-verbose 1))
;;--------------------------------------------

To debug connection issues, set tramp-verbose to 6.

To try out:

9.45. Ask to open as root if I lack permission to edit

Very useful. If I try to open a file I don’t have write permissions to, ask if I want to open it as root (using tramp). source

Note: if you’re experiencing problems using this (like tramp hanging), check that you can open them “manually” in the first place, C-x C-f /sudo::/path/to/file. Check the tramp troubleshooting section at emacs wiki.

;;Open as root---------------------------------
;;Ask if I want to open file as root (and use tramp-sudo to give
;;permission)
(defun th-rename-tramp-buffer ()
  (when (file-remote-p (buffer-file-name))
    (rename-buffer
     (format "%s:%s"
             (file-remote-p (buffer-file-name) 'method)
             (buffer-name)))))

(add-hook 'find-file-hook
          'th-rename-tramp-buffer)

(defadvice find-file (around th-find-file activate)
  "Open FILENAME using tramp's sudo method if it's read-only."
  (if (and (not (file-writable-p (ad-get-arg 0)))
           (y-or-n-p (concat "File "
                             (ad-get-arg 0)
                             " is read-only.  Open it as root? ")))
      (th-find-file-sudo (ad-get-arg 0))
    ad-do-it))

(defun th-find-file-sudo (file)
  "Opens FILE with root privileges."
  (interactive "F")
  (set-buffer (find-file (concat "/sudo::" file))))
;;---------------------------------------------

9.46. Emacs calc – not “just” a calculator!

DONE: http://nullprogram.com/blog/2009/06/23/

TODO: https://blog.markhepburn.com/2013/12/07/andrew-hyatts-emacs-calc-tutorials

MAYBE: https://www.emacswiki.org/emacs/Calc_Tutorials_by_Andrew_Hyatt

https://www.gnu.org/software/emacs/manual/html_mono/calc.html#TeX-and-LaTeX-Language-Modes

To get started: https://github.com/ahyatt/emacs-calc-tutorials

Basics: Note, there are many key-commands, and the complexity and power of calc makes it daunting, thus it’s often easiest to just “M-x calc-<fuzzu search>”, but key “x” already does that first part for you. Neat.

C-x * c start / or M-x calc

_ = enter negative number Q = square root p = precision (default 12)

= rational number, e.g. 1:7 (for 1/7)

d r = change display radix ’ = entter algebraic expression d B = change display to Big mode (similar to LaTeX display math-like) [ = Start entering vector / matrix x = call function / M-x

Enter hour-format: 1@ 59’ 30“

t N = insert time date

u c = convert units a x = expand algebraic expression a s = simplify algebraic expression a d = differentiate (!) a i = integrate (!)

Sum numbers in marked rectangle: C-x * r V R + which is:

C-x * – invokes calc-dispatch r – creates a vector from the marked rectangle V R – invokes calc-reduce on that vector

  • – reduce the vector using addition (or type ? to see all the available operators)

9.47. Undo-tree

Amazing stuff. See pragmaticemacs blog post for example, or elpa doc, ew, src.

(require 'undo-tree)
;; enable undo-tree-mode globally:
(global-undo-tree-mode)
Table 25: undo-tree keys
Key Alt. key Description
C-_ C-/ undo
M-_ C-? redo (same as undo of undo)
C-x u   undo-tree-visualize
C-r i u   save tree state to register
C-r i U   load tree state to register
Table 26: In undo-tree-visualize
Key Description
q quit undo-tree buffer
t toggle time display
d show diff
p/n previous (undo) / next (redo)
b/f switch to previous branch
left/right switch to previous branch
</> scroll left/right
RET select node and exit

10. MISC

10.1. Arduino

https://github.com/bookest/arduino-mode

https://www.emacswiki.org/emacs/ArduinoSupport

  • 0. maybe set $ARDUINODIR?
  • 1. Need arduino.mk as well, will give command line auto-compleation
  • 2. Add yourself to dialout group (whatever group allows access to serial port). You will probably need to kill off emacs and re-login to have this take effect.
  • 3. Run regular arduino IDE and set up preferences to point to correct board type/serial port (arduino.mk reads this for automagically populating fields below)
  • 4. Install arduino-mk from your repository/github, or http://bzr.ed.am/make/arduino-mk/files
  • 5. Create simple Makefile in the same directory as your .ino file. Contents can be as simple as this (only the include is truly necessary, all other lines can be omitted for simple sketches):

    BOARD_TAG = uno (see make show_boards)
    ARDUINO_LIBS = <space separated list of libs, arduino.mk will try to guess>
    MONITOR_PORT = /dev/ttyUSB0 (will be automatically guessed from IDE prefs)
    include /usr/share/arduino/Arduino.mk
    
  • 6. Call Makefile with M-x compile RET make -k upload
  • 7. if this doesn’t work, use https://platformio.org/ + emacs instead, e.g. http://docs.platformio.org/en/stable/ide/emacs.html (also, there’s http://inotool.org/), maybe need to do a:

    platformio init --ide emacs
    

    for it to create a .projectile file.

C-c . c Compile buffer C-c . U Upload compiled buffer

Must set port (one-time thing) in the GUI I think, then one can do:

arduino --upload filename
(setq auto-mode-alist (cons '("\\.\\(pde\\|ino\\)$" . arduino-mode) auto-mode-alist))
(autoload 'arduino-mode "arduino-mode" "Arduino editing mode." t)

10.2. epub

Nov is a mode for reading epub files, (or else emacs just opens it as an archive with *.html files for each chapter, available in melpa.

;; n/p for chapter navigation, and SPC for scroll, "F1 m" for help
(when (locate-library "nov")
  (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode)))

11. BBCODE MODE   mode

For forums. Available on github.

Table 27: bbcode keys
Key Action
C-c C-t c code
C-c C-t b bold
C-c C-t i italic
C-c C-t u undelined
C-c C-t q quote
C-c C-t l url
;;BBCode mode----------------------------------
;; TODO: not sure what is the best way to load this mode
(require 'bbcode-mode)
;; (autoload 'bbcode-mode "bbcode-mode" "For BBcode on forums" t)
;; (add-to-list 'auto-mode-alist '("\\.bbcode$" . bbcode-mode))

(add-hook 'bbcode-mode-hook
          (lambda ()
            ;;(set-fill-column 120)
            (auto-fill-mode -1)))
;;---------------------------------------------

12. C++ MODE   mode

Most of this is for both C and C++.

Update 2018-05: Looks very interesting, but I haven’t read it: https://nilsdeppe.com/posts/emacs-c++-ide2

This link: https://tuhdo.github.io/c-ide.html#sec-6 collects more than I have time to go through at the moment.

To set up emacs for powerful C/C++ editing, I recommend these two short videos part 1 and part 2.

Also, CppCon 2015: Atila Neves “Emacs as a C++ IDE” presentation introduces some nifty things (which he provides in cmake-ide through MELPA), using the compiler itself to set all local variables, suitable for large projects.

For jumping between definitions there’s ETags eller Ctags but I’ve heard Cscope is best. They all have problems finding the correct place in big projects, with complicated hierarchies.

12.2. TODO Irony-mode

For good auto-completion in C++ / C, use irony-mode that uses libclang compiler. (Requires cmake (to be used in the project) and clang installed).

Here’s a 3 minute video on setting it up: https://cestlaz.github.io/post/using-emacs-55-irony-completions/

(add-hook 'c++-mode-hook 'irony-mode)
(add-hook 'c-mode-hook 'irony-mode)
(add-hook 'irony-mode-hook 'irony-cdb-autosetup-compile-options)
(add-hook 'irony-mode-hook #'irony-eldoc)

(add-to-list 'company-backends 'company-irony)

12.4. One liners

;;Generic -------------------------------------
;; C++-specific. Which extensions should be associated with C++ (rather than C)
(add-to-list 'auto-mode-alist '("\\.h$"  . c++-mode)) ;h-files
(add-to-list 'auto-mode-alist '("\\.icc" . c++-mode)) ;implementation files
(add-to-list 'auto-mode-alist '("\\.tcc" . c++-mode)) ;files with templates

;;Indentation style:
;;(add-hook 'c-mode-common-hook '(lambda () (c-set-style "stroustrup")))
;;(add-hook 'c-mode-common-hook '(lambda () (c-set-style "linux")))
;;---------------------------------------------

12.5. Improve compile

;; Better compile buffer ----------------------
(require 'compile)
(add-hook 'c-mode-common-hook
          (lambda ()
            (setq
             compilation-scroll-output 'first-error  ; scroll until first error
             ;; compilation-read-command nil          ; don't need enter
             compilation-window-height 11)

            (local-set-key (kbd "<M-up>")   'previous-error)
            (local-set-key (kbd "<M-down>") 'next-error)

            (unless (file-exists-p "Makefile")
              (set (make-local-variable 'compile-command)
                   ;; emulate make's .c.o implicit pattern rule, but with
                   ;; different defaults for the CC, CPPFLAGS, and CFLAGS
                   ;; variables:
                   ;; $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $<
                   (let ((file (file-name-nondirectory buffer-file-name)))
                     (format "%s -o %s %s %s"
                             (or (getenv "CC") "g++")
                             (file-name-sans-extension file)
                             ;;(or (getenv "CPPFLAGS") "-DDEBUG=9")
                             (or (getenv "CFLAGS") " -g -O2")
                             file)))))
          ;;(number of things in " " in format must match number of arg. in getenv.)

          ;;This will run Make if there is a Makefile in the same directory as the
          ;;source-file, or it will create a command for compiling a single
          ;;file and name the executable the same name as the file with the extension
          ;;stripped.
          )
;;---------------------------------------------

12.6. Show function name in mod-line

;;Show function name in mod-line--------------
(add-hook 'c-mode-common-hook
  (lambda ()
    (which-function-mode t)))
;;--------------------------------------------

12.7. Smart navigation between h and cpp/cc files

Simple keybinding to switch between header and corresponding implementatio file. If marker is on an “#include” it goes to that file instead.

;;Navigate .h och .cpp ------------------------
;;Now, we can quickly switch between myfile.cc and myfile.h with C-c o.
;;Note the use of the c-mode-common-hook, so it will work for both C and C++.
(add-hook 'c-mode-common-hook
  (lambda()
    (local-set-key  (kbd "C-c o") 'ff-find-other-file)))
;;--------------------------------------------

12.8. Fold code-block

Keybinding collides with next-error, i.e. sub-optimal.

;;Fold code-block-----------------------------
(add-hook 'c-mode-common-hook
          (lambda()
            ;; ;; Collides with winner mode:
            ;; (local-set-key (kbd "C-c <right>") 'hs-show-block)
            ;; (local-set-key (kbd "C-c <left>")  'hs-hide-block)
            ;; (local-set-key (kbd "C-c <up>")    'hs-hide-all)
            ;; (local-set-key (kbd "C-c <down>")  'hs-show-all)

            ;; Now same/similar to org-mode hirarcy, but collides with
            ;; my (previous) setting for next-error/previous-error
            (local-set-key (kbd "M-<right>") 'hs-show-block)
            (local-set-key (kbd "M-<left>")  'hs-hide-block)
            (local-set-key (kbd "M-<up>")    'hs-hide-all)
            (local-set-key (kbd "M-<down>")  'hs-show-all)

            ;;hide/show code-block
            (hs-minor-mode t)))
;;--------------------------------------------

12.9. Indentation

I don’t want tabs at all in my source code, unless my collaborator is using tabs. This section deals with how to rectify the problem.

12.9.1. My Style:

This style uses spaces for indentation, unless the code is written using tabs, in which case dtrt-indent autodetects. Then it uses tabs, and they are 3 columns wide.

Does not work (yet): cant re-indent comment-lines at column 0, and class indention is fucked.

;;My-C++-style---------------------------------
;; Define my own style for c++-mode:
(c-add-style "my-style"
             '("linux"                    ;; dont indent { } like "gnu" style does (use same level as "for" "if" etc.)
               (indent-tabs-mode . nil)   ;; don't use tabs use spaces for indentation
               (c-basic-offset . 2)       ;; indent 2 columns (default in linux style I think)
               (tab-width . 3)            ;; if there is a tab it is displayed as 3 columns (Carl's wishes)
               (c-tab-always-indent . t)  ;; TAB-key only indents.
               ;; (backward-delete-function . nil) ;; DO NOT expand tabs to spaces when deleting, (Not working?)
               ;;(c-syntactic-indentation . t)     ;; Is default: indent according to syntax, not prev. line
               ;;(c-set-offset 'substatement-open . 0)     ;; brackets at same indentation level as statements they open
               (c-offsets-alist . ((inline-open . 0)       ;; custom indentation rules
                                   (brace-list-open . 0)            ;; what does this do?
                                   (statement-case-open . +)))      ;; what does this do?


               ))

(defun my-c++-mode-hook ()
  (c-set-style "my-style")               ;; use my-style defined above
  ;; (auto-fill-mode)                     ;; Auto-insert hard line breaks after current-fill-column
  ;; (c-toggle-auto-hungry-state 1)       ;; Both auto-newline (after } etc.) and hungry delete
  )

  (add-hook 'c++-mode-hook 'my-c++-mode-hook)
;;---------------------------------------------

12.9.2. dtrt-indent

Gets loaded first time we enter C or C++ mode. source. Note that with the (current, 2014-03-01) default of dtrt-indent-min-indent-superiority 100, dtrt will not adjust if number of single indentation lines are too small compared to double indentated for instance. See documentation for better explenation.

;; Guess indentation style --------------------
;;Automagically find the indentation style in the source file.
;;(Good for me, since my collaborator is using tabs -- the horror!)

;;Use autoload for faster start-up (rather than "require"):
;;(autoload 'dtrt-indent-mode "dtrt-indent" "Adapt to foreign indentation offsets" t)
;;(add-hook 'c-mode-common-hook 'dtrt-indent-mode)

(add-hook 'c-mode-common-hook
          (lambda()
            (when (require 'dtrt-indent nil 'noerror)
              (dtrt-indent-mode t)
              ;; don't be so strict about getting the guess right
              (setq dtrt-indent-min-indent-superiority 50))))
;;---------------------------------------------

13. ERC MODE   mode

ERC is the Emacs IRC-client. It works great, and has several useful modules enabled by default, like auto-complete all nicknames in current channel, and clickable url’s (or do RET), and channel tracking in the mode-line.

Table 28: Standard IRC commands
IRC command Key Description
  M-p erc-previous-command
  M-n erc-next-command
/join #foo C-c C-j join channel #foo.
/part msg C-c C-p leave current channel.
/quit msg C-c C-q disconnect & leave message msg for all to see
/gquit msg   quit all servers, with message msg
/nick newnick   changes nickname
/names (in channel) C-c C-n runs /names #channel in current channel
/query nick   open private buffer shared with “nick”.
    (both must be registered)
/dcc    
/reconnect    
/amsg   send message to all channels on server
/away reason   mark user as away, for “reason”
/clear   clear/wipe out window contents
/idle nick   show idle time for user nick

See irc help.

Switching between buffers can be done as usual (C-xb,C-x left), or by C-c C-b when already in one erc-buffer. C-c C-SPC cycles through buffers with changes, and finaly goes to most recent non-erc buffer.

To display channel nicknames in a side buffer, just add the following to your .emacs or ERC configuration file:

(require 'erc-nicklist)

Then activate the nicklist buffer, using M-x erc-nicklist RET in the channel buffer (you need to do this for each channel buffer if you want a nicklist for each channel).

M-x erc-nicklist-quit closes the nicklist buffer.

13.1. Auto connect

Automatically connect to the irc-networks, and their channels. I made it into a function, that I must call manually, so it doesn’t start unless I explicitly tells it to.

;; Auto joining--------------------------------
;; Make sure to use wildcards for e.g. freenode as the actual server
;; name can be be a bit different, which would screw up auto connect.

(defun erc-hook-me-up ()
  "Call function manually to start all my ERC-buffers.

If the code is put directly into ~/.emacs (without this function
around it), it will restart ERC each time I reload the config, or
start a new emacs session, which is silly."
  (interactive)
  (require 'erc-join)
  (erc-autojoin-mode t)

  (erc :server "irc.freenode.net" :port 6667 :nick "mynick" :password "mypassword") ;;XXX
  ;;(erc :server "irc.oftc.net" :port 6667 :nick "mynick")

  ;; ;;for running Bitlbee, to check Gmail chatt (Google Talk).
  ;; ;;(erc :server "im.bitlbee.org" :port 6667 :nick "mynick")
  ;; (erc :server "localhost" :port 6667 :nick "jag")

  (setq erc-autojoin-channels-alist
        '((".*\\.freenode.net" "#wanderlust" "#pioneer" "#next-browser"
           ;;"#ubuntu-se"  "#emacs"  "#conkeror" "#archlinux" "#debian" "##c++" "#gnuplot" "#zsh"
           ;;"#stumpwm" "#minecraft" "#lisp" "#scheme" "#lispgames" "##ibmthinkpad" "#pioneer"
           )
          ;;          ("irc.irchighway.net" "#comics-anonomous")
          ;;          ("localhost" "&bitlbee")  ;; don't know if this it right.
          ;;          ("oftc.net" "#suckless" "#bitlbee")
          )))
;;---------------------------------------------

13.2. General commands

General one-line commands go here

;;General-settings----------------------------------

;;If I post while status is "away", set me as back. (i.e. unset /away)
(setq erc-auto-discard-away t)

;;set defaults (not used when auto-joining I think).
(setq erc-server "irc.freenode.net"  ;default, works well
      erc-port 6667                  ;default, works well
      erc-nick "mynick"
      ;;      erc-user-full-name user-full-name
      ;;      erc-email-userid "userid"    ; for when ident is not activated
      erc-prompt-for-password t) ;whether to query for passwords or not required for OPN.

;;Kill buffers for channels after /part
(setq erc-kill-buffer-on-part t)
;;Kill buffers for private queries after quitting the server
(setq erc-kill-queries-on-quit t)
;;Kill buffers for server messages after quitting the server
(setq erc-kill-server-buffer-on-quit t)

;; utf-8 always and forever
(setq erc-server-coding-system '(utf-8 . utf-8))

;;TEST: Interpret mIRC-style color commands in IRC chats
(setq erc-interpret-mirc-color t)

;;Disable text "buttonization", since slow & is useless in text mode
;;(erc-button-mode nil)

;;If someone sends a /notice don't just show it in the server buffer,
;;but also in the mini-buffer.
(setq erc-echo-notices-in-minibuffer-flag t)

;;enable fly-spell for my input (only). Can have channel specific
;;dictionaries.
(erc-spelling-mode 1)

(setq erc-spelling-dictionaries '(("irc.freenode.net:6667"   "american")
                                  ("#pioneer"                "british-ize")
                                  ("&bitlbee"                "svenska")
                                  ("#ubuntu-se"              "svenska")
                                  ("irc.oftc.net:6667"       "american")
                                  ("irc.irchighway.net:6667" "american")
                                  ("localhost:6667"          "svenska")))
;;---------------------------------------------

13.3. Don’t track every little thing

In the Mode-line you get a notice when the status of one of the channels/buffers changes (in a: [#e,#i…]), but we don’t need to be notified upon every change in the channels status.

;;Don't track every little thing: -------------
;;shown in channel-status in modline...
(erc-track-mode t)
;;But exclude these: (numbers are for the irc-server)
(setq erc-track-exclude-types '("JOIN" "NICK" "PART" "QUIT" "MODE"
                                 "324" "329" "332" "333" "353" "477"))

;; don't show any of this (separate from command above...)
;;(setq erc-hide-list '("JOIN" "PART" "QUIT" "NICK"))

;;For the bitlbee channel:
(defun erc-ignore-unimportant (msg)
  (if (or (string-match "*** localhost has changed mode for &bitlbee to" msg)
          ;;(string-match "Unknown error while loading configuration" msg)
          (string-match "Account already online" msg))
      (setq erc-insert-this nil)))
(add-hook 'erc-insert-pre-hook 'erc-ignore-unimportant)

;;---------------------------------------------

13.4. Make header red when IRC connection is closed

Makes the header-line red when the IRC-server is disconnected, as the “ERC: CLOSED” message in the mod-line easily goes by without a notice. Very useful.

;; change header face if disconnected----------
(defface erc-header-line-disconnected
  '((t (:foreground "black" :background "indianred")))
  "Face to use when ERC has been disconnected.")

(defun erc-update-header-line-show-disconnected ()
  "Use a different face in the header-line when disconnected."
  (erc-with-server-buffer
   (cond ((erc-server-process-alive) 'erc-header-line)
         (t 'erc-header-line-disconnected))))

(setq erc-header-line-face-method 'erc-update-header-line-show-disconnected)
;;---------------------------------------------

13.5. Colorize NickNames

Gives all nicknames colors, by using md5sum on the first characters, to get a rrggbb value. emacsWiki:ErcHighlightNicknames

Note: I’m having problems with this in emacs 24.3.91.1, so I use erc-hl-nicks.el instead.

;;Make NickName colors unique------------------
(with-eval-after-load "erc"
  (add-to-list 'erc-modules 'highlight-nicknames)
  (erc-update-modules))
;;---------------------------------------------

13.6. Match/highlight words

;;Match/highlight words------------------------
;;cause all instances of these words to be highlighted in the channel buffers.
;;Also: if you are using track-modified-channels-mode, channels that mention
;;the keywords in them will appear in a difference face in your modeline.

;;highlight differently when running the bitlbee command: blist
(setq erc-keywords '((".*Online.*" (:foreground "green"))
                     (".*Busy"     (:foreground "red"))
                     (".*Away"     (:foreground "orange"))
                     (".*Do not"   (:foreground "red"))
                     (".*Idle"     (:foreground "orange"))
                     ;; Above for bitlbee blist command.
                     ;; ("wanderlust" (:foreground "green"))
                     ;; ("mynick"   (:foreground "red"))
                     ))
;;---------------------------------------------

13.7. Logging

Logging is not enabled by default. To save a log wile in ERC-mode: C-c C-l (calls erc-save-buffer-in-logs).

buffer hasn’t been saved before, as the number 1 (point-min)).

The region between `erc-last-saved-position’ and `erc-insert-marker’ is saved to the current buffer’s logfile, and `erc-last-saved-position’ is updated to reflect this.

;;Logs ----------------------------------------
(require 'erc-log)
(add-to-list 'erc-modules 'log)

(setq erc-log-insert-log-on-open nil             ;;is on by default
      erc-log-channels-directory "~/.emacs.d/erc-logs/"   ;;default is C-c C-l saves to ~/logs/
      erc-save-buffer-on-part t                  ;;autosave log when /part or /quit
      )

(if (not (file-exists-p erc-log-channels-directory))
    (mkdir erc-log-channels-directory t))
;;---------------------------------------------

13.8. Timestamp on left

This is useful when searching logs. I’m not using it though.

;;Timestamp on left----------------------------
;; Set up timestamp on each line on the left
(setq erc-timestamp-only-if-changed-flag nil
      erc-timestamp-format "[%R-%m/%d] "
      erc-insert-timestamp-function 'erc-insert-timestamp-left)
;;---------------------------------------------

13.9. Functions

Useful functions for ERC mode:

;;---------------------------------------------
;; Clears out annoying erc-track-mode stuff for when we don't care.
;; Useful for when ChanServ restarts :P
(defun erc-reset-track-mode ()
  (interactive)
  (setq erc-modified-channels-alist nil)
  (erc-modified-channels-update))
;;(global-set-key (kbd "C-c r") 'erc-reset-track-mode)
;;---------------------------------------------

13.10. Function to show number of users logged in

Call through M-x, or through /howmany.

;;---------------------------------------------
(defun erc-cmd-HOWMANY (&rest ignore)
  "Display how many users (and ops) the current channel has."
  (interactive)
  (erc-display-message nil 'notice (current-buffer)
                       (let ((hash-table (with-current-buffer
                                             (erc-server-buffer)
                                           erc-server-users))
                             (users 0)
                             (ops 0))
                         (maphash (lambda (k v)
                                    (when (member (current-buffer)
                                                  (erc-server-user-buffers v))
                                      (incf users))
                                    (when (erc-channel-user-op-p k)
                                      (incf ops)))
                                  hash-table)
                         (format
                          "There are %s users (%s ops) on the current channel"
                          users ops))))
;;---------------------------------------------

13.11. Bitlbee

Bitlbee is an awesome instant messenger that pipes all messages from GMail, MSN, etc, to a local IRC server, which you can connect to through any IRC-client, such as ERC or IRSSI.

source: link, bitlbee.el and http://wiki.bitlbee.org/

13.11.1. getting started

Installing:

sudp apt-get install betlbee

Starting the server:

sudo /etc/init.d/bitlbee start

Connect to:

localhost:6667

Now you need to register an account on the channel:

register mypassword

Now start adding accounts you do,

For Jabber:

account add jabber username@jabber.org yourpassword

For MSN:

account add msn username@hotmail.com yourpassword

For ICQ:

account add oscar 648244897 yourpassword login.icq.com

For TWITTER:

account add twitter username password

For AIM:

account add oscar 321454897 yourpassword login.oscar.aol.com

For YIM:

account add yahoo username yourpassword

For GMAIL:

account add jabber username@gmail.com youpassword talk.google.com:5223:ssl

If there’s a problem try port 5223 or 5222.

To see which number to use, run:

account list

To turn on an account do:

account 0 on

Now save your configuration with:

save

Turn off all accounts

account off

Remove account

account 0 del

Remove everything, including my login

drop mypassword

Things to set:


set strip_html true set auto_connect true set auto_reconnect true set save_on_quit true

Table 29: Bitlbee Commands
Commands: description
blist will list your buddies and their status.
blist all show all buddies
account list list all accounts available in the bitlbee server
account del [#] delete account number #. Same number as in the list
rename [user] [alias] change name of a person
add [#] [user]  
help  
set view account settings
save ?
set charset ISO8859-1 gives Norwegian/danish åäö -> åæø
  (run in terminal “iconv -l” to see available charset)
drop remove my entire account

13.11.2. code for .emacs

;;Bitlbee--------------------------------------
;;connect to bitlbee
(when (require 'bitlbee nil 'noerror)
  (defvar bitlbee-password "mypassword")           ;;XXX

  (defun bitlbee-identify ()
    "If we're on the bitlbee server, send the identify command to the
    &bitlbee channel."
    (when (and (string= "localhost" erc-session-server)
               (string= "&bitlbee" (buffer-name)))
      (erc-message "PRIVMSG" (format "%s identify %s"
                                     (erc-default-target)
                                     bitlbee-password))))
  (add-hook 'erc-join-hook 'bitlbee-identify)

  (defun bitlbee-connect ()
    (interactive)
    (save-window-excursion
      (when (get-buffer "&bitlbee")
        (switch-to-buffer "&bitlbee")
        (erc-message "PRIVMSG" (concat (erc-default-target) " identify " bitlbee-password))
        (erc-message "PRIVMSG" (concat (erc-default-target) " account on 0")
                     (erc-message "PRIVMSG" (concat (erc-default-target) " account on 1"))))))
  (setq bitlbee-reconnect-timer (run-with-timer 0 60 'bitlbee-connect))
  )

;;start bitlbee server on startup:
(erc :server "localhost" :port "6667" :nick "jag" :password bitlbee-password)
;;---------------------------------------------

13.12. Erc-tex

If you have LaTeX installed, you most likely also have dvipng, and then you can use this nice mode. It automatically renders any math between $$. Since I’m not using math that often in my erc, I autoload it and call it manually M-x erc-tex-mode if I feel the need for it.

(autoload 'erc-tex-mode "erc-tex" "insert math in \"$$\" in ERC buffer" t)

14. FORTRAN MODE   mode

Fortran is terrible. But this is how I make it less so.

Manual: Emacs normally uses Fortran mode for files with extension ‘.f’, ‘.F’ or ‘.for’, and F90 mode for the extensions ‘.f90’, ‘.f95’, ‘.f03’ and ‘.f08’.

Default “fortran-mode” is fixed fortran 77 form. We want to use free fortran 90 form i.e. “f90-mode”:

(add-to-list 'auto-mode-alist '("\\.f\\'" . f90-mode))

15. GEDCOM MODE   mode

Standard system for geneaology. Used in C-programs (ncurses based) LifeLine, and can be imported/exported in python GTK-program Gramps.

#+begin_src emacs-lisp :tangle .emacs (autoload ’gedcom-mode “gedcom”) (setq auto-mode-alist (cons ’(“\\.ged\(" . gedcom-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("lltmp[0-9a-zA-Z.]+\)” . gedcom-mode) auto-mode-alist)) #+end_src emacs-lisp :tangle .emacs

16. GNUPLOT MODE   mode

I’m nowadays using gnuplot-mode from melpa.

There is a light-weight (as in few lines of code) Gnuplot-mode which uses the compilation buffer for compilation-error handling, easy keybinding, and syntax highlighting. I keep a copy in my git.

Also, rainbow-mode is nice to give color to all color strings like “#rrggbb”.

Table 30: Gnuplot keys
Key command
C-c C-c compile buffer
C-c C-r compile-run region
C-c C-b compile-run buffer
;;============================================
;;              GNUPLOT-MODE
;;============================================

;; Automatically load gnuplot mode for all .gp & .gnu extension
(setq auto-mode-alist (append '(("\\.gp$" . gnuplot-mode)) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.gnu$" . gnuplot-mode)) auto-mode-alist))

;; color background in any color string: #RRGGBB with relevant color
(autoload 'rainbow-mode "rainbow-mode" "rainblow-mode." t)
(add-hook 'gnuplot-mode-hook 'rainbow-mode)
;;============================================

17. GUD MODE (gdb debugging)   mode

Awesome debugging power at my fingertips. Run with

M-x gdb

or

gdb --annotate=3 ./yourbinary

See emacswiki

17.1. Main stuff

;;Make up/down behave as in terminal
;;run it like this "M-x gdb",
;;  gdb --annotate=3 ./yourBinary
(add-hook 'gud-mode-hook
          '(lambda ()
             (local-set-key [home] ; move to beginning of line, after prompt
                            'comint-bol)
             (local-set-key [up] ; cycle backward through command history
                            '(lambda () (interactive)
                               (if (comint-after-pmark-p)
                                   (comint-previous-input 1)
                                 (previous-line 1))))
             (local-set-key [down] ; cycle forward through command history
                            '(lambda () (interactive)
                               (if (comint-after-pmark-p)
                                   (comint-next-input 1)
                                 (forward-line 1))))
             )
          (setq gdb-many-windows t))
;;============================================

18. LaTeX MODE   mode

AuCTex is a must for Latex. It can be installed through the package manager in your OS (ubuntu/debian: auctex.deb), or through ELPA (internal package system of Emacs).

AuCTeX has tonnes of features, but preview and reftex are modes I find extremely useful. Reftex is amazing, it inserts labels, references, citations, right where you want them, and shows table of contents of sections, and labels.

18.1. Keys for LateX with AuCTeX installed

Table 31: Excluding ReTeX-keys, these are my most used AuCTeX keys (at least the first 5)
Key binding function
C-c C-c compile buffer if any changees, else view
C-c C-r compile region (into region.dvi) / view region
C-c C-s insert section
C-c C-e insert environment
C-u C-c C-e change enclosing environment
C-c ] close environment
C-c ? gives documentation for the symbol at point
   
C-c ~ math mode
C-c C-m macro insert (or C-c RET)
C-c C-w something with overfull boxes
   
C-c C-p C-s preview section
C-c C-q C-s automatic formatting of a section:
Table 32: Keys for RefTeX (note: RefTeX is not on by default in AuCTeX, check config)
Key binding function
C-c = table of contents
C-c ( create label
C-c ) reference label
C-c & try when marker at a ref, label, cite, index
C-c [ search citations, uses file used by \bibliography
   
C-c / insert index
C-c < alternative index, more advanced
C-c \ add word or selection to index phrase file
C-c > display/edit index
Table 33: Preview keys for typesetting equations right in the document (using magic and png?)
Key binding function
C-c C-k kill running preview process
   
C-c C-p C-s preview-section
C-c C-p C-r preview-region
C-c C-p C-b preview-buffer
C-c C-p C-d preview-document
   
C-c C-p C-c C-p preview-clearout-at-point
C-c C-p C-c C-s preview-clearout-section
C-c C-p C-c C-r preview-clearout
C-c C-p C-c C-b preview-clearout-buffer
C-c C-p C-c C-d preview-clearout-document

18.2. Miscellaneous

;; choose one, for what happens with long lines:
;;(add-hook 'LaTeX-mode-hook 'visual-line-mode)
;;(add-hook 'LaTeX-mode-hook 'auto-fill-mode)

(add-hook 'LaTeX-mode-hook
          '(lambda ()
             (ispell-change-dictionary "american" nil)

             ;;Make equations into images & show in emacs:
             (autoload 'latex-math-preview-expression "latex-math-preview" nil t)
             (autoload 'latex-math-preview-save-image-file "latex-math-preview" nil t)
             (autoload 'latex-math-preview-beamer-frame "latex-math-preview" nil t)))

(setq font-latex-fontify-script nil ;;Don't fontify sub/super: _ ^
      TeX-auto-save t               ;;enable parse on save
      TeX-parse-self t              ;;enable parse on load
      TeX-auto-untabify t           ;; remove Tabs at save
      ispell-check-comments nil)    ;;don't spell check comments

;;Auto choose Swedish if usepackage{babel}[swedish]
;;so that:  Shift+2-> '' rather than ", or similar...
(add-hook 'TeX-language-sv-hook
(lambda() (ispell-change-dictionary "svenska")))

18.3. Math $$-matching

;;Math-$$-matchning---------------------------
(setq LaTeX-mode-hook'
      (lambda () (defun TeX-insert-dollar ()
                   "custom redefined insert-dollar"
                   (interactive)
                   (insert "$$")           ;;in LaTeX mode, typing "$" automatically
                   (backward-char 1))))    ;;insert "$$" and move back one char.
;;--------------------------------------------

18.4. RefTeX awesomeness

;;RefTeX--------------------------------------
;;Navigate sections by right mouse button. Similar to as C-c =
(add-hook 'reftex-load-hook 'imenu-add-menubar-index)
(add-hook 'reftex-mode-hook 'imenu-add-menubar-index)

(add-hook 'LaTeX-mode-hook 'turn-on-reftex)            ;;with AUCTeX LaTeX mode

(autoload 'reftex-mode    "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" t)

;; To integrate RefTex even closer with AUCTeX.  E.g: when C-c C-s
;; or C-c C-e is called, AUCTex will call RefTeX, which will insert
;; a label automatically instead of having AUCTeX ask you for one;
;; When C-c C-s AUCTeX will update section list in RefTeX; RefTeX
;; will also tell AUCTeX about new label, citation, and index keys,
;; and add them to completions list.
(setq reftex-plug-into-AUCTeX t)

;;Make C-u prefixed commands not re-parse entire doc.
(setq reftex-enable-partial-scans t)

;; ;;Even with partial-scan enables, reftex must make one full scan,
;; ;;this saves the result to a file "*.rel"
;; (setq reftex-save-parse-info t)

;; ;; use separate buffer for selecting each label type
;; (setq reftex-use-multiple-selection-buffers t)
;;--------------------------------------------

18.5. Beamer – compile single frame

Latex-mode default behaviour is useful when editing a Beamer presentation:

  • “If you want to compile just one frame, you can press C-c .

(LaTeX-mark-environment) – possibly with a prefix argument (or just press it a few times) to mark the current frame, and then press C-c C-r (TeX-command-region). The latter command is extremely useful. It takes the “pinned region” (i.e., if there’s no active region, it remembers the previously used one), saves it to a temporary file (together with the whole preamble), and launches a compile or view command on that. This way I can cut down on the compile time by at least an order of magnitude.“

Also, beamer + orgö-mode can be used to make very nice looking posters.

(defun LaTeX-command-beamer-frame ()
  "Run `TeX-command-region' on the current frame environment."
  (interactive)
  (save-mark-and-excursion
   (while (not (looking-at-p "\\\\begin *{frame}"))
     (LaTeX-find-matching-begin))
   (forward-char)
   (LaTeX-mark-environment)
   (TeX-command-region)))

19. LISP MODE   mode

19.1. ParEdit

paredit (ew) is a must if programming any Lisp dialect. It has a threshold, no matter if you’re pro or beginner, but it is worth the effort.

This animated example page is nice, although the animations are way too fast.

(autoload 'paredit-mode "paredit"
  "Minor mode for pseudo-structurally editing Lisp code." t)
(eval-after-load "paredit" '(diminish 'paredit-mode))
(add-hook 'emacs-lisp-mode-hook       (lambda () (paredit-mode +1)))
(add-hook 'lisp-mode-hook             (lambda () (paredit-mode +1)))
(add-hook 'lisp-interaction-mode-hook (lambda () (paredit-mode +1)))
(add-hook 'scheme-mode-hook           (lambda () (paredit-mode +1)))
(add-hook 'slime-repl-mode-hook       (lambda () (paredit-mode +1)))
(add-hook 'ielm-mode-hook             (lambda () (paredit-mode +1)))
(add-hook 'hy-mode-hook               (lambda () (paredit-mode +1)))
(add-hook 'inferior-hy-mode-hook      (lambda () (paredit-mode +1)))
(add-hook 'clojure-mode-hook          (lambda () (paredit-mode +1)))
(add-hook 'cider-repl-mode-hook       (lambda () (paredit-mode +1)))
;; ;;Make eldoc aware of paredit's most used commands
;; (add-hook 'paredit-mode-hook
;;           (lambda) ()
;;           (require 'eldoc)
;;           (eldoc-add-command
;;            'paredit-backward-delete
;;            'paredit-close-round))

(add-to-list 'auto-mode-alist '("\\.hy\\'" . hy-mode))

(add-hook 'hy-mode-hook
  (lambda()
    (local-set-key (kbd "C-c C-e") 'hy-shell-eval-current-form)
    (local-set-key (kbd "C-c C-r") 'hy-shell-eval-region)
    (local-set-key (kbd "C-c C-b") 'hy-shell-eval-buffer)))

(add-hook 'emacs-lisp-mode-hook
          (lambda ()
            (paredit-mode t)

            (turn-on-eldoc-mode)
            (eldoc-add-command
             'paredit-backward-delete
             'paredit-close-round)

            (local-set-key (kbd "RET") 'electrify-return-if-match)
            (eldoc-add-command 'electrify-return-if-match)))


19.2. Eldoc

As you type a function (in emacs-lisp) in current buffer eldoc shows in the minibuffer the documentation for that function, arguments etc.

http://emacswiki.org/emacs/ElDoc

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
(add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)
(add-hook 'ielm-mode-hook 'turn-on-eldoc-mode)

(eval-after-load "eldoc" '(diminish 'eldoc-mode "elD"))

;;Also have documentation when writing Scheme-code:
(when (locate-library "scheme-complete")
  (autoload 'scheme-get-current-symbol-info "scheme-complete" nil t)
  (add-hook 'scheme-mode-hook
            (lambda ()
              (make-local-variable 'eldoc-documentation-function)
              (setq eldoc-documentation-function 'scheme-get-current-symbol-info)
              (eldoc-mode))))

19.3. Minibuffer

Have nicer emacs-list support in the “M-x” prompt

;; When evaluating code in Emacs, put eldoc ducumentation in modeline instead!
;; http://endlessparentheses.com/sweet-new-features-in-24-4.html
(add-hook 'eval-expression-minibuffer-setup-hook #'eldoc-mode)
(add-hook 'eval-expression-minibuffer-setup-hook #'paredit-mode)

20. LUA MODE   mode

Lua is a powerful scripting/configuration language.

;;lua-mode------------------------------------
(autoload 'lua-mode "lua-mode" "Lua editing mode." t)
(add-to-list 'auto-mode-alist '("\\.lua$" . lua-mode))
(add-to-list 'interpreter-mode-alist '("lua" . lua-mode))

(add-hook 'lua-mode-hook 'hs-minor-mode)

(add-hook 'lua-mode-hook
      (lambda ()
        (setq indent-tabs-mode t)
        (setq tab-width 4)
        (setq lua-indent-level 4)))
;;--------------------------------------------

21. MAGIT / GIT   mode

An extremly powerful mode for managing Git repositories. It doesn’t hide the complexity of git, so you still need to understand staging, committing, etc.

Makes rebasing, and resolving conflicts and seeing the diff amazing.

https://cestlaz.github.io/posts/using-emacs-47-magit http://endlessparentheses.com/it-s-magit-and-you-re-the-magician.html https://emacsair.me/2017/09/01/magit-walk-through/#fnref:1

  • When visiting a file, C-c M-g brings up a status window for operations on

file (stage, unstage, log, blame, etc.)

  • The new command magit-edit-line-commit, which is available from the file

popup (on e), can be used to edit the commit that added the current line. Likewise magit-diff-edit-hunk-commit can be used to do the same from within a diff, where C-c C-e is bound to it. The editing is usually done using an interactive rebase that stops at the appropriate commit. (url)

M-x magit-status to see git status, and in the status buffer:

Table 34: Basic Magit keys:
Key Description
n/p next/previous, up / down,
h help, in what ever context / pop-up
s to stage file/region (or files if many are highlighted)
u to unstage file (or files if many are highlighted)
c c to commit (type the message then C-c C-c to actually commit)
b b to switch to another branch
P p to do a git push
F F to do a git pull
TAB toggle diff on file/commit
l l log
b branch
r e rebase, interactive
A cherry pick
k discard change
!! run git command from magit

M-1 (hide) to M-4 (show full diff) toggles how much to display in the magit-status window. M-2 is the sanest one. For more info one can toggle with TAB on file to show diff.

When viewing a diff +/- will expand how much code to show surrounding the diff, 0 resets to default. RET takes you from the diff to the full file.

Table 35: M-x magit-blame keys
RET Shows commit at point
SPC “DWIM”. Show commit or scroll down
DEL As above, but scroll up
n Move to next chunk
p Move to previous chunk
N Move to next chunk of the same commit
P Move to prev. chunk of the same commit
t Toggles showing commit headings
b Opens Blame popup
b b Blame commit at point

Also install git-timemachine, mode activated by M-x git-timemachine (as read-only), then use n/p for next version of the file, or t for selecting revision by commit message, or b/c for magit-blame, and c show current commit

MAGIT 1.* posts:


http://oremacs.com/2015/03/11/git-tricks/ http://endlessparentheses.com/automatically-configure-magit-to-access-github-prs.html?source=rss http://www.masteringemacs.org/article/introduction-magit-emacs-mode-git

Rewrite commit messages https://shingofukuyama.github.io/emacs-magit-reword-commit-messages/

rebase / squash commits in magit: http://www.howardism.org/Technical/Emacs/magit-squashing.html

MAGIT 2.* posts:


“Many of the variable names have been changed so if you are using any in your init.el you will probably need to change them. In my case, I had to change magit-repo-dirs to magit-repository-directories.”

http://endlessparentheses.com/create-github-prs-from-emacs-with-magit.html

Tips on every-day usage: http://endlessparentheses.com/it-s-magit-and-you-re-the-magician.html

;;(global-set-key (kbd "C-x g") 'magit-status)
(global-set-key (kbd "<f8>")  'magit-status)

21.1. git gutter fring

Show with +/- in fringe which lines have been changed. https://github.com/syohex/emacs-git-gutter-fringe

;; You need to install fringe-helper.el
(require 'git-gutter-fringe)
(global-git-gutter-mode)
;; (setq git-gutter-fr:side 'left-fringe)

22. MAKEFILE MODE   mode

Note, since version 4.0 of make, it is now fully extendable with the GNU Scheme Lisp interpreter Guile.

22.1. no trailing whitespace

Makefiles are picky about whitespaces at the end of lines.

(add-hook 'makefile-mode-hook
          (lambda()
            (setq show-trailing-whitespace t)))

;;This sets the buffer-local variable show-trailing-whitespace,
;;only for Makefiles (including Makefile.am and Makefile.in)
;;============================================

23. MARKDOWN MODE (GIT)   mode

Markdown mode from (git) for typsetting git comments for issues and pull requests. This cheat sheet is a good place to start with markdown, and github flavored markdown (gfm), which is what I use.

(autoload 'gfm-mode "markdown-mode"
  "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.text\\'" . gfm-mode))
(add-to-list 'auto-mode-alist '("\\.markdown\\'" . gfm-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . gfm-mode))

;; ;; I think with gfm-mode instead of markdown-mode, I don't need this
;; (add-hook 'markdown-mode-hook '(lambda ()
;;                                         ;(set-fill-column 999999)
;;                                  (auto-fill-mode -1)))

24. MATLAB MODE   mode

Seems like the matlab.el file is not very well maintained.

Requires “matlab.el” which is a part of emacs-goodies-el.deb on Debian.

;;============================================
;;              MATLAB-MODE
;;============================================
(autoload 'matlab-mode "matlab" "Enter Matlab mode." t)
(setq auto-mode-alist (cons '("\\.m\\'" . matlab-mode) auto-mode-alist))
(autoload 'matlab-shell "matlab" "Interactive Matlab mode." t)

;; User Level customizations (You need not use them all):
(setq matlab-shell-command-switches '("-nosplash -nojvm"))
(setq matlab-indent-function t)       ;if you want function bodies indented
(setq matlab-verify-on-save-flag nil) ;turn off auto-verify on save
(defun my-matlab-mode-hook ()
  (setq fill-column 76))              ;where auto-fill should wrap
(add-hook 'matlab-mode-hook 'my-matlab-mode-hook)
(defun my-matlab-shell-mode-hook ()
  '())
(add-hook 'matlab-shell-mode-hook 'my-matlab-shell-mode-hook)

;; use F10 to submit selected txt
;;(define-key matlab-mode-map (quote [f10]) `matlab-shell-run-region)

;; This package requires easymenu, tempo, and derived.
;; This package will optionally use custom, shell, and gud.
;;============================================

25. ORG MODE   mode

Org mode (overview), possibly the easiest, most useful, most awesome thing in Emacs. Perfect for creating list or documents with hierarchy. (Also, it’s markup language is vastly superior to markdown).

“Org-mode is so expansive that explaining it to someone who hasn’t used is a challenge. It’s part calendar, part to do list, part literate programming editor, part interactive notebook (in the style of iPython), part spreadsheet, part link-able document web (in the style of wikipedia). I’ve heard of it being used to typeset academic articles (you can export to pdf), and I personally use it as a blog post editor and note taking app. Some use it as a time sheet, keeping track of billable hours.” source

Emacs org-mode examples and cookbook (alt source)

For using org to blog, this and this lays out how it’s done, and here (using org-publish and no third party stuff, but then use this for RSS generation).

Argues org-publish is the only blogging system that meets his requirements:

https://ambrevar.xyz/blog-architecture/index.html + useful links to other org-mode built blogs https://gitlab.com/ambrevar/ambrevar.gitlab.io https://orgmode.org/worg/org-blog-wiki.html

RSS generator for mulit-org-files blogs

TO-read: http://endlessparentheses.com/how-i-blog-one-year-of-posts-in-a-single-org-file.html

M-x org-entities-help shows: available symobls, org-entity LaTeX code, and HTML code for special symbols. As an org buffer.

Org-mode can be used for infinite things (almost like an Emacs within Emacs!):

For very good tutorial on using code blocks (even executing blocks on remote machine!), this is a very nice video: Literate Devops with Emacs (his git, especially his org-conf)

25.1. Documentation, keys

Org mode: greatest invention since the wheel! Shortcut cheat sheet.

Alt-Shift-left/right - change heading and all in sub-tree Alt-left/right - change only this heading

Table 36: General keys
Key binding function
C-c C-t set TODO/DONE on line.
M-RET new section (same level)
M-Shift-RET new section (same level) + “TODO”
Shift-TAB toggle show-mode: overview, contents, showall
M-S-up/down move entire tree one level up/down
C-c C-o open-at-point (expandera)
C-c C-e export org-file
C-c n/p next/previous section
Table 37: Footnotes:
Key binding function
C-c C-x f Footnote-action “do what I want”
C-c C-c Jump between reference and definition
C-c ’ Edit footnote in spearate window
   

When this command is called with a prefix argument, a menu of additional options is offered:

  • s Sort the footnote definitions by reference sequence. During editing, Org makes no effort to sort footnote definitions into a particular sequence. If you want them sorted, use this command, which will also move entries according to org-footnote-section. Automatic sorting after each insertion/deletion can be configured using the option org-footnote-auto-adjust.
  • r Renumber the simple fn:N footnotes. Automatic renumbering after each insertion/deletion can be configured using the option org-footnote-auto-adjust. S Short for first r, then s action. n Normalize the footnotes by collecting all definitions (including inline definitions) into a special section, and then numbering them in sequence. The references will then also be numbers. d Delete the footnote at point, and all definitions of and references to it.
Table 38: Calender:
Key binding function
C-c . Show calender
S-up/dn/l/r Move one day up/dn/r/l in calender view
> / < Move one month
10 Sets the day to 10th of default month
Tue Sets the day to Tuesday fo default week
+1d +1w +1y Add a day, a week or a year to date.
Table 39: Tables: (replaces all spreadsheat programs)
Key binding function
RET Realign and move to one row down
TAB Realign and move to one column right
S-TAB Realign and move to one column left
C-c C-c Realign table (don’t move cursor)
M-up/down Move row
M-right/left Move column
M-S-left Kill current column
M-S-right Insert column (to the left)
M-S-up Kill current row
M-S-down Insert row (above current)
C-| Convert region into table.
C-- insert hline below current position
C-RET insert hline below current position, and move to it
C-c ? Show coordinate/ref for current cell
C-c } Show position/coordinates in table (eg. “A12”)
C-c C-c (Re)Apply formula. (if on a [Formula] or TBLFM field)
C-u C-c = Insert field formula in cell
C-c = Insert field formula in column
C-c + Sum numbers in column, show in echo area
C-c ` Edit current field (cell) in separate buffer

Some more functions of tables

  • C-c ^ org-table-sort-lines

    Sort the table lines in the region based on current column, and range of lines between the nearest horizontal separator lines, or the entire table. If point is before the first column, you will be prompted for the sorting column. If there is an active region, the mark specifies the first line and the sorting column, while point should be in the last line to be included into the sorting. The command prompts for the sorting type (alphabetically, numerically, or by time). When called with a prefix argument, alphabetic sorting will be case-sensitive.

  • M-x org-table-import

    Import table from (TAB or SPC) seperated file. Prefix arg specifies seperator.

  • M-x org-table-export

    Export table to TAB seperated file. Might want to specify TABLE_EXPORT_FILE and TABLE_EXPORT_FORMAT

25.2. General, keybindings, etc.

;;General------------------------------------
(require 'org-install)
;; The following lines are always needed.  Choose your own keys.
(add-to-list 'auto-mode-alist '("\\.org$" . org-mode))

;; capture link with C-c l (for later insertion into org-mode file using C-c l)
(define-key global-map "\C-cl" 'org-store-link)

;; start org-agenda with C-c a
(define-key global-map "\C-ca" 'org-agenda)

(define-key global-map "\C-cb" 'org-iswitchb)

;; Add time stamp when toggling a TODO to DONE state
(setq org-log-done t)

;; replace the "..." with below symbol for collapsed org-mode content
;;(setq org-ellipsis "…")
(setq org-ellipsis "⬎")

;;RET follows hyperlinks in org-mode:
(setq org-return-follows-link t)

;;Use abbrev-minor-mode with org-mode: (I have global abbrev mode now)
;;(add-hook 'org-mode-hook (lambda () (abbrev-mode 1)))

;;Can be set per file basis with: #+STARTUP: noalign (or align). Same
;;as doing C-c C-c in a table.
(setq org-startup-align-all-tables t)

;; I prefer all extions to be folded when opening a file
(setq org-startup-folded t)

;; By default, org-mode allows a single newline for formating
;; bold/italics, etc. Change default to 3 lies
;; https://fuco1.github.io/2018-12-23-Multiline-fontification-with-org-emphasis-alist.html
(setcar (nthcdr 4 org-emphasis-regexp-components) 3)
;;---------------------------------------------

25.3. Export to LaTeX

Here I have some tweaks for when exporting org-mode files to LaTeX:

  • When exporting org files with code-snippets in them to LaTeX, have the resulting LaTeX file use the LaTeX listings package for those code-blocks.
  • I also add my own export class for Org-mode to Latex, that doesn’t add as many redundant packages. use by putting this on top of the org-mode file:

    #+LATEX_CLASS: myclass
    #+LaTeX_CLASS_OPTIONS: [a4paper]
    

Also adding support for beamer.

;; Make markdown export is always available
(eval-after-load "org"
  '(require 'ox-md nil t))

;;Org-export to LaTeX--------------------------
(require 'ox-latex)
(unless (boundp 'org-latex-classes)
  (setq org-latex-classes nil))

(add-to-list 'org-latex-classes
             '("article"
               "\\documentclass[11pt,a4paper]{article}
 \\usepackage[utf8]{inputenc}
 \\usepackage[T1]{fontenc}
 \\usepackage[normalem]{ulem}
 \\usepackage{graphicx}
 \\usepackage{longtable}
 \\usepackage{amssymb}
 \\usepackage{listings}
 \\usepackage[colorlinks=true,urlcolor=SteelBlue4,linkcolor=Firebrick4]{hyperref}
 \\usepackage[hyperref,x11names]{xcolor}
                      [NO-DEFAULT-PACKAGES]
                      [NO-PACKAGES]"
               ("\\section{%s}" . "\\section*{%s}")
               ("\\subsection{%s}" . "\\subsection*{%s}")
               ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
               ("\\paragraph{%s}" . "\\paragraph*{%s}")
               ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
             '("beamer"
               "\\documentclass\[presentation\]\{beamer\}"
               ("\\section\{%s\}" . "\\section*\{%s\}")
               ("\\subsection\{%s\}" . "\\subsection*\{%s\}")
               ("\\subsubsection\{%s\}" . "\\subsubsection*\{%s\}")))
;;---------------------------------------------

25.4. Ispell in Org-mode

Fix orgmode in ispell mode. From: http://endlessparentheses.com/ispell-and-org-mode.html?source=rss

(defun endless/org-ispell ()
  "Configure `ispell-skip-region-alist' for `org-mode'."
  (make-local-variable 'ispell-skip-region-alist)
  (add-to-list 'ispell-skip-region-alist '(org-property-drawer-re))
  (add-to-list 'ispell-skip-region-alist '("~" "~"))
  (add-to-list 'ispell-skip-region-alist '("=" "="))
  (add-to-list 'ispell-skip-region-alist '("^#\\+BEGIN_SRC" . "^#\\+END_SRC")))
(add-hook 'org-mode-hook #'endless/org-ispell)

25.5. a useful template

From pragmaticemacs I found this little code snippet. Highlight text, then M-x org-begin-template, and select what you want.

(defun org-begin-template ()
  "Make a template at point."
  (interactive)
  (if (org-at-table-p)
      (call-interactively 'org-table-rotate-recalc-marks)
    (let* ((choices '(("s" . "SRC")
		      ("e" . "EXAMPLE")
		      ("q" . "QUOTE")
		      ("v" . "VERSE")
		      ("c" . "CENTER")
		      ("l" . "LaTeX")
		      ("h" . "HTML")
		      ("a" . "ASCII")))
	   (key
	    (key-description
	     (vector
	      (read-key
	       (concat (propertize "Template type: " 'face 'minibuffer-prompt)
		       (mapconcat (lambda (choice)
				    (concat (propertize (car choice) 'face 'font-lock-type-face)
					    ": "
					    (cdr choice)))
				  choices
				  ", ")))))))
      (let ((result (assoc key choices)))
	(when result
	  (let ((choice (cdr result)))
	    (cond
	     ((region-active-p)
	      (let ((start (region-beginning))
		    (end (region-end)))
		(goto-char end)
		(insert "#+END_" choice "\n")
		(goto-char start)
		(insert "#+BEGIN_" choice "\n")))
	     (t
	      (insert "#+BEGIN_" choice "\n")
	      (save-excursion (insert "#+END_" choice))))))))))

25.6. orgtbl-mode

orgtbl-mode allows you to use the power of org-mode tables in non-org-mode documents, where you would have the org-table as a comment in that mode’s language.

M-x orgtbl-insert-radio-table inserts all you need by querying use in mini-buffer.

;;For smart org-tables in LaTeX, emails, and other modes.
;;Use M-x orgtbl-insert-radio-table
(add-hook 'LaTeX-mode-hook 'turn-on-orgtbl)
(add-hook 'message-mode-hook 'turn-on-orgtbl)
(add-hook 'html-mode-hook 'turn-on-orgtbl)
\begin{tabular}{lrrr}
Month & \multicolumn{1}{c}{Days} & Nr.\ sold & per day\\
% BEGIN RECEIVE ORGTBL salesfigures
% END RECEIVE ORGTBL salesfigures
\end{tabular}
%
\begin{comment}
#+ORGTBL: SEND salesfigures orgtbl-to-latex :splice t :skip 2
| Month | Days | Nr sold | per day |
|-------+------+---------+---------|
| Jan   |   23 |      55 |     2.4 |
| Feb   |   21 |      16 |     0.8 |
| March |   22 |     278 |    12.6 |
#+TBLFM: $4=$3/$2;%.1f
% $ (optional) to make font lock happy if unbalanced in TBLFM.
\end{comment}
  • :splice nil/t

    When set to t, return only table body lines, don’t wrap them into a tabular environment. Default is nil.

  • :fmt fmt

    A format to be used to wrap each field, it should contain %s for the original field value. For example, to wrap each field value in dollars, you could use :fmt “\(%s\)”.

25.7. org-babel

Set up which languages should be executable through org-babel-mode. Ditaa is a nice way to convert ascii-art-styled figures into typeset png files, excellent for including in an org file for html or LaTeX export.

And here is a short introduction to code blocks and their functionality, and the ob-async package for asynchronous execution of code blocks; and also studies specifically for python.

Also, the manual should prove a good resource.

Also, here are interesting org-babel examples in many programming languages: https://github.com/dfeich/org-babel-examples

;;Org-Babel -----------------------------------
(add-to-list 'org-src-lang-modes '("dot" . "graphviz-dot"))

;;Requires org-mode 7.x or later:
(eval-after-load "org"
  '(org-babel-do-load-languages
    'org-babel-load-languages
    '(;;(sh . t) ;; not find ob-sh package, apparently?
      (emacs-lisp . t)
      (ditaa . t)
      (dot . t)
      (python . t)
      (ipython . t) ;; requires ob-ipython mode from MELPA
      (gnuplot . t) ;; requires gnuplot-mode installed from ELPA
      )))

;; specify path to ditaa
;;(setq org-ditaa-jar-path "~/ditaa0_9/ditaa0_9.jar")
(setq org-ditaa-jar-path "/usr/bin/ditaa")

;; have fontlock src blocks and tab in code blocks work according to
;; their major-mode, even when I'm outsied them
(setq org-src-fontify-natively t)
(setq org-src-tab-acts-natively t)

;; no extra indentation for contents in src code blocks
(setq org-edit-src-content-indentation 0)

;; don't ask for confirmation when running code block
(setq org-confirm-babel-evaluate nil)

;; Fix an incompatibility between the ob-async and ob-ipython packages
(setq ob-async-no-async-languages-alist '("ipython"))

;; display/update images in the buffer after I evaluate
(add-hook 'org-babel-after-execute-hook 'org-display-inline-images 'append)

;; saving, C-x C-s, in a source block buffer, exits the buffer
;; (this is the natural way one expects it to behave)
(eval-after-load 'org-src
  '(define-key org-src-mode-map
     (kbd "C-x C-s") #'org-edit-src-exit))
;;---------------------------------------------

25.8. TODO org-calendar

  • Localize to where I am, (for me I install calendar-norway)
  • For advanced calendar / org-agenda integration with icalendar, synchronization with google calendar etc. and many advanced features, check out emacs-calfw.
;;Calendar starts with Monday
(setq calendar-week-start-day 1)

;; Localises date format, weekdays, months, lunar/solar names:
(require 'calendar-norway nil 'noerror)
;; Set what holidays you want in your calendar:
(setq calendar-holidays
   (append
    ;; Include days where you don't have to work:
    calendar-norway-raude-dagar
    ;; Include other days that people celebrate (julafton, lucia, etc.):
    ;; calendar-norway-andre-merkedagar
    ;; Include daylight savings time:
    calendar-norway-dst
    ;; And then you can add some non-Norwegian holidays etc. if you like:
    '((holiday-fixed 6 6 "Svenska flaggans dag")
      (solar-equinoxes-solstices))))

25.9. org-agenda

http://orgmode.org/manual/Agenda-Views.html http://members.optusnet.com.au/~charles57/GTD/org_dates/ http://www.gnu.org/software/emacs/manual/html_node/org/Agenda-commands.html

key  
C-c a t list of TODO items (t marks as DONE), prefix with C-u [N-days]
C-c a a agenda of scheduled items (l log-mode on/off)
   
n / p next / previous line
f / b move agenda forward / backwards in time
j jump to date
. today
L recenter on item in other buffer
TAB also move to other buffer
F Follow mode on/off: Like “L” for every n & p
v d/w/m/y view day / week / month / year
C-x C-s save all org-buffers files
;; Setting org-agenda-start-on-weekday to nil means that the agenda
;; view start on current day

(custom-set-variables
 '(org-agenda-ndays 7)                  ; show 7 day week
 '(org-agenda-start-on-weekday nil)     ; don't show past days
 '(org-agenda-show-all-dates t))        ; also show empty/free dates

;; Do C-c C-c on any item to add tags
(setq org-tag-alist '((:startgroup . nil)  ;; start mutualy exclusive list
                      ("@HEMMA" . ?h)
                      (:endgroup . nil)    ;; end mutually exclusive
                      ("VIKTIGT" . ?v)
                      ("DATOR" . ?d)))

Snippets from http://www.brool.com/post/using-org-mode-with-gtd/

;;C-c a t compiles list of all open TODO items.

(setq org-agenda-files
      (list "gtd.org"                   ; getting things done
            "agenda.org"                ; to be chopped up
            "home.org"                  ; concentrate on home related stuff /  not-work
            "work.org"                  ; concentrate on work
            "födelsedagar.org"          ; people like it when remembering their birthday
            "tickler.org"               ; schedule and forget
            "köp-sälj.org"              ; stuff to be bough/sold
            ;; "~/.emacs.d/org"            ; all in this folder
            ))
;; at the moment, 14 days pre-warning is too "cluttery"
;; (note: can be set individually for each deadline as well)
(setq org-deadline-warning-days 4)

;; highlight the line I'm on
(add-hook 'org-agenda-finalize-hook (lambda () (hl-line-mode)))

 ;; do C-c C-t on a headline to set propper todo keyword
(setq org-todo-keywords '((sequence "TODO(t)" "WAITING(w)" "|" "DONE(d)" "CANCELLED(c)")))


(defun gtd ()
  "Open my get stuff done file"
  (interactive)
  (find-file "~/.emacs.d/org/gtd.org"))

 ;; not sure what this does [2020-05-23 Sat] http://www.brool.com/post/using-org-mode-with-gtd/
(setq org-agenda-custom-commands
      '(("w" todo "WAITING" nil)
        ("n" todo "NEXT" nil)
        ("d" "Agenda + Next Actions" ((agenda) (todo "NEXT")))))

25.10. org-contacts

For managing contacts (phone, email, birthdays, etc.) Note: you must run 64 bit emacs for dates prior to 1970, or else it will fail.

Also, I find this will replace the email address auto-complete in message mode that notmuch (email client) provides, so I’m disabling it since the move to notmuch. Birth days and contacts can be managed using BBDB, or org agenda.

;;org-contacts --------------------------------
(eval-after-load "org"
  '(progn
     (require 'org-contacts)
     (setq org-contacts-files '("~/dokument/kontakter.org"))))
;;---------------------------------------------

25.11. org-capture

The following customization sets a default target1 file for notes, and defines a global key2 for capturing new stuff.

C-c c
Start a capture process. You will be placed into a narrowed indirect buffer to edit the item.
C-c C-c
Once you are done entering information into the capture buffer, C-c C-c will return you to the window configuration before the capture process, so that you can resume your work without further distraction.
C-c C-w
Finalize by moving the entry to a refile location (see Refiling notes).
C-c C-k
Abort the capture process and return to the previous state.

In the configuration below I specify which files to store what in when commiting a note (C-c C-c). See Manual: Template-expansion for syntax and here for an example.

Here is story of a person describing how his usage of capture has evolved over time. Ends with capture creating a separate file for each day.

(setq org-default-notes-file "~/.emacs.d/org/notes.org")
(define-key global-map (kbd "\C-c c") 'org-capture)

;; set up different templates
(setq org-capture-templates
      '(;(<key> <description> entry (file+headline <path> <headline> <template-string>))
        ("s" "schemalägg" entry (file+headline "~/.emacs.d/org/agenda.org" "Schema")
         "** %^{description} \n   SCHEDULED: %^t %?\n" :empty-lines 1)
        ("a" "agenda" entry (file+headline "~/.emacs.d/org/agenda.org" "Händelser")
         "** %^{description} %u %?\n" :empty-lines 1)
        ("t" "todo/Att göra" entry (file "~/.emacs.d/org/todo.org")
         "* TODO %^{Description} %^g %i\n %?" :empty-lines 1)
        ("K" "att köpa" entry (file+headline "~/.emacs.d/org/köp-sälj.org" "ATT KÖPA")
         "** TODO %^{description} \n Skapad: %u\n %?" :empty-lines 1)
        ("S" "att sälja" entry (file+headline "~/.emacs.d/org/köp-sälj.org" "ATT SÄLJA")
         "** TODO %^{description} \n Skapad: %u\n %?" :empty-lines 1)
        ("d" "diary" entry (file+datetree "~/.emacs.d/org/diary.org")
         "* %^{description}  %^g \n %? \n Skapad: %U" :empty-lines 1)
        ))

25.12. org-crypt

Any text under a section tagged with :crypt: will be encrypted when saved.

Preventing tag inheritance stops you having encrypted text inside encrypted text.

To decrypt text at point: M-x org-decrypt-entry

;;org-crypt -----------------------------------
(require 'org-crypt)
(org-crypt-use-before-save-magic)
(setq org-tags-exclude-from-inheritance (quote ("crypt")))
;; GPG key to use for encryption
;; Either the Key ID or set to nil to use symmetric encryption.
(setq org-crypt-key nil)
;;---------------------------------------------

26. POV-RAY MODE   mode

Pov-ray is a ray tracer renderer written in C++ using only text files. Following is a quick review of useful keys.

Table 40: Povray mode keys
Key Description
C-c C-c c r render, default quality
C-c C-c c 1 render, test quality
C-c C-c c 5 render, highest quality
C-c C-c c v view, internal viewer
C-c C-c c e view, external viewer
C-c C-c C-h look up word under cursor
C-c C-c c i open include file under cursor

TODO: C-c C-c v + “y”.

;;============================================
;;             POV-RAY-MODE
;;============================================
;; https://gitorious.org/pov-mode/pov-mode/trees/master

(autoload 'pov-mode "pov-mode" "PoVray scene file mode" t)
(add-to-list 'auto-mode-alist '("\\.pov\\'" . pov-mode))
(add-to-list 'auto-mode-alist '("\\.inc\\'" . pov-mode))

;; TODO
;;(set pov-documentation-directory "")
;;(set pov-include-dir "")

(defun set-my-pov-mode-hotkeys  ()
  "Sets some convenient keyboard shortcuts for pov-mode."
  (interactive)
  (define-key pov-mode-map (kbd "<f9>") 'pov-menu-render-test))

(add-hook 'pov-mode-hook 'set-my-pov-mode-hotkeys)

;;============================================

27. PROGRAMMING MODE   mode

New major mode in Emacs 24 loaded for all programming modes. Thus stuff that is common for C++, lisp, python, etc. can be specified here.

What about LaTeX? Nope, not a prog-mode derivative.

Here is a guide on how to use emacs for code development, starting with basic introduction to emacs, keys, modes, and useful packages.

Some sublime like code navigation (minimap) and code folding (origami) is demonstrated in this post.

27.1. Smartparen

Be smart about parenthesis. Also read this blog post.

Basic functionality:

  • Insert parenthesis in pairs.
  • Mark region + ( surrounds it with parenthesis.
  • C-M-Spc is good for marking region
  • C-M-k only kill to matching parenthesis
;; load default config
(require 'smartparens-config)

;; use it in all programming modes:
(add-hook 'prog-mode-hook #'smartparens-mode)
(add-hook 'markdown-mode-hook 'smartparens-mode)

27.2. auto-check code syntax

Flycheck is an improved version of the built in flymake-mode. M-x flycheck-info. It relies on extrnal tools, like gcc or cang for C/C++ or pylint for python. (For having the error description in a pop-up window instead of echoed in the mini-buffer, install flycheck-pos-tip.)

After install: M-x flycheck-verify-setup (C-c ! v) to see which linters it’s using in current mode.

  • C-c ! n/p for next/previous error, stand with marker for a while for notification, or mouse-over, for info on error.
Table 41: Key-commands, also available through menu: Tools->Syntax-checking
Key  
C-c ! v show settings of detected syntax checkers
C-c ! n/p next/previous error
C-c ! l list errors
C-c ! c flycheck-buffer
C-c ! C clear errors
C-c ! s select syntax checker
C-c ! f enable on the fly checker
;;Check syntax while typing code:
(add-hook 'prog-mode-hook #'flycheck-mode)

27.3. TODO auto-complete code

There are two major systems: auto-complete and company. The latter is more maintained, more actively developed, has a better API for developers to hook into it, and considered more “intelligent” as it will only show auto completion for functions and variables, not just any word previously typed. The former has more supported languages (but that is changing fast), and shows doc-strings by default, but is more difficult to setup, and doesn’t work so well.

To get company to use ispell list for auto completion in text mode see this

Another interesting addition to company is documentation, the same way auto-complete did it. This is added by company-quickhelp.

See third party packages for stuff for company mode to use.

I installed company-auxtex (for LaTeX), company-c-headers (for auto-completion of header #include<> statement), company-jedi for python (see Python-mode).

M-x company-mode - start mode M-x company-complete - start completion manually M-x customize-variable RET company-backends

Table 42: After having typed a few letters a list will show up
Keys Description
M-n / M-p move in completion list
TAB to complete common part
C-h (and F1?) show doc-string (in separate buffer)
C-r/s/o search completions
C-w shows source, if supported by the backend.
;;Company mode--------------------------------
(add-hook 'after-init-hook 'global-company-mode)
(eval-after-load "company" '(diminish 'company-mode "comp"))

(with-eval-after-load 'company
  (company-auctex-init)
  (add-hook 'python-mode 'run-python)

  (setq company-idle-delay 1)
  (setq company-minimum-prefix-length 3)

  ;;(add-to-list 'company-backends 'company-c-headers)
  (define-key company-active-map (kbd "M-n") nil)
  (define-key company-active-map (kbd "M-p") nil)
  (define-key company-active-map (kbd "C-n") #'company-select-next)
  (define-key company-active-map (kbd "C-p") #'company-select-previous))

  ;; also have documentation strings in the hint
  (company-quickhelp-mode)

27.4. Spell check comments and strings

;;Spell check---------------------------------
;;Spell check comments and strings
;;Change dictionary: "C-c e" = engelska, "C-c s"=svenska, "C-c w"=turn off flyspell
(add-hook 'prog-mode-hook
            '(lambda ()
               (local-set-key (kbd "C-c s 1")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "svenska")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 2")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "american")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 3")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "british-ize")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 4")
                               (lambda()(interactive)
                                 (ispell-change-dictionary "british-ise")
                                 (flyspell-mode 1)
                                 (flyspell-buffer)))
               (local-set-key (kbd "C-c s 0")
                               (lambda()(interactive)
                                 (flyspell-mode -1)))
               ))
;;---------------------------------------------

27.5. code-review-region

Copies code region, inserts file name, and line number, ready to be pasted into an email. Use: M-x code-review-region. src

(defun chomp (str)
  "Chomp leading and tailing whitespace from STR."
  (replace-regexp-in-string (rx (or (: bos (* (any " \t\n")))
                                    (: (* (any " \t\n")) eos)))
                            ""
                            str))

(defun code-review-region (beg end)
  (interactive "r")
  (let* ((text (chomp (buffer-substring-no-properties beg end)))
         (line-number (line-number-at-pos))
         (file (buffer-file-name))
         (path (replace-regexp-in-string "^.*branches/" ""
                                         (replace-regexp-in-string
                                          "^.*trunk/" "" file))))
     (with-temp-buffer
       (insert text)
       (goto-char (point-min))
       (while (re-search-forward "^" nil t)
         (replace-match "| " nil nil))
       (goto-char (point-min))
       (insert (format "+---[%s:%s]\n" path line-number))
       (goto-char (point-max))
       (insert "\n+---\n")
       (kill-region (point-min) (point-max)))))


27.6. Highlight (too) long lines, and key-words

;;Fontify -------------------------------------
;;Highlight columns longer than 79 lines
(when (> (display-color-cells) 16)         ;if not in CLI
  (add-hook 'prog-mode-hook
            (lambda ()
              (font-lock-add-keywords nil '(("^[^\n]\\{79\\}\\(.*\\)$" 1 font-lock-warning-face t)))
              (font-lock-add-keywords nil '(("\\<\\(FIXA\\|TEST\\|TODO\\|FIXME\\|BUG\\|NOTE\\)"
                                             1 font-lock-warning-face prepend)))
              (font-lock-add-keywords nil '(("\\<\\(__FUNCTION__\\|__PRETTY_FUNCTION__\\|__LINE__\\)"
                                             1 font-lock-preprocessor-face prepend)))
           )))
;;--------------------------------------------

27.7. Auto Kill compile buffer if no errors

This function is global, and not associated with prog-mode at all. Very handy. Kill the compilation buffer if it was successful.

TODO: Working on some kind of matching for a no-error, but warnings in compile. Then I want to keep the buffer, in the background.

;;Kill-compile-buffer-if-success-------------
;;If compilation was successful, kill it.
;;Also works for LaTeX. TODO: keep in background if there are warnings.

;; Note: the M-x grep command will print its result as a Compilation
;; buffer (named *grep*), but we do not want to kill that one.

(defvar current-frame) ;;to avoid Elisp-compiler warning. temp fix.

(defun notify-compilation-result(buffer msg)
  "Close *compilation* buffer if successful, set the focus back
to Emacs frame. Note: *grep* is a compilation buffer, but we want
to keep that if it's successful."
  (if (string= (buffer-name) "*compilation*") ;don't match *grep* buff
      (cond ((string-match "^finished" msg)   ;kill buffer
             ;;(tooltip-show "\n Compilation Successful :-) \n "))
             (kill-buffer-and-window))
            ((string-match "^warnings" msg) ;buffer to background
             ;;(tooltip-show "\n Compilation Warnings :-| \n")
             (delete-windows-on buffer)))
    ;;(tooltip-show "\n Compilation Failed :-( \n ")
    )

  (setq current-frame (car (car (cdr (current-frame-configuration)))))
  (select-frame-set-input-focus current-frame))

(add-to-list 'compilation-finish-functions
             'notify-compilation-result)
;;--------------------------------------------

27.8. compile

From http://endlessparentheses.com/better-compile-command.html

(defun my-compile-please ()
  "Compile without confirmation."
  (interactive)
  ;; Do the command without a prompt.
  (save-window-excursion
    (compile compile-command))
  ;; Create a compile window of the desired width.
  (pop-to-buffer (get-buffer "*compilation*"))
  (enlarge-window
   (- my-compile-window-size (window-width))
   'horizontal))

;; This gives a regular `compile-command' prompt.
(define-key prog-mode-map [C-f9] #'compile)
;; This just compiles immediately.
(define-key prog-mode-map [f9]
  #'my-compile-please)

;; Don't ask me to save _all_ buffers. If there's an error due to me
;; not having saved the file prior to compilation, I'll figure it out
;; on my own:
(setq compilation-ask-about-save nil)

;; Stop on the first error.
(setq compilation-scroll-output 'first-error)

;; Don't stop on info or warnings.
(setq compilation-skip-threshold 2)

28. PYTHON MODE   mode

Good soruce, but perhaps outdated (from 2010), also for doc-tests it might be worth reading this. Also, “Emacs: The Best Python Editor?” is a clear writ-up, focusing on using elpy, one can skip all the “Emacs n00b” parts in the beginning.

TODO: check out: http://ctags.sourceforge.net/

ctags-exuberant -e -R --languages=python --exclude="__init__.py"

At work we use the following python tools:

black
formats code, e.g. upon saving.
flake8
glues together pep8, pyflakes, mccabe
mypy
optional static type checker
isort
sort and separate imports into blocks automatically
nbstripout
Remove crap from noteooks, for checking into repositories

There are a few options:

  1. default emacs python-mode, that can be extended with:
    • jedi-company for auto-completion,
    • pyenv-mode for managing virtual environments
    • pylookup for documentation, uses a database
    • configure to use ipython terminal process. (note, to use with pyenv, ipython must be installed in the local virtual environment. Might need to restart shell/emacs for it to detect new ipython).
    • configure flymake for which tools to use for python
    • python-pylint, flake8(?), py-autopep8 (MELPA), blacken (MELPA) for autopep8 & black integration
    • isort (for imports?)
    • eldoc? to show call signatures in minibuffer (or is included in python-mode?)
    • pydoc?
  2. Elpy
  3. To use the language-server needs a lsp-mode, e.g. lsp-mode (and, if fancy, lsp-ui), or elgot, then a language server for python (tutorial-1 tutorial-2) server with some python server, e.g. lsp-python-ms or lsp-pyls, Will still need several emacs packages, like pyvenv, company-lsp, projectile or find-file-in-project Install in Emacs:

    • lsp-mode
    • company-lsp
    • projectile or find-file-in-project

    cons:

    • Somtimes one has to restart the server (M-x lsp-restart-workspace), and can be slow (according to comments from 2018).
    • “If you have an existing setup for a language environment, the LSP features end up layering over existing functionality, and that can have unexpected results.”

Perhaps something to play with:

28.1. DONE ipython and/or jupyter integration

In emacs 24.3 and above the default python interpreter when running M-x run-python can be changed to ipython.

For having powerful “notebook” integragion, i.e. blocks of code, that when evaluated shows blocks of results including graphics, like plots, tables, etc. there are two main options.

Install jupyter-console on Arch Linux, and:

  1. EIN (Emacs Ipython Notebook) is looks to be the most “fancy schmancy” one, but as I understand it, it tries to force jupyter notebook paradigm into emacs (with the “cell block concept”), when there’s already a better, more “emacsy”-option…
  2. …namely org-mode that has code blocks, and result-blocks, and a markup langauge of it’s own, that’s better than markdown. ob-ipython, integrates ipython with org-mode. the README also has a section: “Why not use EIN?”, worth reading.

Also-1: here are interesting code examples: https://github.com/dfeich/org-babel-examples

Also-2: Ipython covers som has some nice tricks, e.g. prefixing %time to a command will time it, or %timeit for benchmarking; fortran-modules, and parallelization.

;; use elpy as my Python IDE, on top of default python-mode
(advice-add 'python-mode :before 'elpy-enable)
(require 'python)

(cond ((executable-find "ipython")
       (setq python-shell-interpreter "ipython"
             python-shell-interpreter-args "-i --simple-prompt")
       ;; python-shell-interpreter-args "console --simple-prompt"
       ;; for some reason, my emacs doesn't interpret ansi term
       ;; characters correctly without this
       (setenv "IPY_TEST_SIMPLE_PROMPT" "1")
       (add-to-list 'python-shell-completion-native-disabled-interpreters "jupyter"))
      ;; ipython devs now consider --pylab a mistake
      ;;(setq python-shell-interpreter-args "--pylab")
      ((executable-find "jupyter")
       (setq python-shell-interpreter "jupyter"
             python-shell-interpreter-args "console --simple-prompt"
             python-shell-prompt-detect-failure-warning nil))
      (t
       (setq python-shell-interpreter "python"
             python-shell-interpreter-args "-i")))

28.2. Elpy

Elpy is a pretty complete Python environment for emacs. Install it through MELPA, and run M-x elpy-enable, or put in your config:

(elpy-enable)

or:

(advice-add 'python-mode :before 'elpy-enable)

read the documentation.

  • C-c C-c eval file or region
  • C-RET eval current statement (line/block/function)
  • C-c C-z jump to shell
  • C-c C-d documentation for thing under cursor (q to quit)
  • C-c C-e edit all instances of symbol at point
  • C-c k kill associated python shell
  • C-c K kill all python shells
  • syntax check
    • C-c C-v run check in separate buffer
    • C-c C-n/p next error in file (not working?)
    • how do I get my pylint checkmark in margin? python-check-command: To change which command is used for syntax checks, you can customize this option. By default, Elpy uses the flake8 program, which you have to install separately

Elpy provides commands to send the current Python statement (e), function definition (f), class definition (c), top- level statement (s), group of Python statements (g), cell (w), region (r), or buffer (b) to the Python shell for evaluation. These commands are bound to prefix C-c C-y

  • C-c C-r f elpy-format code
  • C-c C-f find file in current project.
  • C-c C-s Search the files in the current project for a string. By default, this uses the symbol at point.
  • M-x elpy-set-project-root change project root

    • want support for meaningful multi-occur, tramp, auto-detect (if git repo etc.),

    “This command uses, under the hood, either of the following packages that must be installed:

    • projectile, autodetect project path if, e.g. .git or empty .projectile file in folder. “Dev: I don’t use TRAMP myself, however, so I never paid that much attention to the TRAMP support. It’s mostly community-maintained.”
    • find-file-in-project">“Find file/directory quickly in current project. The project root is detected automatically if Git/Subversion/Mercurial is used, else set: (setq ffip-project-root ”~/projs/PROJECT_DIR“).”, “Works flawlessly with Tramp Mode”
  • M-up/down move current region
  • M-left/right indent current region
  • M-. Go to the location where the identifier at point is defined.
  • elpy-get-info-from-shell - use shell instead(?) of jedi
  • M-x pyvenv-workon must have set WORKON_HOME variable in local file, pointing to the folder containing the .python-version to use.
  • M-x pyvenv-activate
  • M-x pyvenv-deactivate

M-x elpy-config M-x elpy-profile-buffer-or-region

  • WORKON_HOME is from virtualenvwrapper, want to set this as a file-local variable, doesn’t make sense to set globally.

Code formatting:

  • install on arch linux?
    • autopep8
    • python-black
  • M-x elpy-config and install jedi and autopep8
    • note: elpy uses its own virtual env, by default separate for system, so need to install jedi through clicking “install” in elpy-config. See documentation on RPC (Remote Procedure Call) process.
  • install in Emacs:
    • py-autopep8 connects autopep8 to Emacs.
    • blacken enables black to run from within Emacs.

elpy-rpc–get-package-list is used to list packages I want RPC to install (in .emacs.d/elpy/rpc-env)

Table 43: Key bindings for elpy / python as a python IDE
Key Action
C-c C-c eval region/buffer to python shell
C-RET eval current line + nested lines
C-c C-z switch between file and shell
C-c C-d show documentation under point
   
C-arrow Move by indentation
M-arrow Move by current region
   
M-TAB Force completion suggestion at point
   
M-. navigate
   
C-c C-e edit all instances of symbol at point
   
C-c C-v elpy syntax check
C-c C-n next syntax error
C-c C-p previous syntax error
   
C-c @ C-c toggle code folding at point
C-c @ C-b toggle folding of all docstrings
C-c @ C-m toggle folding of all comments
C-c @ C-a unfold everything
   
C-c C-u d start python debugger
C-c C-u b add/remove break-point at line
C-c C-u p run debugger, pause at point
C-c C-u e run post-mortem pdp on last exception
   

default value: flake8 for syntax checking

python-check-command
(when (load "flycheck" t t)
  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))
  (add-hook 'elpy-mode-hook 'flycheck-mode))

28.3. lsp-mode

mutually exclusive with Elpy.

pipenv install python-language-server[all]

(“all” = various code formating stuff)

28.4. TODO elpy

page 16 of manual: When package eval-sexp-fu is loaded and eval-sexp-fu-flash-mode is active, the statements sent to the shell are briefly flashed after running an evaluation command, thereby providing visual feedback.

read up on code folding. p 18. Claims it’s indicated in buffer margin?

  • elpy-folding-fringe-indicators t
  • I needed to manually activate hs-minor-mode

read up on debugging, page 18, and testing p 19 and refactoring

elpy-formatter (Customize Option) Allows the selection of one’s preferred formatter. Available options are: yapf , autopep8 and black. yapf and autopep8 can be configured with style files placed in the project root directory (determined by elpy-project-root). black can be configured in the pyproject.toml file of your project.

elpy-profile-buffer-or-region seems to use system python and not selected virtual env? or all packages in file that is to be profiled need to be installed in the elpy’s RPC?

28.5. Auto completion

For auto completion in python I use company-mode with jedi, see programming-mode for more.

;; Also work well for python:
(defun my/python-mode-hook ()
  (add-to-list 'company-backends 'company-jedi))
(add-hook 'python-mode-hook 'my/python-mode-hook)

;; un-comment if above doesn't give me full auto-completion in python:
(add-hook 'python-mode-hook 'jedi:setup)

28.6. pylint

Pylint is both good (catch bugs in code!) and bad (too verbose!), but luckily the last issue can be solved, by turning off the features, in the configuration file, see this post.

(Install pylint in MELPA, and use flycheck to wrapp it).

(setq flycheck-flake8rc “/path/to/your/flake8-config-file”) (add-hook ’python-mode-hook ’flycheck-mode)

To print out the default configuration:

pylint --generate-rcfile >.pylintrc

Some to add:

max-line-length=120
disable= C0326, W0621, C0111, C0103, W0702, W0703, C0321, W0511, W0102, R0913, R0914, R0915, R0912, R0902, R0903, C0303, C0302, C0325, W0401

Check the code with pylint (requires pylint to be installed). Use M-x pylint in buffer. source

;(setq flycheck-flake8rc "/path/to/your/flake8-config-file")
(add-hook 'python-mode-hook 'flycheck-mode)

One can also add pylint emacs integration, which gives pylint as a compilation buffer. I think flycheck + “native” pylint is enough for now, so not using it.

;; add M-x pylint compilation of a buffer
(autoload 'python-pylint "python-pylint" nil t)
(autoload 'pylint "python-pylint" nil t)

28.7. Misc

Make RET indent to same level as previous line.

(add-hook 'python-mode-hook
          '(lambda ()
             (define-key python-mode-map "\C-m" 'newline-and-indent)))

28.8. python lookup

pylookup.el

;; load pylookup when compile time
;;(eval-when-compile (require 'pylookup))

;; set search option if you want
;; (setq pylookup-search-options '("--insensitive" "0" "--desc" "0"))

;; to speedup, just load it on demand
(autoload 'pylookup-lookup "pylookup"
  "Lookup SEARCH-TERM in the Python HTML indexes." t)
(autoload 'pylookup-update "pylookup"
  "Run pylookup-update and create the database at `pylookup-db-file'." t)

;; set executable file and db file
(setq pylookup-program "~/.emacs.d/pylookup.py")
(setq pylookup-db-file "~/.emacs.d/pylookup.db")

(add-hook
 'python-mode-hook
 '(lambda ()
    (local-set-key (kbd "C-c h") 'pylookup-lookup)))

28.9. lambda font

Replace the word “lambda” in python code with the greek letter in the font-lock. I.e. the text isn’t changed just the display of it.

(require 'lambda-mode)
(add-hook 'python-mode-hook #'lambda-mode 1)
;;change default symbol for lambda:
(setq lambda-symbol (string (make-char 'greek-iso8859-7 107)))

28.10. TODO Clever docstrings / yasnippets

Dock strings be can adhere to either (for being compliant with sphinx doc generator):

28.11. TODO EIN - Emacs Ipython Notebook

  • TODO: no auto-compleation? Maybe because I have jedi disabled, before I started EIN?

There are many ways to stara a notbook using EIN, use ONE of the following:

  1. M-x ein:login to a running jupyter server, or,
  2. Open an .ipynb file, press C-c C-o, or,
  3. M-x ein:run launches a jupyter process from emacs, or,
  4. [Jupyterhub] M-x ein:login to any of https://hub.data8x.berkeley.edu https://hub.data8x.berkeley.edu/user/1dcdab3 https://hub.data8x.berkeley.edu/user/1dcdab3/?token=c421c68, or,
  5. [Preview] To run on AWS, open an .ipynb file, press C-c C-r. see doc.
  6. To start a new jupyter server from emacs:
    • M-x ein:jupyter-server-start and give folder with jupyter notebooks in. Select notebook / start new.
    • Run jupyter server in emacs C-c C-z
;; images open in external image viewer by default, to inline:
(setq ein:output-area-inlined-images t)
Table 44: Selection of keybindings I’m using
Key Binding
C-c Prefix Command
C-x Prefix Command
   
C-up/down go to next cell up/down
C-c C-n/p go to next cell up/down
   
M-S-return ein:worksheet-execute-cell-and-insert-below-km
M-down ein:worksheet-not-move-cell-down-km
M-up ein:worksheet-not-move-cell-up-km
   
C-x C-s ein:notebook-save-notebook-command-km
C-x C-w ein:notebook-rename-command-km
   
M-RET ein:worksheet-execute-cell-and-goto-next-km
M-, ein:pytools-jump-back-command
M-. ein:pytools-jump-to-source-command
   
C-c C-a insert cell above
C-c C-b insert cell below
C-c C-k kill cell
C-c C-c execute cell
C-u C-c C-c execute all cells
C-c C-l clear output
C-c C-S-l clear all output
C-c C-e toggle showing output
C-c up/down move cell up/down
   
C-c C-t toggle cell type e.g. markdown/code/raw
   
C-c RET merge cell with previous
C-c C-s split cell at point
   
C-c C-f ein:file-open-km
C-c C-o ein:notebook-open-km
   
C-c C-q ein:notebook-kill-kernel-then-close-command-km
C-c C-r ein:notebook-reconnect-session-command-km
C-c C-v ein:worksheet-set-output-visibility-all-km
C-c C-w ein:worksheet-copy-cell-km
C-c C-y ein:worksheet-yank-cell-km
C-c C-z ein:notebook-kernel-interrupt-command-km
C-c C-# ein:notebook-close-km
C-c C-$ ein:tb-show-km
C-c C-/ ein:notebook-scratchsheet-open-km
C-c C-; ein:shared-output-show-code-cell-at-point-km
   
C-c C-x C-r ein:notebook-restart-session-command-km
   
C-c M-w ein:worksheet-copy-cell-km

29. R MODE   mode

Use the ess project, install from MELPA. Manual.

Key Command
M-x R start
C-c l load file
C-c c eval func/para/step
C-x C-n eval line
;; ;; From http://stats.blogoverflow.com/2011/08/using-emacs-to-work-with-r/
;; (add-hook 'inferior-ess-mode-hook
;;     '(lambda nil
;;           (define-key inferior-ess-mode-map [\C-up]
;;               'comint-previous-matching-input-from-input)
;;           (define-key inferior-ess-mode-map [\C-down]
;;               'comint-next-matching-input-from-input)
;;           (define-key inferior-ess-mode-map [\C-x \t]
;;               'comint-dynamic-complete-filename)))

;; ESS will not print the evaluated commands, also speeds up the
;; evaluation
(setq ess-eval-visibly nil)

;if you don't want to be prompted each time you start an interactive R
;session
(setq ess-ask-for-ess-directory nil)

30. SCALA MODE   mode

Since Scala syntax isn’t lisp, a Scala cheat sheet can come in handy.

Use Ensime (install through Melpa), which incorporates scala-mode2 which is a continuation of older scala-mode.

ENSIME consists of both SBT-mode and scala-mode, that can be used independently.

For using Ensime, one needs to compile the project with SBT, and create a .ensime-file in the root folder of the project.

(require 'ensime)
(add-hook 'scala-mode-hook 'ensime-scala-mode-hook)

;; if not using MELPA-stable version, don't warn us every time:
(setq ensime-startup-snapshot-notification nil)

30.1. To generate a .ensime file

https://ensime.github.io/build_tools/sbt/

Server-side of ensime needs a .ensime file.

Note: SBT needs jdk8-openjdk for this, which isn’t an explicit dependency for sbt (on Arch Linux), i.e. not just java-rutime-headless and openjdk8-src. This due to ensime using stuff from tools.jar, or something else that needs compiling to java.

In: ~/.sbt/0.13/plugins/plugins.sbt put (use latest version number):

addSbtPlugin("org.ensime" % "sbt-ensime" % "1.12.3")

Generate .ensime file in project’s root folder:

sbt ensimeConfig

then start ensime in Emacs with M-x ensime

http://www.47deg.com/blog/scala-development-with-emacs

30.2. Keys

“You must type C-c C-c a before using “Refactor/Rename” (C-c C-r r) and “Source/Find all references” (C-c C-v r). At the moment, these two commands will give incomplete results unless all source files are parsed.”

Table 45: Ensime key commands
Key Function
C-c C-v i over symbol opens “type inspector”
C-c C-r r rename symbol under point, everywhere
C-c C-v s launch SBT console
M-. Navigate
M-* Navigate
C-c C-v C-c C-c send C-c to SBT
C-c C-b s launch SBT child process on buffer
C-c C-b c to compile
C-c C-b r to run
C-c C-b n to issue a clean
C-c C-b p to do a package
C-c C-b t invoke testQuick
C-c C-b T run all tests

31. TEXT MODE   mode

31.1. Suggestion for mode

olivetti mode seems like a very nice mode to give you a clean window, without distractions when spending long time writing, e.g. a novel. I’ve never used it myself, though.

31.2. Line breaks / long lines

Linebreaks in emacs can either be:

Soft

Use visual-lines-mode, to behave just like a word processor: Long lines are wrapped arond automatically at the edge of the current emacs window frame, and line is readjusted, but these “virtual” line breaks are not saved to file, nor do they mess up the line number counter.

(Starting from Emacs 23 line-move-visual is t by default, which makes movement of point (C-a, C-e, etc.) by visual lines displayed on screen rather than logical/real buffer lines, as it should be).

Hard

Use auto-fill-mode, to insert RET (a hard/real line break) after fill-column (C-x f) value is passed. Evaluated when SPC is pressed. One can always re-process the current paragraph with M-q.

To undo the hard line breaks: C-x f 99999 RET, M-q.

(defvar soft-line-breaks-p nil   ; nil or t
  "Use hard or soft line breaks for long lines")

;; M-q doesn't insert double space after period.
(setq sentence-end-double-space nil)

(if soft-line-breaks-p
    (add-hook 'text-mode-hook 'turn-on-visual-line-mode)
  (add-hook 'text-mode-hook
            '(lambda ()
               (set-fill-column 78)       ; lines are 78 chars long ...
               (auto-fill-mode t))))      ; ...and wrapped around automagically

31.3. Spell check

Several different programs for spellchecking can be used in emacs. Default is ispell, however, aspell is the GNU spell checker (better than ispell, gives more suggestions etc.), and myspell is by they same author who did apsell and pspell. Then there’s hunspell which is a (backwards compatible) far better derivative of myspell, now in use by libre/open office, and Mozilla. Unfortunately I have not managed to get hunspell up and running. Yet.

Run M-x ispell-change-dictionary RET SPC to see which are available.

Note 1: some aspell dictionaries are in the Arch linux User Repository only, e.g. Norwegian.

Note 2: I use the british-ize dictionary, this might be interesting to read on the use of z vs. s in English language.

;;Spell check---------------------------
;;Swedish spell check in all i text files (including LaTeX-files).
;;These settings will not affect programming.

(add-hook 'text-mode-hook '(lambda () (flyspell-mode nil)))
;;(add-hook 'text-mode-hook '(lambda () (ispell-change-dictionary "svenska" nil)))

;;don't print words in mini-buffer when scanning, so sloooow
(setq flyspell-issue-message-flag' nil)

;;auto configure language (does not work? Says "??" in mod-line)
;;(require 'auto-dictionary)
;;(add-hook 'flyspell-mode-hook '(lambda () (auto-dictionary-mode 1)))

;;ispell=unix native spell checker, aspell=GNU's ispell, hunspell=OpenOffice & firefox
(setq ispell-program-name "aspell"
  ispell-extra-args '("--sug-mode=normal"))

;;change dictionary: "C-c e" = engelska, "C-c s"=svenska, "C-c w"=turn off flyspell
(add-hook 'text-mode-hook
          '(lambda ()
             (local-set-key (kbd "C-c s 1")
                            (lambda()(interactive)
                              (ispell-change-dictionary "svenska")
                              (flyspell-mode 1)
                              (flyspell-buffer)))
             (local-set-key (kbd "C-c s 2")
                            (lambda()(interactive)
                              (ispell-change-dictionary "american")
                              (flyspell-mode 1)
                              (flyspell-buffer)))
             (local-set-key (kbd "C-c s 3")
                            (lambda()(interactive)
                              (ispell-change-dictionary "british-ize")
                              (flyspell-mode 1)
                              (flyspell-buffer)))
             (local-set-key (kbd "C-c s 4")
                            (lambda()(interactive)
                              (ispell-change-dictionary "british-ise")
                              (flyspell-mode 1)
                              (flyspell-buffer)))
             (local-set-key (kbd "C-c s 6")
                            (lambda()(interactive)
                              (ispell-change-dictionary "bokmal")
                              (flyspell-mode 1)
                              (flyspell-buffer)))
             (local-set-key (kbd "C-c s 7")
                            (lambda()(interactive)
                              (ispell-change-dictionary "nynorsk")
                              (flyspell-mode 1)
                              (flyspell-buffer)))

             (local-set-key (kbd "C-c s 0")
                            (lambda()(interactive)
                              (flyspell-mode -1)))
             ))
;;--------------------------------------------

32. TIME

32.1. Time zones

List which places are of interest when calling this function: M-x display-time-world

(setq display-time-world-list
      '(("Australia/Sydney" "Sydney")
        ("Asia/Tokyo" "Tokyo")
        ("Asia/Singapore" "Singapore")
        ("Europe/Copenhagen" "Copenhagen")
        ("Europe/London" "London")
        ("America/New_York" "New York")
        ("America/Los_Angeles" "Los Angeles")))

33. UNISON MODE   mode

Something I hacked up myself. I keep it here, but I think someone put it into MELPA/Marmelade? I don’t maintain it much.

I made it mostly to learn how to do an emacs mode. Note to self: If in future endeavors I want to add a compilation buffer to my mode, check out this post.

2017-update: this and this post seems useful to learn how to write major modes, and this (2018). Large write up here (2019).

(autoload 'unison-mode "unison-mode" "my unison mode" t)
(setq auto-mode-alist (append '(("\\.prf$" . unison-mode)) auto-mode-alist))

34. FUNCTIONS

Functions that are handy to have. Invoke by M-x.

34.1. Remove ^M from files

;;Remove ^M------------------------------------
;; Call with M-x strip[TAB]
(defun strip-^m ()
  (interactive)
  (goto-char (point-min))
  (while (search-forward "\r" nil nil)
    (replace-match "")))
;;(define-key esc-map "o" 'strip-^m)
;;--------------------------------------------

34.2. build tables

From emacsnotes, on interactive delim-col.

“delim-col creates pretty tables from a text region and helps convert those tables in to different table formats like TSV1, CSV1, Org1, LaTeX1, GFM1, 2 or any other makeshift format that you may come up with.”

(defun my-delimits-column-region (orig-fun &rest args)
  (let
      ((delimit-columns-separator
        (read-regexp
         (format "%s (%s): " "Specify the regexp which separates each column" delimit-columns-separator)
         (list delimit-columns-separator)))
       (delimit-columns-before
        (read-string
         (format "%s (%s): " "Specify a string to be inserted before each column" delimit-columns-before)
         nil nil delimit-columns-before))
       (delimit-columns-after
        (read-string
         (format "%s (%s): " "Specify a string to be inserted after each column" delimit-columns-after)
         nil nil delimit-columns-after))
       (delimit-columns-str-separator
        (read-string
         (format "%s (%s): " "Specify a string to be inserted between each column" delimit-columns-str-separator)
         nil nil delimit-columns-str-separator))
       (delimit-columns-str-before
        (read-string
         (format "%s (%s): " "Specify a string to be inserted before the first column" delimit-columns-str-before)
         nil nil delimit-columns-str-before))
       (delimit-columns-str-after
        (read-string
         (format "%s (%s): " "Specify a string to be inserted after the last column" delimit-columns-str-after)
         nil nil delimit-columns-str-after))
       (delimit-columns-format
        (let*
            ((choices
              '(("Align Columns" . t)
                ("No Formatting")
                ("Align Separators" . separator)
                ("Pad Columns" . padding)))
             (default-choice
               (car
                (rassoc delimit-columns-format choices)))
             (choice
              (completing-read
               (format "%s (%s): " "Specify how to format columns" default-choice)
               choices nil t nil nil default-choice)))
          (message "%s" choice)
          (assoc-default choice choices))))
    (apply orig-fun args)))

(advice-add 'delimit-columns-region :around #'my-delimits-column-region)
(advice-add 'delimit-columns-rectangle :around #'my-delimits-column-region)

34.3. Search across buffers

Search for word across all open buffers. Note: ibuffer can do this as well.

;;Search all open buffers---------------------
(defun search (regexp)
  "Search all buffers for a regexp."
  (interactive "sRegexp to search for: ")
  (multi-occur-in-matching-buffers ".*" regexp))
;;--------------------------------------------

34.4. Nuke all buffers

;;nuke-all-buffers-----------------------------
(defun nuke-all-buffers ()
"Kill all buffers, leaving *scratch* only."
(interactive)
(mapc (lambda (x) (kill-buffer x)) (buffer-list)) (delete-other-windows))
;;---------------------------------------------

34.5. Kill all other buffers

;;Kill all other buffers----------------------
;;kills all buffers, except the current one.
    (defun kill-all-other-buffers ()
      "Kill all other buffers."
      (interactive)
      (mapc 'kill-buffer (delq (current-buffer) (buffer-list))))
;;--------------------------------------------

34.6. Artistic mode

For ASCII-art

;;Artistic mode ASCII-art---------------------
;; toggle artiste-mode
(defun artist-mode-toggle ()
  "Toggle artist-mode"
  (interactive)
  (if (eq major-mode 'artist-mode)
      (artist-mode-off)
    (artist-mode)))
;;(global-set-key (kbd "C-c d") 'artist-mode-toggle)
;;--------------------------------------------

34.7. youtube-dl url under point

From https://ambrevar.xyz/emacs2/,

(defun my/youtube-dl-at-point (&optional url)
  "Run 'youtube-dl' over the URL at point.
If URL is non-nil, use that instead."
  (interactive)
  (setq url (or url (thing-at-point-url-at-point)))
  (let ((eshell-buffer-name "*youtube-dl*"))
    (eshell)
    (when (eshell-interactive-process)
      (eshell t))
    (eshell-interrupt-process)
    (insert "youtube-dl " url)
    (eshell-send-input)))

35. JSON

Nice hack, if one doesn’t want to install js2-mode, to pretty print json, from irreal blog, parse region into python to pretty print: C-u M-| python -m json.tool

Or put it in a function:

(defun json-format ()
  (interactive)
  (save-excursion
    (shell-command-on-region (mark) (point) "python -m json.tool" (buffer-name) t)))

third alternative, if one doesn’t want to rely on python nor js2-mode, is to install and use json-reformat mode.

36. OBSOLETE / UNUSED

Here I put fun/interesting/useful things that are no longer needed by me, but could be of interest to others or my future self.

36.1. recent buffers

Recent file is in Emacs since v.21. The code below binds it to C-x C-r which is otherwise bound to find-file-read-only which I’ve never found useful anyways. There are tons of ways to use icicles, ido, or iswitch with recentf, or filter files based on directory, or time etc.

I find TAB or corresponding numbers easiest to use in the recentf-open-files buffer.

;;Recent files --------------------------------
;; List of recent opened files
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
;;---------------------------------------------

36.2. turn on line numbers when goto-line is called

This could be fun. I never use linum-mode (shows line numbers in the margin, available since (> emacs-major-version 22)) but this code turns it on only temporarily while you goto-line: M-g g or M-g M-g.

(code from emacs-rocks)

;;Goto line with linum-mode--------------------
;; only active when M-g M-g or M-g g
(defun goto-line-with-feedback ()
  "Show line numbers temporarily, while prompting for the line number input"
  (interactive)
  (if (and (boundp 'linum-mode)
           linum-mode)
      (call-interactively 'goto-line)
    (unwind-protect
        (progn
          (linum-mode 1)
          (call-interactively 'goto-line))
      (linum-mode -1))))

(global-set-key [remap goto-line] 'goto-line-with-feedback)
;;---------------------------------------------

36.3. iy-go-to-char

Same as ’f’ in vim. For faster navigation/jump through text. I haven’t gotten into the habit of using this yet. Good to combine with key-chord

;;iy-go-to-char--------------------------------
;;move marker to character. Like 'f' in vim.
(when (require 'iy-go-to-char nil 'noerror)
;;(when (locate-library "iy-go-to-char")
  (global-set-key (kbd "C-c f") 'iy-go-to-char)
  (global-set-key (kbd "C-c F") 'iy-go-to-char-backward)
  (global-set-key (kbd "C-c ,") 'iy-go-to-char-continue)
  (global-set-key (kbd "C-c .") 'iy-go-to-char-continue-backward)
)
;;---------------------------------------------

36.4. cursor

Similar to emacs-fu’s code, but not as good for read only.

;; cursor -------------------------------------
(blink-cursor-mode 1)           ; blink cursor
;; http://www.emacswiki.org/cgi-bin/wiki/download/cursor-chg.el
;; change cursor for verwrite/read-only/input
(when (require 'cursor-chg nil 'noerror)  ; Load this library
  (change-cursor-mode 1) ; On for overwrite/read-only/input mode
  (toggle-cursor-type-when-idle 1)
  (setq curchg-default-cursor-color "Yellow"))
;;---------------------------------------------

36.5. popup-shell

Some code from here. Could be handy but I never use it. A shell pops up when pressing F11.

(defvar th-shell-popup-buffer nil)

(defun th-shell-popup ()
  "Toggle a shell popup buffer with the current file's directory as cwd."
  (interactive)
  (unless (buffer-live-p th-shell-popup-buffer)
    (save-window-excursion (shell "*Popup Shell*"))
    (setq th-shell-popup-buffer (get-buffer "*Popup Shell*")))
  (let ((win (get-buffer-window th-shell-popup-buffer))
        (dir (file-name-directory (or (buffer-file-name)
                                      ;; dired
                                      dired-directory
                                      ;; use HOME
                                      "~/"))))
    (if win
        (quit-window nil win)
      (pop-to-buffer th-shell-popup-buffer nil t)
      (comint-send-string nil (concat "cd " dir "\n")))))

(global-set-key (kbd "<f11>") 'th-shell-popup)

36.6. auto-dictionary (fails):

Should autodetect language, but is just slow.

;;--------------------------------------------
(when (require 'auto-dictionary nil 'noerror)
  ;;So slow, does not work as well as wished.
  (add-hook 'flyspell-mode-hook (lambda () (auto-dictionary-mode 1)))
)
;;--------------------------------------------

36.7. highlight current line

;;highlight line------------------------------
;; hl-line: highlight the current line
(when (fboundp 'global-hl-line-mode)
  (global-hl-line-mode t)) ;; turn it on for all modes by default
;;--------------------------------------------

36.8. cyberpunk cursor

Changes color while blinking. Keep in mind: blinking cursor equals screen updates equals higher power usage which might not be what you want on a laptop, or in a world with no infinite energy-source.

;;Cyberpunk cursor-----------------------------
;; Changes color while blinking
(defvar blink-cursor-colors (list  "#92c48f" "#6785c5" "#be369c" "#d9ca65")
  "On each blink the cursor will cycle to the next color in this list.")

(setq blink-cursor-count 0)
(defun blink-cursor-timer-function ()
  "Cyberpunk variant of timer `blink-cursor-timer'. OVERWRITES original version in `frame.el'.
This one changes the cursor color on each blink. Define colors in `blink-cursor-colors'."
  (when (not (internal-show-cursor-p))
    (when (>= blink-cursor-count (length blink-cursor-colors))
      (setq blink-cursor-count 0))
    (set-cursor-color (nth blink-cursor-count blink-cursor-colors))
    (setq blink-cursor-count (+ 1 blink-cursor-count))
    )
  (internal-show-cursor nil (not (internal-show-cursor-p)))
  )
;;--------------------------------------------

36.9. geeky startup message

Definitley not needed by anyone, but nerdy fun.

;;--------------------------------------------
;;A geeky startup message, somewhat reminiscent of “The Matrix: Reloaded”
(defconst animate-n-steps 3)
(defun emacs-reloaded ()
  (animate-string (concat ";; Initialization successful, welcome to "
                          (substring (emacs-version) 0 16) ".")
                  0 0)
  (newline-and-indent)  (newline-and-indent))
(add-hook 'after-init-hook 'emacs-reloaded)
;;--------------------------------------------

37. EMACS 24 news

37.1. TODO Check out

electric-pair-mode, electric-indent-mode, electric-layout-mode

37.2. Count words (obsolete since Emacs 24)

From emacs 24(.3?) M-= counts words (as defined by the current mode), lines, and characters in region; C-u M-= in entire buffer, so this code is no longer needed. Uses count-words-region and count-words.

;;count words-----------------------------------
;;Prior to emacs 24 there was no count-words function
;;Taken from emacs-fu.
(if (< emacs-major-version 24)
    (defun count-words (&optional begin end)
      "count words between BEGIN and END (region); if no region defined, count words in buffer"
      (interactive "r")
      (let ((b (if mark-active begin (point-min)))
            (e (if mark-active end (point-max))))
        (message "Word count: %s" (how-many "\\w+" b e)))))
;;--------------------------------------------

37.3. minibuffer TAB completion

Nice. More like zsh.

;;TAB cycles if fewer than 5 completions. Else show *Completions*
;;buffer.
  (if (>= emacs-major-version 24)
      (setq completion-cycle-threshold 5))

38. EMACS 25 news

https://www.masteringemacs.org/article/whats-new-in-emacs-25-1

x-select-enable-clipboard’ is renamed ’select-enable-clipboard’ and ’x-select-enable-primary’ is renamed ’select-enable-primary’. Additionally they both now apply to all systems (OSX, GNUstep, Windows, you name it), with the proviso that on some systems (e.g. Windows) ’select-enable-primary’ is ineffective since the system doesn’t have the equivalent of a primary selection.

Successive single-char deletions are collapsed in the undo-log just like successive char insertions. Which commands invoke this behavior is controlled by the new ’undo-auto-amalgamate’ function. See the node “Undo” in the ELisp manual for more details.

New command ’comment-line’ bound to ’C-x C-;’.

New minor mode ’global-eldoc-mode’ is enabled by default.

The way to turn on and off ’save-place’ mode has changed. It is no longer sufficient to load the saveplace library and set ’save-place’ non-nil. Instead, use the two new minor modes: ’save-place-mode’ turns on saving last place in every file, and ’save-place-local-mode’ does that only for the file in whose buffer it is invoked. The ’save-place’ variable is now an obsolete alias for ’save-place-mode’, which replaces it, and ’toggle-save-place’ is an obsolete alias for the new ’save-place-local-mode’ command.

New command ’package-install-selected-packages’ installs all packages from ’package-selected-packages’ which are currently missing.

New command ’package-autoremove’ removes all packages which were installed strictly as dependencies but are no longer needed.

pinentry.el allows GnuPG passphrase to be prompted through the minibuffer instead of a graphical dialog, depending on whether the gpg command is called from Emacs (i.e., INSIDE_EMACS environment variable is set). This feature requires newer versions of GnuPG (2.1.5 or later) and Pinentry (0.9.5 or later). To use this feature, add “allow-emacs-pinentry” to “~/.gnupg/gpg-agent.conf” and reload the configuration with “gpgconf –reload gpg-agent”.

’setq’ and ’setf’ must now be called with an even number of arguments. The earlier behavior of silently supplying a nil to the last variable when there was an odd number of arguments has been eliminated.

’package-initialize’ now sets ’package-enable-at-startup’ to nil if called during startup. Users who call this function in their init file and still expect it to be run after startup should set ’package-enable-at-startup’ to t after the call to ’package-initialize’.

New variable ’text-quoting-style’ to control how Emacs translates quotes. Set it to ’curve’ for curved single quotes, to ’straight’ for straight apostrophes, and to ’grave’ for grave accent and apostrophe. The default value nil acts like ’curve’ if curved single quotes are displayable, and like ’grave’ otherwise. The new variable affects display of diagnostics and help, but not of info. As the variable is not intended for casual use, it is not a user option.

39. TESTING GROUND

Here I put stuff I’m currently playing around with, or just forgotten about.

39.1. test .emacs sanity

Code snippet that will test the emacs config file and echo “all is well” if no errors, or pop up a buffer describing the error. From here

(defun my-test-emacs ()
  (interactive)
  (require 'async)
  (async-start
   (lambda () (shell-command-to-string
          "emacs --batch --eval \"
(condition-case e
    (progn
      (load \\\"~/.emacs\\\")
      (message \\\"-OK-\\\"))
  (error
   (message \\\"ERROR!\\\")
   (signal (car e) (cdr e))))\""))
   `(lambda (output)
      (if (string-match "-OK-" output)
          (when ,(called-interactively-p 'any)
            (message "All is well"))
        (switch-to-buffer-other-window "*startup error*")
        (delete-region (point-min) (point-max))
        (insert output)
        (search-backward "ERROR!")))))

39.2. Screenwriting mode

http://ericjmritz.name/2014/04/26/screenwrite-mode-for-gnu-emacs/

screenwriter mode (fork)

Fix stuipid rebinding of default emacs keys:

(define-key screenwriter-mode-map (kbd "C-c C-s") 'screenwriter-slugline)
(define-key screenwriter-mode-map (kbd "C-c C-a") 'screenwriter-action-block)
(define-key screenwriter-mode-map (kbd "C-c C-d") 'screenwriter-dialog-block)
(define-key screenwriter-mode-map (kbd "C-c C-t") 'screenwriter-transition)

39.3. open-with

Good for opening an html-file in your web browser, for instance.

On OSX it would use the “open” program to decide which program to open the file with, otherwise you’d be prompted to enter the name of the program in the minibuffer. src

Note: This causes Emacs to lock until the opened program exits.

;;Open-file-with-------------------------------
(defun open-with ()
  "Simple function that allows us to open the underlying
file of a buffer in an external program."
  (interactive)
  (when buffer-file-name
    (shell-command (concat
                    (if (eq system-type 'darwin)
                        "open"
                      (read-shell-command "Open current file with: "))
                    " "
                    buffer-file-name))))

;;(global-set-key (kbd "C-c o") 'open-with)
;;---------------------------------------------

39.4. lusty exploorer

Alternative way to open files. Opens a split minibuffer with all files matching current typed string, and narrows search as you type. Better than default emacs behavior, there are other ways I prefer.

;Testar lusty exploorer----------------------
(when (require 'lusty-explorer nil 'noerror) ;;Only read if package available
  ;; override the normal file-opening, buffer switching
  (global-set-key (kbd "C-x C-f") 'lusty-file-explorer)
  (global-set-key (kbd "C-x b")   'lusty-buffer-explorer))
;;--------------------------------------------

39.5. Disable cua and transient mark modes in term-char-mode

;;--------------------------------------------
;; disable cua and transient mark modes in term-char-mode
;; http://www.emacswiki.org/emacs/AnsiTermHints
;; remember: Term-mode remaps C-x to C-c
(defadvice term-char-mode (after term-char-mode-fixes ())
  (set (make-local-variable 'cua-mode) nil)
  (set (make-local-variable 'transient-mark-mode) nil)
  (set (make-local-variable 'global-hl-line-mode) nil)
  (ad-activate 'term-char-mode)
  (term-set-escape-char ?\C-x))

(add-hook 'term-mode-hook
          (lambda()
            (local-unset-key (kbd "<tab>"))))
;;--------------------------------------------

39.6. Only show auto-completions buffer on second Tab-press

;;--------------------------------------------
;;only show auto-completions buffer on second Tab-press
;;if no match is found
(setq completion-auto-help 1)
;;--------------------------------------------

39.7. Auto completion for: () {} [] “” ’’

Pairs any kind of bracket. Simple but effective. Note, don’t use this with paredit (which is a powerful Lisp-mode parenthesis matcher).

;;--------------------------------------------
;; auto-completion on brackets.
(setq skeleton-pair t)
(global-set-key (kbd "(") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "{") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "[") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "\"") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "'") 'skeleton-pair-insert-maybe)   ;; TODO: don't use in lisp-mode'
;;--------------------------------------------

39.8. autopair ({[]})

Smart matching of parenthesis. EW. source.

;;(autoload 'autopair-global-mode "autopair" nil t)
(when (require 'autopair nil 'noerror)
  ;; Use paredit intead in any lsip-environment:
  (add-hook 'lisp-mode-hook             #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'emacs-lisp-mode-hook       #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'lisp-mode-hook             #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'lisp-interaction-mode-hook #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'scheme-mode-hook           #'(lambda () (setq autopair-dont-activate t)))
  (add-hook 'slime-mode-hook            #'(lambda () (setq autopair-dont-activate t))) ;does not fix
  (add-hook 'slime-repl-mode-hook       #'(lambda () (setq autopair-dont-activate t))) ;does not fix
  (autopair-global-mode) ;; to enable in all buffers
  (setq autopair-blink 'nil))

40. END

40.1. custom stuff

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(safe-local-variable-values (quote ((flyspell-mode)))))
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )

40.2. Send message to message-buffer

(message "Configuration file read to end")