All notes
Emacs

Emacsrc


;; Tabs.
(setq-default indent-tabs-mode t)  ; Will always use tabs to indent.
(setq indent-tabs-width 4)
(setq default-tab-width 4)
(global-set-key (kbd "TAB") 'self-insert-command) ; for Fundamental mode.

(fset 'yes-or-no-p 'y-or-n-p) ;make the y or n suffice for a yes or no question.

;; Must have - between modifier and key, e.g. C-c, M-s.
(global-set-key (kbd "M-SPC") 'set-mark-command)
(global-set-key (kbd "C-;") 'revert-buffer)
(global-set-key (kbd "\e\e;") 'revert-buffer) ; "Escape Escape ;"

(global-set-key (kbd "<f7>") nil)
(global-set-key (kbd "<f7> %") 'query-replace-regexp)

; replace buffer-menu by ibuffer.
(global-set-key (kbd "C-x C-b") 'ibuffer)
(setq ibuffer-expert t)
(add-hook 'ibuffer-mode-hook 
  '(lambda ()
	(ibuffer-auto-mode 1)
	(toggle-truncate-lines 1)))

(setq read-file-name-completion-ignore-case nil)
(prefer-coding-system 'utf-8)
(setq-default c-syntatic-indentation nil) ; disable indentation engine of c++ mode.
(setq default-truncate-lines nil) ;t is true. nil is false.

(show-paren-mode t)
(column-number-mode t)

(delete-selection-mode t) ;transient-mark-mode will be set t automatically after this.
(transient-mark-mode t) ;highlight the active region.
;(setq default-input-method nil) ;avoid chinese input method when init emacs.
(font-lock-mode t) ; syntax highlighted.

;; add-to-list will add item before the alist by default. Use (add-to-list 'alist '(a . b) APPEND) if you want append it instead.
(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
(add-to-list 'auto-mode-alist '("\\.txx\\'" . c++-mode))
(add-to-list 'auto-mode-alist '("\\.cu\\'" . c++-mode))

(global-set-key (kbd "C-:") 'time-stamp) ; C-: was previously undefined.

;; Use: "M-x global-visual-line-mode" if truncate-lines doesn't work.
(global-set-key [?\C-t] 'toggle-truncate-lines) ; C-t is by default transpose-chars.
;; It does not apply to horizontally-split windows. Set below to make it happen:
(setq truncate-partial-width-windows nil)

(add-hook 'c-mode-hook '(lambda() (c-toggle-electric-state -1)))
(add-hook 'c++-mode-hook '(lambda() (c-toggle-electric-state -1)))

(put 'upcase-region 'disabled nil)
(put 'downcase-region 'disabled nil)

(setq initial-scratch-message nil) ; Set initial scratch message to nil.
(setq delete-by-moving-to-trash t) ; Making deleted files go to the trash can.

(when (not (equal window-system nil) )
	(custom-set-variables
	 '(ansi-color-names-vector ["#242424" "#e5786d" "#95e454" "#cae682" "#8ac6f2" "#333366" "#ccaa8f" "#f6f3e8"])
	 '(custom-enabled-themes (quote (manoj-dark)))
	 '(size-indication-mode t))
)

;;;;;;;;;;;;;;; Packages.

; start package.el with emacs
(when (>= emacs-major-version 24)
	(require 'package)
	;; melpa is emacswiki archive.
	(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))
	(package-initialize)
)

; cmake mode.
;(setq load-path (cons (expand-file-name "~/cmake-mode") load-path))
(require 'cmake-mode)
(setq auto-mode-alist
      (append '(("CMakeLists\\.txt\\'" . cmake-mode)
                ("\\.cmake\\'" . cmake-mode))
              auto-mode-alist))

Basics

Usual keys


C-x C-x
  M-x exchange-mark-and-point
C-x [email protected], C-x C-SPC
  M-x pop-global-mark
C-u C-SPC
  Jump to the mark, and set the mark from position popped off the local mark ring (this does not affect the global mark ring).
M-x helm-all-mark-rings
  List both local and global mark rings.

C-M-v
  M-x scroll-other-window
  M-next
  Scroll next window upward ARG lines; or near full screen if no ARG.

C-M-V
  M-x scroll-other-window-down
  M-prior

M-;
  M-x comment-dwim. dwim: Do What I Mean.

C-x 5 b
    switch-to-buffer-other-frame.
C-x 5 0
    delete-frame.
M-x make-frame

C-u
    universal-argument
C-u 1 1 j
    Output: jjjjjjjjjjj
C-u 1 C-u 1
    Output: 1

C-NUM
M-NUM
    digit-argument
C-1 C-u 1
    Output: 1

Debugging

M-x toggle-debug-on-error

Encoding

ergoEmacs: emacs encoding faq.

wcfNote on Best Practice: We recommend to use utf-8 always, for cross-platform. If you use gb18030 on Windows but utf-8 elsewhere, the file will have problems for git- file change only because of encoding switching. You can always set buffer-local var with "M-x revert-buffer-with-coding-system" for those GB18303 files.


;;;;; buffer-file-coding-system

buffer-file-coding-system
; Variable.
; For example, it can be chinese-gb18030-dos
; Automatically becomes buffer-local when set.
; Coding system to be used for encoding the buffer contents on saving.

; Open a file with specific coding system
Alt+x revert-buffer-with-coding-system

; Set a encoding system for saving file
Alt+x set-buffer-file-coding-system

;;;;; coding-system

; The current coding system used for opening and saving files?
Alt+x describe-coding-system

M-x prefer-coding-system
; Add CODING-SYSTEM at the front of the priority list for automatic detection.
(prefer-coding-system 'utf-8)

;;;;; terminal, selection

M-x set-terminal-coding-system
(set-terminal-coding-system CODING-SYSTEM optional TERMINAL)
; Also bound to C-x RET t
; Set coding system of terminal output to CODING-SYSTEM. All text output to TERMINAL will be encoded with the specified coding system.

M-x set-selection-coding-system
; It is bound to C-x RET x
; Make CODING-SYSTEM used for communicating with other X clients.

;;;;; language-environment

;; UTF-8 as default encoding
(set-language-environment "UTF-8")
(describe-variable 'current-language-environment)

;;;;; coding-systems

Alt+x list-coding-systems

locale-coding-system
; Var.
; Coding system to use with system messages.
; On Windows, its value is cp936

Character set and Encoding system

ergoemacs: unicode basics.

ASCII does not really separate the concepts, since it's very simple, dealing with only 128 chars.

An encoding system defines a character set implicitly.

Unicode primarily defines 2 things:

Best practise: use editorconfig

Setting coding per file with hint in file comment will not work for some file formats - e.g. CSV. And setting coding per directory is not working (see the next section).

The best practice would be to use .editorconfig file. For example:


root = true

[*]
end_of_line = crlf
insert_final_newline = true
charset = gb18030
indent_style = space
indent_size = 2

Set coding per directory

WCFNOTE: this doesn't work, since emacs dir locals doesn't support coding.

Add the following in a file '_dir-locals.el' (Windows) or '.dir-locals.el':


((nil
  (coding . gb18030-dos)))

gnu.org: directory-variables.


; Prompts for a mode (you may use 'nil' for all modes) or subdirectory name, and for variable and value, and adds the entry defining the directory-local variable.
M-x add-dir-local-variable

M-x delete-dir-local-variable

; Copies the file-local variables in the current file into .dir-locals.el.
M-x copy-file-locals-to-dir-locals

Key binding

Meta key problem, and also Super, Hyper

Set keys

;; make PC keyboard's Win key or other to type Super or Hyper, for emacs running on Windows.
(setq w32-pass-lwindow-to-system nil)
(setq w32-lwindow-modifier 'super) ; Left Windows key
(setq w32-pass-rwindow-to-system nil)
(setq w32-rwindow-modifier 'super) ; Right Windows key
(setq w32-pass-apps-to-system nil)
(setq w32-apps-modifier 'hyper) ; Menu/App key

;; set keys for Apple keyboard, for emacs in OS X
(setq mac-command-modifier 'meta) ; make cmd key do Meta
(setq mac-option-modifier 'super) ; make opt key do Super
(setq mac-control-modifier 'control) ; make Control key do Control
(setq ns-function-modifier 'hyper)  ; make Fn key do Hyper

;; On Linuxes, you should define Super & Hyper key in the OS. For example, in Ubuntu 11.04, it's under System - Preferences - keyboard then "Layout" tap, "Options" button.

int main()
{
}

What's the difference between "<return>" and "RET"?

ErgoEmacs.

"<return>" is the Return key while emacs runs in a graphical user interface.

"RET" is the Return key while emacs runs in a terminal. "RET" is also equivalent to "C-m".

If you define: (global-set-key (kbd "<return>") 'backward-char) and run emacs in terminal, your keybinding will have no effect.

Same, "TAB" is equivalent to "C-i". Same, "ESC" == "C-[".

Key definitions

ErgoEmacs gives a detailed list.


; Escape
;; The “\e, \r, \n, \t” are representations of non-printable ASCII chars in a programing language inside a string. This is a C language convention. Emacs lisp adopted this notation.
(global-set-key (kbd "\e\e;") 'revert-buffer) ; "Escape Escape ;"
(global-set-key (kbd "<escape><escape>;") 'revert-buffer) ; "Escape Escape ;"

; Single Modifier Key
(global-set-key (kbd "M-a") 'backward-char) ; Alt+a
(global-set-key (kbd "C-a") 'backward-char) ; Ctrl+a

; Function keys and Special keys
;; wcfNote: use lowercase here!!! <F3> will not work!!!
(global-set-key (kbd "<f3>")   'backward-char)   ; F3 key
(global-set-key (kbd "<kp-3>") 'backward-char)   ; the “3” key on number keypad
(global-set-key (kbd "<insert>") 'backward-char) ; Ins key
(global-set-key (kbd "<delete>") 'backward-char) ; Del key
(global-set-key (kbd "DEL") 'backward-char) ; Backspace key
(global-set-key (kbd "<deletechar>") 'backward-char) ; Delete key
(global-set-key (kbd "<home>") 'backward-char)
(global-set-key (kbd "<end>") 'backward-char)
(global-set-key (kbd "<next>") 'backward-char)   ; page down key
(global-set-key (kbd "<prior>") 'backward-char)  ; page up key
(global-set-key (kbd "<left>") 'backward-char)   ; ←
(global-set-key (kbd "<right>") 'backward-char)  ; →
(global-set-key (kbd "<up>") 'backward-char)     ; ↑
(global-set-key (kbd "<down>") 'backward-char)   ; ↓
(global-set-key (kbd "RET") 'backward-char) ; Enter/Return key
(global-set-key (kbd "SPC") 'backward-char) ; Space bar key
(global-set-key (kbd "H-b") 'backward-word) ; H is for hyper
(global-set-key (kbd "s-b") 'backward-word) ; lower case “s” is for super
(global-set-key (kbd "M-H-b") 'backward-word) ; Meta+Hyper+b
(global-set-key (kbd "M-s-b") 'backward-word) ; Meta+Super+b

; Key Sequence
;; Example of single key sequence
(global-set-key (kbd "<f7>") nil) ; good idea to put nil to the starting key
(global-set-key (kbd "<f7> <f8>") 'calendar)
(global-set-key (kbd "<f7> <f9>") 'calc)
;; Example of sequence of single or chord keys
(global-set-key (kbd "C-e") nil) ; good idea to put nil to the starting key
(global-set-key (kbd "C-e a") 'calendar)  ; Ctrl+e a
(global-set-key (kbd "C-e SPC") 'calendar)  ; Ctrl+e Space
(global-set-key (kbd "C-e C-a") 'calendar); Ctrl+e Ctrl+a

Question mark before chars

delorie.com: Character Type.

A character in Emacs Lisp is nothing more than an integer. In other words, characters are represented by their character codes. For example, the character A is represented as the integer 65.

The usual read syntax for alphanumeric characters is a question mark followed by the character:

`?A' for the character A, `?B' for the character B, and `?a' for the character a.
?Q => 81     ?q => 113
Escape sequences

You can use the same syntax for punctuation characters, but it is often a good idea to add a `\' so that the Emacs commands for editing Lisp code don't get confused. These sequences which start with backslash are also known as escape sequences.



`?\ '   the space character.
`?\\'   the '\' char.

?\a => 7                 ; C-g
?\b => 8                 ; backspace, BS, C-h
?\t => 9                 ; tab, TAB, C-i
?\n => 10                ; newline, C-j
?\v => 11                ; vertical tab, C-k
?\f => 12                ; formfeed character, C-l
?\r => 13                ; carriage return, RET, C-m
?\e => 27                ; escape character, ESC, C-[
?\\ => 92                ; backslash character, \
?\d => 127               ; delete character, DEL

Control characters may be represented using yet another read syntax - caret syntax:



?\^I and ?\^i are valid read syntax for the character C-i.

; Instead of the `^', you can use `C-'.
?\^I => 9
?\C-I => 9

; M-
M-A as `?\M-A', or as `?\M-\101'.
C-M-b as `?\M-\C-b', `?\C-\M-b', or `?\M-\002'

; Shift
; the shift bit is `\S-';
`?\C-\S-o' or `?\C-\S-O' represents the shifted-control-o character.

; Octal.
?\012 => 10         ?\n => 10         ?\C-j => 10
?\101 => 65         ?A => 65

Set key commands


;; unset a key
(global-unset-key (kbd "C-b"))
;; or
(global-set-key (kbd "C-b") nil)

(progn
  ;; some Hyper keys to insert Unicode chars
  (define-key key-translation-map (kbd "H-3") (kbd "•")) ; bullet
  (define-key key-translation-map (kbd "H-4") (kbd "◇")) ; white diamond
  (define-key key-translation-map (kbd "H-5") (kbd "†")) ; dagger
  )

Indentation

Short keys

TAB
    Indent current line "appropriately" in a mode-dependent fashion. 
LFD
    Perform RET followed by TAB (newline-and-indent). 

M-^
    Merge two lines (delete-indentation). This would cancel out the effect of LFD. 
C-M-o
    Split line at point; text on the line after point becomes a new line indented to the same column that it now starts in (split-line). 

M-m
    Move to the first nonblank character on the current line (back-to-indentation). 

C-M-\
    Indent several lines to same column (indent-region). 
C-x TAB
    Shift block of lines rigidly right or left (indent-rigidly). 
M-i
    Indent from point to the next prespecified tab stop column (tab-to-tab-stop). 

M-x indent-relative
    Indent from point to under an indentation point in the previous line.

Indent styles

Wikipedia: Indent_stype.


// k&r.
// Variants: 1TBS (1 True Braces Style), Stroustrup, Linux kernel, BSD KNF.
While (x == y) {
    something();
    somethingelse();
}

// Allman
while (x == y)
{
    something();
    somethingelse();
}

// GNU
while (x == y)
  {
    something();
    somethingelse();
  }

Set indent style

EmacsWiki: IndentingC.


(setq-default
	tab-width 4
	indent-tabs-mode t
	c-basic-offset 4
	c-default-style "k&r")

Useful tricks

C-u M-! date	Insert output ot date shell command to current point.

Editing

Concepts

The kill ring

There is only one kill ring, shared by all buffers, so you can kill text in one buffer and yank it in another buffer.

There are several other methods: you could store the text in a register, or use Accumulating Text.

The maximum number of entries in the kill ring is controlled by the variable kill-ring-max. The default is 60.

You can see the contents in the kill ring: C-h v kill-ring.

Rectangles

GNU.org: rectangles.

To specify a rectangle for a command to work on, set the mark at one corner and point at the opposite corner. The rectangle thus specified is called the region-rectangle.


M-x kill-rectangle: C-x r k
M-x copy-rectangle-as-kill: C-x r M-w
M-x yank-rectangle: C-x r y. With its upper left corner at point.

M-x delete-rectangle: C-x r d
M-x open-rectangle: C-x r o. Fill the rectangle with blank space, and push the previous contents to the right.
M-x clear-rectangle: C-x r c. Clear the rectangle with spaces.

M-x rectangle-number-lines: C-x r N.
M-x delete-whitespace-rectangle

M-x string-rectangle: C-x r t string RET. Replace with string.
M-x string-insert-rectangle

M-x rectangle-mark-mode: C-x SPC. When this mode is active, the region-rectangle is highlighted and can be edited, and the standard kill and yank commands operate on it.

"Killing" a rectangle is not killing in the usual sense; the rectangle is not stored in the kill ring, but in a special place that only records the most recent rectangle killed.

You can also copy rectangles into and out of registers with C-x r r r and C-x r i r.

Registers

emacswiki. The register name consists of a single character. Register names are case-sensitive.

Emacs: registers.


M-x view-register RET R
  Display a description of what register R contains.

The registers could store: Position, Text, Rectangle, Configuration, Number, File, Keyboard Macro, and Bookmarks (persistent).


Assume R is the register name (alwasy in the last):

Position:
M-x point-to-register: C-x r SPC R
M-x jump-to-register: C-x r j R

Text:
M-x copy-to-register: C-x r s R. Save region into register R.
M-x insert-register: C-x r i R. Insert text from register R.
M-x append-to-register RET R
  Append region to text in register R.

Number:
C-u number C-x r n R
  Store number into register R (number-to-register).
C-u number C-x r + R
  If r contains a number, increment the number in that register by number. Note that command C-x r + (increment-register) behaves differently if r contains text.

Configuration:
M-x window-configuration-to-register: C-x r w r
M-x frameset-to-register: C-x r f r
Use C-x r j r to restore a window or frame configuration. (This is the same command used to restore a cursor position.)

Keyboard Macro:
C-x C-k x r (kmacro-to-register) stores the last keyboard macro in register r.
To execute the keyboard macro in register r, type C-x r j r.

Why we need "text register" since we have kill/yank already?
It may be inconvenient to yank it from the kill ring, since each subsequent kill moves that entry further down the ring.

Delete registers?

Do you really need to clear a register? You can just override your register saving another information in it.

How to list all registers?

All of the commands that prompt for a register will display a "preview" window that lists the existing registers (if there are any) after a short delay.

To change the length of the delay, customize register-preview-delay. To prevent this display, set that option to nil. You can explicitly request a preview window by pressing C-h or F1.

Accumulating Text


append-to-buffer
  Append region to the contents of a specified buffer.

M-x prepend-to-buffer
  Prepend region to the contents of a specified buffer.

M-x copy-to-buffer
  Copy region into a specified buffer, deleting that buffer’s old contents.

M-x insert-buffer
  Insert the contents of a specified buffer into current buffer at point.

M-x append-to-file
  Append region to the contents of a specified file, at the end. The file is changed immediately on disk. You should only append to files that are not being visited in Emacs.

Skeleton

emacswiki.org.



(define-skeleton hello-world-skeleton
  "Write a greeting"  ; DocString.
  "Type name of user: "  ; The prompt string. Input will be saved as 'str'.
  "hello, " str | "world" "!" _)  ; str | "world", here "world" is the default value if str is nil.

; The _ symbol specifies the “wrap position”, i.e., where the point will end up when the skeleton has been inserted. If any text is selected beforehand, the skeleton will wrap around it.

; Then you can bind it to a key with:
(global-set-key "\C-cl" 'latex-skeleton)

Modes

ediff

Similar to vimdiff.


; Side-by-side.
(setq ediff-split-window-function 'split-window-horizontally)

Entry Points (functions)

Quick commands

Move around

j  Jump to start point. -j jump to last point. Nj jump to point N.
p/n  Previous/Next difference region.

v/V  Scrolls up/down.
</>  Scrolls left/right.
ga/gb  Goto buffer A/B.

Toggle features

? -help

| -vert/horiz split
h -highlighting
@ -auto-refinement

## -ignore whitespace
#c -ignore case
#f/#h -focus/hide regions

X -read-only in buf X
m -wide display

Manipulate

a/b -copy A/B's region to B/A
 rx -restore buf X's old diff
  * -refine current region
  ! -update diff regions

 wx -save buf X
 wd -save diff output

flycheck

Flycheck for lisp

One method is byte-compile-file.

Another option is flycheck.

ido

Fuzzy search for files using C-c C-p f
for directories using C-c C-p d

json

Download:


M-x json-mode-beautify
M-x json-mode-show-path  C-c,C-p

robe

Emacs IDE for ruby

C-c C-d         robe-doc
M-.             robe-jump

M-,             pop-tag-mark

;; As you change the code in your project, you'll want to update the running process:
; Reload a single file
C-c C-l         ruby-load-file
; Reload a project
C-c C-k         robe-rails-refresh

Questions

server doesnot respond

Add "127.0.0.1" to your no_proxy settings. See "proxy" in this page. github.com: robe issue.

Prevent emacs from adding coding info in the first line

SO: prevent emacs from adding coding info in the first line.


(setq ruby-insert-encoding-magic-comment nil)

shell

ibm.com: emacs shell.

用户实际上是工作在一个 Emacs 的文本缓冲区里面,并不直接和 Shell 进行交互。一切的命令输入都是写入到这个文本缓冲区当中,经由 comint.el从缓冲区中读取,然后转交给后台的 Shell 进程。Shell 产生的输出再由 comint.el进行收集,然后写入到用户所用的这个缓冲区当中来。

具体启动什么样的 Shell 进程 通过 Emacs 配置文件里的 shell-file-name 变量指定,或者由用户的环境变量 SHELL 或 EMACSSHEL 来指定。通常的写法是 (setq shell-file-name "/bin/bash") 或者 export EMACSSHELL=/usr/bin/zsh.

另外如果你希望使用一个支持 ANSI color 的 Shell 进程,那么最好在你的 Emacs 配置文件里面加入下面两行,以便在执行 ls – color=auto 命令的时候输出的色彩信息能够被 Emacs 正确解析。


(autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t) 
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on t)

如果我在用过 Ctrl-x 1 之后希望能够快速“退回”到“刚才”使用过的窗口设置,而不是把它再做一遍,有没有办法做呢?GNU Emacs 有一个叫做 winner-mode 的 minor mode 可以帮你完成这个愿望。只需要在你的 Emacs 配置文件里面加入下面几行


(when (fboundp 'winner-mode) 
  (winner-mode) 
  (windmove-default-keybindings))

然后就可以使用 Ctrl-c LEFT,退回你的上一个窗口设置。

Shortcuts

man shell-mode.

== Send input
C-c RET, M-x comint-copy-old-input.
    Just send the current line to shell.
RET before end of process output
    Copies the current line minus the prompt to the end of the buffer and sends it. wcfNote: annoying when you come back through history and execute command there. Use C-c RET instead.
M-x send-invisible
    reads a line of text without echoing it, and sends it to the shell. This is useful for entering passwords.
M-x comint-continue-subjob
    If you accidentally suspend your process, use it to continue.
C-c C-a, M-x comint-bol-or-process-mark

== Multiple

C-u M-x shell
    It will prompt for a name for the new shell. Also works with eshell. C-u runs the command universal-argument.
M-x rename-buffer
    Rename the buffer of your shell. Then you will be able to launch a second shell.
M-x rename-uniquely

Multiple shells

StackOverflow: run multiple shells.


(defun create-shell ()
	"creates a shell with a given name"
	(interactive);; "Prompt\n shell name:"
	(let ((shell-name (read-string "shell name: " nil)))
	(shell (concat "*" shell-name "*"))))

(defun new-shell ()
  (interactive)

  ; let-bind variables if they're intended for local use.
  (let (
        (currentbuf (get-buffer-window (current-buffer)))
        (newbuf     (generate-new-buffer-name "*shell*"))
       )

   (generate-new-buffer newbuf)
   (set-window-dedicated-p currentbuf nil)
   (set-window-buffer currentbuf newbuf)
   (shell newbuf)
  )
)

Term, Multi-term

GNUManual.

To switch between line and char mode, use these commands:

C-c C-j
Switch to line mode (term-line-mode). Do nothing if already in line mode.

C-c C-k
Switch to char mode (term-char-mode). Do nothing if already in char mode.

== The following commands are only available in char mode:

C-c C-c
Send a literal C-c to the sub-shell.

C-c char
This is equivalent to C-x char in normal Emacs. For example, C-c o invokes the global binding of C-x o, which is normally ‘other-window’.

multi-term

M-x term-continue-subjob

C-c C-j         term-line-mode
C-c C-k         term-char-mode

;; Switch
multi-term-prev
multi-term-next

M-,
    In line mode, send a line of input at a time.

Multi-term mode.


(when (eq system-type 'gnu/linux)
	(require 'multi-term)
	(setq multi-term-program "/bin/bash")
)

Set shortcut

rawsyntax.com. SO: unbinding emacs keys for multi-term.

By default, the key bindings of term-char-mode' conflict with user's keystroke. So this function unbinds some keys withterm-raw-map', and binds some keystroke with `term-raw-map'.

For more info, see info for variables: term-unbind-key-list and term-bind-key-list.

For example:


(add-hook 'term-mode-hook
  (lambda ()
    (add-to-list 'term-bind-key-alist '("M-[" . multi-term-prev))
    (add-to-list 'term-bind-key-alist '("M-]" . multi-term-next))
    (add-to-list 'term-bind-key-alist '("C-c C-k" . term-char-mode))
    (add-to-list 'term-bind-key-alist '("C-c C-j" . term-line-mode))
    (add-to-list 'term-bind-key-alist '("C-z" . term-stop-subjob))
))

Tab completion not work due to yasnippet

SO: emacs ANSI term not tab completing.


; Suggested fix:
(add-hook 'term-mode-hook (lambda()
                (yas-minor-mode -1)))

; Another fix:
(add-hook 'term-mode-hook (lambda()
        (setq yas-dont-activate t)))

Abbrev

ErgoEmacs.


(define-abbrev-table 'global-abbrev-table '(
	;; email
	("8me" "[email protected]")
	;; computing tech
	("8wp" "Wikipedia")
	("8ms" "Microsoft")
	("8g" "Google")))
;; stop asking whether to save newly added abbrev when quitting emacs
(setq save-abbrevs nil)

;; Wcf note: don't use the following for automatic abbreviation expansion. Instead, type C-x ' (expand-abbrev).
;; turn on abbrev mode globally
; (setq-default abbrev-mode t)
;; type for example 8g then press Space, then it'll expand to Google .

yassnippet

ErgoEmacs.


#name : Doctype HTML 4.01 Strict
# --
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Special Characters:

$0  the position of the cursor (after the snippte is inserted). You don't need to put a $0 if you don't need to.
$n  a field, where the n is a integer starting with 1. (Example: $1, $2, ...). Pressing tab will move cursor to these stops for user to fill in. Multiple occurrence of the same $n means typing in one field will automatically fill the other.
${n:default text}  same as $n, but provides a default text.
$&  means indent the line according to the mode's indentation rule.
`...` (backtick) is used to enclose elisp code. The lisp code will be evaluated in the same buffer the snippet is being expanded.

Examples:

<h1>\$1</h1>
<img src="\$1" class="\$2" alt="\$3">
`user-mail-address`
`(current-time-string)`

(yas-reload-all)
(yas-insert-snippet key) ;; keybinding C-c & C-s

(yas-expand) ;; tries to expand a snippet abbrev (also known as snippet key) before point.
;; When yas-minor-mode is enabled, it binds yas-expand to TAB and <tab> by default

html

ErgoEmacs.

Tag		hotkey				command name
<h1>	Ctrl+c 1			html-headline-1
<h2>	Ctrl+c 2			html-headline-2
<p> 	Ctrl+c Enter		html-paragraph
<hr>	Ctrl+c Ctrl+c -		html-horizontal-rule
<br>	C-c C-j				html-line
<ul>	Ctrl+c Ctrl+c u		html-unordered-list
<li>	Ctrl+c Ctrl+c l		html-list-item
		Ctrl+c /			sgml-close-tag
<a>		Ctrl+c Ctrl+c h		html-href-anchor
<img>	Ctrl+c Ctrl+c i		html-image
		Ctrl+c Ctrl+v		browse-url-of-buffer
		Ctrl+c Tab			sgml-tags-invisible wcfWarn: this will modify file.

How to insert my custom tag?

Put the following code in your emacs init file.


(defun insert-p-tag ()
 "Insert HTML markup <p></p>."
 (interactive)
 (insert "<p>
</p>")
 (backward-char 5)
)

;; now, set a key:
(global-set-key (kbd "<f8>") 'insert-p-tag)
;; Select the above code, then call eval-region.

Customize inserting tags


(defun wrap-html-tag (tagName)
  "Add a tag to beginning and ending of current word or text selection."
  (interactive "sEnter tag name: ")
  (let (p1 p2 inputText)
    (if (use-region-p)
        (progn
          (setq p1 (region-beginning) )
          (setq p2 (region-end) )
          )
      (let ((bds (bounds-of-thing-at-point 'symbol)))
        (setq p1 (car bds) )
        (setq p2 (cdr bds) ) ) )

    (goto-char p2)
    (insert "</" tagName ">")
    (goto-char p1)
    (insert "<" tagName ">")
    ))

Emacs table

ErgoEmacs. This feature will let you format tabular data by ASCII drawing.

table-insert: create ASCII drawing.
table-capture: convert a selection to ASCII drawing after asking for the delimiter regexps.
table-insert-row
table-insert-column
table-delete-row
table-delete-column
table-generate-source: output to HTML, LaTeX, CALS
table-release: output to space separated values

Speedbar

f: File display mode. b: Buffer display mode.

Cedet

Installation


git clone http://git.code.sf.net/p/cedet/git cedet

# Be sure to place the checked out cedet directory in your ~/.emacs.d. Then compile it:
cd cedet
make # wait for it to complete
cd contrib
make

# Finally, assume that you placed your newly cloned CEDET in ~/.emacs.d, load it into your Emacs:
# (load-file (concat user-emacs-directory "/cedet/cedet-devel-load.el"))
# (load-file (concat user-emacs-directory "cedet/contrib/cedet-contrib-load.el"))

Tuhdo.


; Save as project/ede-projects.el, and load it every time.
(ede-cpp-root-project "project_root"
	:file "/dir/to/project_root/anchor"
	:include-path '("/include1"
		"/include2") ;; add more include
	:system-include-path '("~/linux"))

; When you get errors in your configuration, the best thing to do is:
(toggle-debug-on-error)

;;;;;; Semantic
; Core to CEDET.
; If sematic parsing fails, you always have a reserved and simpler solution: use GNU Global with ggtags or helm-gtags frontends.

; Show what Semantic will try to use.
(semantic-c-describe-environment)

; Turn on sematic mode to do code parsing.
(semantic-mode)

; Semantic caches parsing result for future use.
; The cache is saved in directory specified by semanticdb-default-save-directory. The default directory is ~/.emacs.d/semanticdb.
(semanticdb-minor-mode)

; Periodically checks to see if the buffer is out of date, and reparses while the user is idle (not typing)
(global-semantic-idle-scheduler-mode)

; Make Semantic aware of new changes
(semantic-force-refresh)

; By default, only /usr/include and /usr/local/include are included. You can view it in semantic-dependency-system-include-path.
; Add more paths:
; Only C++-mode.
(semantic-add-system-include "/usr/include/boost" 'c++-mode)
; The following takes effect both in C++ and C mode.
(semantic-add-system-include "~/linux/kernel")
(semantic-add-system-include "~/linux/include")

; Shows the function at the first line of the current buffer.
(add-to-list 'semantic-default-submodes 'global-semantic-stickyfunc-mode)
; If it fails, directly call
(global-semantic-stickyfunc-mode 1)

# Solve auto-complete not to work with semanticdb
# StackOverflow.
# Change
(defun my-cedet-hook () (add-to-list 'ac-sources 'ac-source-semantic))
# into:
(defun my-cedet-hook () (add-to-list 'ac-sources 'ac-source-semantic-raw))

;;;;;; Senator
; Senator stands for SEmantic NAvigaTOR.

; Move up one reference level from current tag, e.g. the source that defines the tag or includes the tag.
; Useful in jumping to definition, or jumping to the class that a function belongs to.
; C-c , u
(senator-go-to-up-reference)

; C-c , n
(senator-next-tag)
; C-c , p
(senator-previous-tag)
; C-c , M-w
(senator-copy-tag)
; C-c , C-w
(senator-kill-tag)

; C-y, it yanks the whole thing including function interface and its body. C-c , C-y only yanks the function interface.
; C-c , C-y
(senator-yank-tag)

hs-minor

Blocks are defined by regular expressions which match the start and end of a text region. For example, anything in between { and } is a block. The regular expressions are defined in hs-special-modes-alist.


; Toggle hiding/showing of a block
; C-c @ C-c
(hs-toggle-hiding)

; Select current block at point and hide it
; C-c @ C-h
(hs-hide-block)
; Select current block at point and show it.
; C-c @ C-s
(hs-show-block)

; Hide all block with indentation levels below this block.
; C-c @ C-l
(hs-hide-level)

; Hide all top level blocks, displaying only first and last lines.
; C-c @ C-M-h
(hs-hide-all)
; Show everything
; C-c @ C-M-s
(hs-show-all)

Auto-complete

Manual Install

Manual.

Key 	Command 	Description
TAB, C-i 	ac-expand 	Completion by TAB
RET, C-m 	ac-complete 	Completion by RET
down, M-n 	ac-next 	Select next candidate
up, M-p 	ac-previous 	Select previous candidate
C-?, f1 	ac-help 	Show buffer help

Dired mode

emacswiki.

m: mark one file.
% m: mark all filenames matching a regexp.
% m RET (empty regexp): mark all files.
% g: mark all files containing a regexp.
t: toggle marked and unmarked files.

GNU.org: dired and find.

M-x find-name-dired
    Use the find utility to choose the files to show in Dired buffer.
M-x find-grep-dired
    Use the find and grep utilities to choose the files to show in Dired buffer.
M-x find-dired
    Most generous command.
M-x describe-variable find-ls-option

M-x locate
M-x locate-with-filter
    Similar, use locate utility.

dired-details minor mode:

(	dired-details-hide
)	dired-details-show

Mark file recursively

StackExchange: resursively open files matching regexp.

C-u C-x d. This let's you enter arguments for how Dired should list files. By default it says "-al" at the prompt. Add 'R' to that, ending up with "-alR".

use-package

github: use-package.

:ensure        Loads the package using package.el if necessary.
:demand        Prevent deferred loading in all cases.

:init          Code to run before PACKAGE-NAME has been loaded.
:config        Code to run after PACKAGE-NAME has been loaded.

; Find help:
C-h f use-package

(use-package multi-term
	:ensure t
	:bind* (
		("<f7> m t" . multi-term))
	:config
	(setq multi-term-program "/bin/bash")
	; Increase buffer from 2048 to larger:
(add-hook 'term-mode-hook
  (lambda ()
    (setq term-buffer-maximum-size 10000)))
	(when (fboundp 'yas-minor-mode)
  	(add-hook 'term-mode-hook (lambda()
	    (yas-minor-mode -1))))
; Add shortcuts:
(add-hook 'term-mode-hook
  (lambda ()
    (add-to-list 'term-bind-key-alist '("M-[" . multi-term-prev))
    (add-to-list 'term-bind-key-alist '("M-]" . multi-term-next))
    (add-to-list 'term-bind-key-alist '("C-c C-k" . term-char-mode))
    (add-to-list 'term-bind-key-alist '("C-c C-j" . term-line-mode))))
)

Another good reference which explains most of important features of use-package : lunaryorn.com.


; "Local" packages:
(use-package autoit-mode
	:ensure nil
	:load-path "~/wcfShells/emacs/packages/autoit"
	:config
	(add-to-list 'auto-mode-alist
    '("\\.au3" . autoit-mode)
	)
)

; Idle initialisation
(use-package company
  :ensure t
  :defer t
  :idle (global-company-mode))

About key-binding

Use bind-key instead of global-set-key, such as:


(bind-key* "<f7> h o" 'htmlOccur)

M-x describe-personal-keybindings
    See all such keybindings you've set throughout your .emacs file.

cacheStoCaches: getting started use-package.

Tramp mode

EmacsWiki.

  • TRAMP (Transparent Remote Access, Multiple Protocols) is a package for editing remote files, similar to AngeFtp or efs.
  • It can transfer the files using rcp or a similar program, or it can encode the file contents (using uuencode or base64) and transfer them right through the shell connection.
  • A good alternative to Tramp that doesn’t do anything at the Emacs level is sshfs. Sshfs allows mounting on the fly a remote filesystem via ssh on a local mount point and to copy from it (see https://wiki.archlinux.org/index.php/Sshfs). It could be as simple (under emacs): ‘sshfs host: localmountpoint’ or, if username, id and gid are different as complex as ‘sshfs [email protected]: localmountpoint -o idmapfile,uidfile=uid,gidfile=gid’.

C-x C-f /remotehost:filename  RET (or /method:[email protected]:filename)

# Port 2222
C-x C-f /ssh:test[email protected]#2222:/tmp

# Using su to edit stuff as root
C-x C-f /su::/etc/hosts RET

; Helpful variables you can set for debugging
(require 'tramp)
(setq tramp-debug-buffer t)
(setq tramp-verbose 10)

Customization

Variables

File variables

In the first line


;; -*- mode: Lisp; coding: utf-8; fill-column: 75; comment-column: 50; -*-

A local variables list

Emacs recognizes the prefix and suffix by finding them surrounding the magic string ‘Local Variables:’, on the first line of the list.


/* Local Variables:  */
/* mode: c           */
/* comment-column: 0 */
/* End:              */

Special keywords

Some “variable names” have special meanings in a local variables list:

Safety of file variables

File-local variables can be dangerous. Therefore, whenever Emacs encounters file local variable values that are not known to be safe, it displays the file’s entire local variables list, and asks you for confirmation before setting them.

Packages

list-packages


(require 'package)
(add-to-list 'package-archives
             '("melpa-stable" . "https://stable.melpa.org/packages/"))
(package-initialize)

SE.
(package-install 'auctex)
; For multiple packages you can use the following:
(setq my-package-list '(package1 package2 packageN))
(mapc #'package-install my-package-list)

M-x describe-package RET pkgName RET

New packages are installed at ~/.emacs.d/elpa/.


;; (featurep FEATURE &optional SUBFEATURE). Return t if FEATURE is present in this Emacs.
(when (featurep 'auto-complete)
;; Do something with auto-complete.
)

http://ergoemacs.org/emacs/emacs_package_system.html.

Feature not provided

Go to the package main file, you will find it's empty. Thus the error is because the package downloading fails.

"list-packages" and press 'd' to delete the package, and re-install it again. If it doesn't work, restart emacs. SO: reinstall package.

Fonts

describe-char
describe-font

; List all fonts.
(print (font-family-list))
; Returns true if Symbola exists
(member "Symbola" (font-family-list))

Fallback fontset for unicode

stackOverflow: how do you specify a fallback font in emacs.


(set-fontset-font "fontset-default" 'unicode
                  "Microsoft YaHei" nil 'prepend)

Lambda


;; An anonymous function.
(lambda (number) (* 7 number))
;; Calling this function, get result: 7*3=21.
((lambda (number) (* 7 number)) 3)

prog1, prog2, progn

Reference. progn: Sequentially execute its arguments and returns the value of the last one.


(progn (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
⇒ "The third form"

(prog1 (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
⇒ "The first form"

(prog2 (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
⇒ "The second form"

Commands

Check if a symbol is defined

Reference. The fboundp actually check a symbol's function cell. Similarly, the boundp checks a symbol's value cell.


; Check if a function is define
(fboundp 'setq) ; t

; Check a variable.
(boundp 'auto-mode-alist) ;t
(boundp 'nil) ; t
(boundp 'wcf) ; nil

; check if a “feature” (package) has been loaded
(featurep 'expand-region) ; nil. I have none of this.
(require 'unicad);
(featurep 'unicad) ; t. I've just installed this.

Data types

cons, car, cdr

cons is used to construct lists. car fetches the first item, and cdr fetches the rest. Reference on car and cdr.


(car '(rose violet daisy buttercup)) ; Returns "rose".
(first '(rose violet daisy buttercup)) ; Returns "rose".
(cdr '(rose violet daisy buttercup)) ; Returns "(violet daisy buttercup)".
(rest '(rose violet daisy buttercup)) ; Returns "(violet daisy buttercup)".

arrays

Lisp has mostly lists, but it also has arrays, which consists of four kinds:

alist, Association lists

Reference. alist is short for Association List, similar to STL Map, recording keys and values. The car of each cons cell is the key, and the cdr is the associated value.

A typical alist:


((pine . cones)
 (oak . acorns)
 (maple . seeds))

;; Symbol a associated with 1. String "b" associated with (2 3).
((a . 1) ("b" 2 3))

;; Set the alist trees.
(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
     ⇒ ((pine . cones) (oak . acorns) (maple . seeds))
;; assoc is used for looking up.
(assoc 'oak trees)
     ⇒ (oak . acorns)
(cdr (assoc 'oak trees))
     ⇒ acorns
;; birch is not in trees.
(assoc 'birch trees)
     ⇒ nil
;; Reverse look up. rassoc uses cdr to look up.
(rassoc 'acorns trees)
     ⇒ (oak . acorns)

;; Yet another example.
(setq needles-per-cluster
      '((2 "Austrian Pine" "Red Pine")
        (3 "Pitch Pine")
        (5 "White Pine")))
(cdr (assoc 3 needles-per-cluster))
     ⇒ ("Pitch Pine")
(cdr (assoc 2 needles-per-cluster))
     ⇒ ("Austrian Pine" "Red Pine")

assq is used more often than assoc, since eq is faster than equal and most alists use symbols as keys. See Equality Predicates.


(assq 'pine trees)
     ⇒ (pine . cones)
;; On the other hand, assq is not usually useful in alists where the
;;	keys may not be symbols:
(setq leaves
      '(("simple leaves" . oak)
        ("compound leaves" . horsechestnut)))
(assq "simple leaves" leaves)
     ⇒ nil
(assoc "simple leaves" leaves)
     ⇒ ("simple leaves" . oak)

What is the differece between (lily white) and (lily . white)?


(setq colors '((rose red) (lily white) (buttercup yellow)))
(rassq 'white colors)
     ⇒ nil
;;In this case, the cdr of the association (lily white) is not the
;;	symbol white, but rather the list (white). This becomes clearer if the
;;	association is written in dotted pair notation:
(lily white) == (lily . (white))

Manipulating alist. Reference to add-to-list.


(setq alist '((foo 1) (bar 2) (foo 3) (lose 4)))
     ⇒ ((foo 1) (bar 2) (foo 3) (lose 4))
;; Delete.
(assq-delete-all 'foo alist)
     ⇒ ((bar 2) (lose 4))
;; NOTE: the original alist is also modified: duplicate keys become unique.
alist
     ⇒ ((foo 1) (bar 2) (lose 4))
;; Add a new cons in the front and override the existing one.
(add-to-list 'html-tag-alist '("code"))
;; Undo the addition. This will remove the FIRST match.
(setq html-tag-alist (delq (assoc "code" html-tag-alist) html-tag-alist))
(assoc "code" html-tag-alist)

When searching an association list for an association with a given key, the first one found is returned, if there is more than one.
In Emacs Lisp, it is not an error if an element of an association list is not a cons cell. The alist search functions simply ignore such elements.

Compiling emacs

Emacs needs libgif, libtiff, libXpm. In CentOS, you should install the devel suit for them:


sudo yum install giflib-devel libtiff-devel libXpm-devel libjpeg-devel ncurses-devel

# On CentOS 6.5, I came across Error:
# undefined reference to `g_settings_get_value'
# The following works:
# Reference.
./configure --without-gsettings

eshell

Ref. Eshell is a shell written entirely in Emacs-Lisp. It replicates most of the features and commands from GNU CoreUtils and the Bourne-like shells, such as ls and cp in Emacs-Lisp. Eshell is woefully underdocumented.

Emacs FAQ

Proxy

SO: emacs behind http proxy.

(setq url-proxy-services
   '(("no_proxy" . "^\\(localhost\\|10.*\\|127.0.0.1\\)")
     ("http" . "proxy.me:8080")
     ("https" . "proxy.me:8080")))

defvar, defcustom, setq

References:

use setq or setq-default for variables defined by 'defvar'.

'set' is the main function to set the value of a variable. 'setq' is another version that automatically quotes its first argument. This is useful since quoting the first argument is what you want to do almost all the time. (setq foo bar) is shorthand for (set (quote foo) bar).

To set this variable globally, you use 'set-default' or 'setq-default'.

defvar

'defvar' which allows the package writer to define a variable and to give some documentation.

'defcustom' builds on 'defvar'. This macro uses `defvar' as a subroutine, which also marks the variable as "special", so that it is always dynamically bound even when `lexical-binding' is t.

defcustom

Specify variables using defcustom so that you and others can then use Emacs's customize feature to set their values.

you are better off using custom-set-variables or customize-set-variable instead of setq.


(customize-set-variable 'sgml-basic-offset 0)

(defcustom SYMBOL STANDARD
  DOC &rest ARGS)

(defcustom json-reformat:indent-width 4
  "How much indentation `json-reformat-region' should do at each level."
  :type 'integer
  :safe #'integerp
  :group 'json-reformat)

;; Set the var.
(custom-set-variables &rest ARGS)
; The arguments should each be a list of the form:
  (SYMBOL EXP [NOW [REQUEST [COMMENT]]])
; This stores EXP (without evaluating it) as the saved value for SYMBOL.
; If NOW is present and non-nil, then also evaluate EXP

(custom-set-variables
 '(column-number-mode t)
)

Chinese char displayed as boxes in comments

StackOverflow: tomorrow theme shows chinese chars as blocks.

It seems like the font you choose doesn't support italic Chinese characters. Type M-x customize-face RET font-lock-comment-face and change slant value to "normal" (wcfNote: not uncheck the checkbox), and the characters should appear.


(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.
 '(default ((t (:family "Inconsolata" :foundry "outline" :slant normal :weight normal :height 240 :width normal))))
 '(font-lock-comment-face ((t (:foreground "chocolate1" :slant normal))))
)

Convert between char and its ASCII code

SO: get ASCII value of a char.

put a question mark before the character and evaluate that expression "?a" (97). Number appears in minibuffer, with C-u it's written behind expression.

Also the inverse works. "(insert 97)" will insert an "a" in the buffer. wcfNOTE: "insert" is non-interactive.

In some cases the character should be quoted

?\" will eval to 34

Can't type Ctrl-;

This stackoverflow explains why: terminal just can't convert Ctrl-; to any ASCII (while CTRL-X etc could be converted due to a list).

EmacsWiki.

ASCII has 33 control characters and the terminal operator sent them by pressing a special key (such as DEL) or by holding down the CTRL key and pressing another key. "Ctrl-;" is not in the ASCII list.

Solution: use keybinding "Meta Meta ;":


; \e means Meta-.
(global-set-key (kbd "\e\e;") 'revert-buffer)

Copy and paste from clipboard

Mac OS

SO: how to paste to emacs from clipboard on OS X.



(when (and (eq system-type 'darwin) (eq window-system nil) )

  (defun copy-from-osx ()
  (shell-command-to-string "pbpaste"))
  
  (defun paste-to-osx (text &optional push)
  (let ((process-connection-type nil))
  (let ((proc (start-process "pbcopy" "*Messages*" "pbcopy")))
  (process-send-string proc text)
  (process-send-eof proc))))
  
  (setq interprogram-cut-function 'paste-to-osx)
  (setq interprogram-paste-function 'copy-from-osx)
)

# Another suggestion is: (however I found it does not work on Mac OS X)
M-x clipboard-yank
M-x clipboard-kill-region

Linux

SO: how to copy text from emacs. When Emacs is running in a console (e.g. gnome-terminal), it is completely divorced from the system and X clipboards: cut and paste in that case is mediated by the terminal.

lingotrek.com. A solution is to use xclip.

You'll need to install a program called xclip. Like pbcopy and pbpaste it works as a go-between for the X11 clipboard and console based applications.

pacman -S xclip
Add xclip.el to emacs startup.

The following is old-dated.


#----------
# https://www.emacswiki.org/emacs/CopyAndPaste#toc2

(setq select-enable-clipboard t)

# x-select-enable-clipboard - default t. Non-nil means cutting and pasting uses the clipboard.
# Related: select-enable-primary. default nil.

# NOTE: It only works for GUI emacs, not terminal emacs.

Emacs backup files

StackOverflow: what are emacs backup files.

The file with the ~ is a backup file that automatically gets created when you save a file.

The #readme.txt# is the file being currently edited/in use (i.e., the autosave version). That will usually go away (unlike the ~ file) when you exit emacs normally (if it crashes or gets killed the # files may stay around).

Override system file

Stackexchange. Stackoverflow: eval-after-load complains about symbol varlue as variable is void.


(defun wangcf:after-load:sgml-mode ()
  (if t ; replace this by a test that checks whether the bug is present in this version of Emacs
      (defun sgml-close-tag () ...)))
(eval-after-load "sgml-mode" '(wangcf:after-load:sgml-mode))

Solve: "void variable alist" error when calling sgml-attributes and sgml-tag. GNU.org.


(defun pradhan:after-load:cc-cmds ()

(defun sgml-close-tag ()
  "Close current element.
Depending on context, inserts a matching close-tag, or closes
the current start-tag or the current comment or the current cdata, ..."
  (interactive)
  (pcase (car (sgml-lexical-context))
    (`comment 	(insert " -->"))
    (`cdata 	(insert "]]>"))
    (`pi 	(insert " ?>"))
    (`jsp 	(insert " %>"))
    (`tag 	(insert " />"))
    (`text
     (let ((context (save-excursion (sgml-get-context))))
       (if context
           (progn
             (insert "</" (sgml-tag-name (car (last context))) ">")
;             (indent-according-to-mode)
		))))
    (_
     (error "Nothing to close"))))
; (eval-after-load "sgml-mode" 'sgml-close-tag)

(defun sgml-attributes (tag &optional quiet)
  "When at top level of a tag, interactively insert attributes.
Completion and configuration of TAG are done according to `sgml-tag-alist'.
If QUIET, do not print a message when there are no attributes for TAG."
  (interactive (list (save-excursion (sgml-beginning-of-tag t))))
  (or (stringp tag) (error "Wrong context for adding attribute"))
  (if tag
      (let ((completion-ignore-case t)
	    (alist (cdr (assoc (downcase tag) sgml-tag-alist)))
	    car attribute i)
	(if (or (symbolp (car alist))
		(symbolp (car (car alist))))
	    (setq car (car alist)
		  alist (cdr alist)))
	(or quiet
	    (message "No attributes configured."))
	(if (stringp (car alist))
	    (progn
	      (insert (if (eq (preceding-char) ?\s) "" ?\s)
		      (funcall skeleton-transformation-function (car alist)))
	      (sgml-value alist))
	  (setq i (length alist))
	  (while (> i 0)
	    (insert ?\s)
	    (insert (funcall skeleton-transformation-function
			     (setq attribute
				   (skeleton-read `(completing-read
						    "Attribute: "
						    ',alist)))))
	    (if (string= "" attribute)
		(setq i 0)
	      (sgml-value (assoc (downcase attribute) alist))
	      (setq i (1- i))))
	  (if (eq (preceding-char) ?\s)
	      (delete-char -1)))
	car)))
)

(eval-after-load "sgml-mode" '(pradhan:after-load:cc-cmds))

Setting indentation

StackOverflow.


; To make this change specific only to html-mode
(add-hook 'html-mode-hook
  (lambda ()
    (set (make-local-variable 'sgml-basic-offset) 0)))

StackOverflow.

Lisp directory not exist

GNU Archive. GNUDoc on General Variables.


export EMACS_DIR=/home/me/emacs-24.3/release/share/emacs/24.3
export EMACSLOADPATH=${EMACS_DIR}/lisp
export EMACSDATA=${EMACS_DIR}/etc
export EMACSDOC=${EMACS_DIR}/etc
export EMACSPATH=${EMACS_DIR}/bin

See emacs-24.3/lisp/mail/emacsbug.el:

(if val (insert (format "  value of $%s: %s\n" var val)))))
     '("EMACSDATA" "EMACSDOC" "EMACSLOADPATH" "EMACSPATH"
       "LC_ALL" "LC_COLLATE" "LC_CTYPE" "LC_MESSAGES"
       "LC_MONETARY" "LC_NUMERIC" "LC_TIME" "LANG" "XMODIFIERS"))

Required XXX feature was not provided

SO.

The according el file should have (provide 'XXX). Check the el file. The culprit may be it being corrupted, e.g. failing to download the package, and only empty el files exists in ~/.emacs.d/.

Slow startup

Stackoverflow. You need to have a fully-qualified domain name for your computer's hostname (e.g., myretina.local); otherwise, Emacs will be slow to start.


sudo hostname serverName.l

Time test

This GNU discussion gives a way to do time test:


# network adapter is initially on
time emacs --kill
# real	0m30.108s
# user	0m0.076s
# sys	0m0.020s

# turned on network adapter
time emacs --kill
# real	0m30.106s
# user	0m0.079s
# sys	0m0.019s

If you doubt that the start-up scripts hinder emacs's startup, run emacs with:


emacs -Q --debug-init

Byte compile

Ref.

# Compile all the .el files in the directory recurively.
# C-u 0: make it not ask about every .el file that does not have a .elc counterpart.
C-u 0 M-x byte-recompile-directory

# Method with dired
# In dired, press m to mark them (press u to unmark), then press B (diredp-byte-compile-this-file).

Repeat last command

To repeat the previous command once, type C-x z. To repeat it a second time immediately after, type just z. By typing z again and again, you can repeat the command over and over. Provided by repeat.el. For help, C-h F repeat RET.

Create scratch buffer

Ref. Use C-x b AnyName to create a buffer named "AnyName".