Keyboard Macros

You can record keystrokes and commands in Emacs and save them for later playback as a keyboard macro. A keyboard macro in Emacs is very different from a lisp macro and you should not confuse the two.

Basic Commands

Key Binding Description
F3 Starts macro recording or inserts counter value
F4 Stop macro recording or play last macro
C-x ( and C-x ) Starts and stop macro recording
C-x e Plays last macro

You can also pass the universal argument and digit arguments to the macro commands:

Key Binding Description
C-u F3 Starts recording but appends to the last macro
C-u F4 Plays the second macro in the ring
numeric F3 Starts recording but sets counter to numeric
numeric F4 Plays last macro numeric times

Appending to the last macro (C-u F3) is occasionally useful, but passing a numeric argument to F4 is very useful since replaying the macro a set number of times is a frequent thing indeed; so much so that passing digit 0 (C-0 F4 or C-u 0 F4, for instance) will run the macro over and over again until it terminates with an error, such as reaching the end of a buffer or when a command in the macro triggers an error.

Advanced Commands

There is an entire prefix key group, C-x C-k, dedicated to Emacs’s macro functionality. There are many commands and you are unlikely to ever use most of them.

Interactive Macro Playback

Let’s start out with the counters. When you start recording, Emacs will automatically initialize an internal counter to zero, and every time you press F3 during the recording, Emacs will insert the counter and then increment the internal counter by 1. There are, of course, many creative uses for the counter: creating numbered lists is the most obvious.

Key Binding Description
C-x C-k C-a Adds to counter
C-x C-k TAB, F3 Inserts counter
C-x C-k C-c Sets counter
C-x C-k C-f Sets format counter
C-x C-k q Queries for user input while recording

The standout command is C-x C-k q. When you call it, Emacs will tag that step in the macro recording and ask the user for advice – in effect stopping the macro temporarily to prompt the user – before continuing.

Query Key Binding Description
Y Continues as normal
N Skips the rest of the macro
RET Stops the macro entirely
C-1 Recenters the screen
C-r Enters recursive edit
C-M-c Exits recursive edit
Saving and Recalling

Macros in Emacs are stored in a macro ring, a concept that you should recognize from other parts of Emacs (like the kill ring and undo ring.) Creating a new macro automatically stores old macros in the macro ring without you having to do anything. The commands below let you save and recall from the macro ring, edit and bind macros to keys, and more.

Key Binding Description
C-x C-k C-n Cycles macro ring to next
C-x C-k C-p Cycles macro ring to previous
C-x C-k n Names the last macro
C-x C-k b Binds the last macro to a key
C-x C-k e Edits last macro
C-x C-k l Edits the last 300 keystrokes
M-x insert-kbd-macro Inserts macro as elisp

Text manialations is one aspect Emacs is especially good at, and it has a variety of tools to help you. Massaging text files for further processing or extracting pertinent information from log files are both common things to do in Emacs.

Editable Occur

I introduced M-x occur in Occur(M-s o in helm): Print lines matching an expression as a way of collating all lines that match a certain pattern.

You can typing e begin to edit, and after you finish, C-c C-c to commit the changes to their original lines, it is especially great for keyboard macros and search & replace.

Deleting Duplicates

By default, M-x delete-duplicate-lines deletes the first dupli- cate line it encounters, starting from the top. With a single universal argument, it starts from the bottom and therefore deletes the last.

Univeral Argument Description
Without Delete first duplicate line
C-u Delete last duplicate line
C-u C-u Delte only adjacent duplicates
C-u C-u C-u Does not delete adjacent blank lines

Flushing and Keeping Lines

Sometimes you want to filter lines in a region by a pattern; whether that is to flush lines that match a pattern, or keep the ones that do.

Both commands act on the active region so it is common – if you want to do this on a whole buffer - to call C-x h to select the entire buffer first.

Command Description
M-x flush-lines Flushes (deletes) all lines in a region that match a pattern
M-x keep-lines Keeps all lines in a region that match a pattern and removes all non-matches

Keeping lines that match a pattern is useful for large log files then you want to.

Joining and Splitting Lines

Unlike the kill commands that act on lines (C-M-<backspace> and C-k), these commands won’t alter your kill ring. They are also more specialized, as they insert or remove lines with- out moving your point.

Key Binding Description
C-o Inserts a blank line after point
C-x C-o Deletes all blank lines after point
C-M-o Splits a line after point, keeping the indentation
M-ˆ Joins the line the point is on with the one above

Whitespace Commands

Managing whitespace is an issue that recurs often when you yank text from elsewhere or if you work with languages where whitespace is significant.

Command Description
M-SPC Deletes all but I space or tab to the left and right of the point
M-x cycle-spacing As above but cycles through all but one, all, and undo
M-\ Deletes all spaces and tabs around the point

M-SPC is useful as it trims all whitespace, to the left or right of the point, to a single whitespace character. ving none. M-x cycle-spacing cycles between leaving one, leaving none, and restoring the original spacing.

Transposing text is the act of swapping two syntactic units of text with one another.

Key Binding Purpose
C-t Transpose characters
M-t Transpose words
C-M-t Transpose s-expression
C-x C-t Transpose lines
M-x transpose-paragraphs Transpose paragraphs
M-x transpose-sentences Transpose sentences

C-t: Transpose Characters

1
A█BC

After C-t:

1
BA█C

Note that the point moved forward one character so you can repeat calls to C-t to “pull” the character to the right:

1
BCA█

When you are at the end of a line. C-t will swap the two characters to the left of the point:

1
BCA█

After C-t:

1
BAC█

This asymmetry is a surprisingly useful way of fixing typos as they occur. Fixing mistyped characters with C-t is a useful time saver as it saves you the effort of deleting both characters and retyping them.

M-t: Transpose Words

Transposing two words with M-t works as you would expect when the words are plain text, like this:

1
Hello █World

After M-t:

1
World Hello█

Consider this example Python code where we have a dictionary (a key-value hash map):

1
2
3
4
names = {
'Jerry':█ 'Seinfeld',
'Cosmo': 'Kramer',
}

With the point between the key and value, a call to M-t is pure magic:

1
2
3
4
names = {
'Seinfeld': 'Jerry',
'Cosmo': 'Kramer',
}

C-M-t: Transpose S-expressions

Consider what happens if we mix a balanced expression with a word:

1
Hello,█ (insert name here)!

After C-M-t:

1
(insert name here), Hello█!

Other Transpose Commands

Transposing lines with C-x C-t is useful however. I use it frequently to re-order newline-based lists and it’s also useful for swapping around variable assignments; changing the order functions are called, and so on.

Killing and Yanking Text

Key Binding Purpose
C-d Delete character
<backspace> Delete previous character
M-d, C-<backspace> Kill word
C-k Kill rest of line
M-k Kill sentence
C-M-k Kill s-expression
C-S-<backspace> Kill current line

Some clipboard-emuivalent commands:

Key Binding Kill Ring Purpose Clipboard
C-w Kill active region cut
M-w Copy to kill ring copy
C-M-w Append kill
C-y Yank last kill paste
M-y Cycle through kill ring, replacing yanked text -

Emacs’s kill commands are best summarized with five simple rules:

  • Consecutive kills append to the kill ring. When you kill some words use M-d, and then move to next line and kill another three words. Your last three words are what you yank from the kill ring, not all six! The movement command broken the cycle.

  • The kill ring can hold many items and like the undo ring you cannot lose information in the kill ring.

  • The kill ring is global and between all the buffers in Emacs. You can view the kill ring - by running C-h v kill-ring.

  • Killing is also deleting when you don't care about the killed text.

  • Marking is unnecessary for most operations that involve syntactic units. There are two exceptions:

    • If you want to copy(M-w) the region, it's quicker to mark first and then copy.
    • If you want to kill or copy odd-shaped regions that don't conform to multiples of synthetic units.

Appending to the kill ring

Type C-M-w, If next command is a kill command, it will append to the last element in the kill ring.

You can use the method to collect several comments into one big group.

Yanking Text

Key Binding Purpose Clipboard
C-y Yank last kill paste
M-y Cycle through kill ring, replacing yanked text -

Cycle through the kill ring is easy:

  1. Press C-y where you want the yanked text to appear.
  2. Without executing another command - type M-y to step back through Emacs' kill ring.

Basic key bindings

Key Bindings Purpose
C-x C-f Find (open) a file
C-x C-s Save the buffer
C-x b Switch buffer
C-x k Kill (close) a buffer
C-x C-b Display all open buffers
C-x C-c Exits Emacs
ESC ESC ESC Exits out of prompts, regions, prefix arguments and returns to just one window
C-/ Undo changes
F10 Activates the menu bar

You have several options when Emacs asks you to save a file:

Key Binding Purpose
Y or yes Saves the file
N or DEL Skips current buffer
q or RET Aborts the save, continues with exit
C-g Aborts save and the exit
! Save all remaining buffers
d Diff the file on the file system with the one in the buffer

IDO mode

To enable it, type M-x ido-mode and then try C-x b or C-x C-f again.

You can enable it permanently by customizing the option ido-mode:

1
M-x customize-option RET ido-mode RET

You can also improve IDO's fuzzy matching by enabling flex matching:

1
M-x customize-option RET ido-enable-flex-matching RET

Windows Managment

Key Binding Purpose
C-x 0 Deletes the active window
C-x 1 Deletes other windows
C-x 2 Split window below
C-x 3 Split window right
C-x o Switch active window

move between windows with rebinding to M-o , add below to ~/.emacs.d/init.el

1
(global-set-key (kbd "M-o") 'other-window)

swich windows with shift key, S-<left>,S-<right>,S-<up>,S-<down>, add below to ~/.emacs.d/init.el

1
(windmove-default-keybindings)

Working with other windows

Key Binding Purpose
C-x 4 C-f Finds a file in the other window
C-x 4 d Opens M-x dired in the other window
C-x 4 C-o Displays a buffer in the other window
C-x 4 b Switches the buffer in the other window and makes it the active window
C-x 4 0 Kills the buffer and window

Frame Management

Frames are useful with multi-monitor setups.

1
2
emacs --daemon
emacsclient -nw
Key Binding Purpose
C-x 5 2 Create a new frame
C-x 5 b Switch buffer in other frame
C-x 5 0 Delete active frame
C-x 5 1 Delete other frames
C-x 5 C-f Finds a file in the other window
C-x 5 d Opens M-x dired in the other window
C-x 5 C-o Displays a buffer in the other window

Gracefully shutdown daemon

1
emacsclient -e '(save-buffers-kill-emacs)'

Getting help

Emacs is a sophisticated self-documenting editor. Every facet of Emacs is searchable or describable.

Emacs’s help system is roughly divided into three parts and knowing which one you need and when will save you time.

The Info Manual

M-x info or C-h i to access.

Key Purpose
[ and ] Previous / next node
l and r Go back / forward in history
n and p Previous / next sibling node
u Goes up one level to a parent node
SPC Scroll one screen at a time
TAB Cycles through cross-references and links
RET Opens the active link
m Prompts for a menu item name and opens it
q Closes the info browser

Look up documentation for a command by typing C-h F and at the prompt enter the name of a command.

Apropos

Key Purpose
M-x apropos display all symbols that match a given pattern
M-x apropos-command or C-h a shows all commands that match a given pattern
M-x apropos-documentation or C-h d searches just the documentation
M-x apropos-library lists all variables and functions defined in a library
M-x apropos-user-option shows user options available through the Customize interface
M-x apropos-value searches all symbols with a particular value

Describe System

key Purpose
M-x describe-mode or C-h m displays the documentation for the major mode
M-x describe-function or C-h f describes a function
M-x describe-variable or C-h v describes a variable
M-x describe-key or C-h k describes what a key binding does

Moving by character

Four fundamental movement

Key Binding Purpose
C-f Move forward by character
C-b Move backward by character
C-p Move to previous line
C-n Move to next line

Moving by line

Key Binding Purpose
C-a Moves point to the beginning of the line
C-e Moves point to the end of the line
M-m Moves point to the first non-whitespace character on this line

Moving by word

Key Binding Purpose
M-f Move forward by word
M-b Move backward by word

Subword and superword movement

Command Purpose
M-x subword-mode Minor mode that treats CamelCase as distinct words
M-x superword-mode Minor mode that treats snake_case as one word

Moving by s-expression

Key Binding Purpose
C-M-f Move forward by s-expression
C-M-b Move backward by s-expression

Down and up List

Key Binding Purpose
C-M-d Move down into a list
C-M-u Move up out of a list

Forward and backward list

Key Binding Purpose
C-M-n Move forward to the next list
C-M-p Move backward to the previous list

Other movement commands

Moving by Paragraph

Key Binding Purpose
M-} Move forward to end of paragraph
M-{ Move backward to start of paragraph

a set of variables that define the beginning and end of a paragraph:

Variable Name Purpose
paragraph-start Defines the beginning of a paragraph using a large regular expression
paragraph-separate Defines the paragraph separator as a regular expression
use-hard-newlines Set by the command M-x use-hard-newlines and defines whether a hard newline defines a paragraph

Moving by sentence

Key Binding Purpose
M-a Move to beginning of sentence
M-e Move to end of sentence

You can alter this behavior by customizing (with M-x customize-option) the following variables:

Variable Name Purpose
sentence-end-double-space Non-nil means a single space does not end a sentence
sentence-end-without-period Non-nil means a sentence will end without a period
sentence-end-without-space A string of characters that end a sentence without requiring spaces after

Moving by Defun

Key Binding Purpose
C-M-a Move to beginning of defun
C-M-e Move to end of defun

Moving by Pages

Key Binding Purpose
C-x ] Moves forward one page
C-x [ Moves backward one page

Scrolling

Key Binding Purpose
C-v Scroll down one page
M-v Scroll up one page
C-M-v Scroll down the other window
C-M-S-v Scroll up the other window

In Mac iterm2, you should use M-PageUp and M-PageDn to scroll the other window.

Move to begin and end

Key Binding Purpose
M-< Move to the beginning of the buffer
M-> Move to the end of the buffer

When you move to the beginning or end of the buffer, Emacs will place the mark – an invisible location marker – where you came from, so you can return to your old position. For instance, if you type M-< to jump to the beginning of the buffer, you can type C-u C-<SPC> to go back.

Numeric arguments

Move down 50 lines

1
M-5 0 C-n

C-u alone has the special meaning of “four times”, moves forward sixteen characters

1
C-u C-u C-f

Take a breath and be relax

My favorite player Kobe has gone. So sad these days. The beginning of 2020 seems so hard. Hold on, man, take a breath and be relax. We will win the battle!

We always want run faster, but not solid on the way. We should slow down, make little things right.

Learning basics

  • Math basic is so important, calculus, linear algebra, probability. Figure out every detail.
  • Emacs, thinking in emacs way, try to forget vim.
  • Dig deep into any concept, try to proof each formula.

Sushi and ramen spirit

  • Sushi and ramen is a spirit, they tell us to focus on one thing, do it all life time, and do it better.
  • To be a coder, we first need have faith, and then working hard, keep going, focus and do one little thing better.

Let's begin

I'll begin the basics from now on. Study every details I face.

8 and 24 R.I.P &

A new day has come!~

What is reinforcement learning

Reinforcement learning is every where in the world. I learn to write blogs in English. I learn to use emacs to do coding jobs. I do some stock trading.

Reinforcement learning includes:

  • Policy: agent's behavior function
  • Value function: how good is each state and/or action
  • Reward signal: defines the goal of a reinforcement learning problem

Policy

Policy is the agent's behavior, it is a map from state to action

  • Deteministic policy:
  • Stocastic policy:

Value function

Value funciton is a prediction of future reward, used to evaluate the goodness/badness of states,and therefor to select between actions.

Exploration and Exploitation

To obtain a lot of reward, a reinforcement learning agent must prefer actions that it has tried in the pat and found to be effective in producing reward. But to discover such actions, it has to try actions that it has not selected before. The agent has to exploit what it has already exprienced in order to obtain reward, but it also has to explore in order to make better action selections in the future.

Like variance and bias in machine learning, we always need to make trade-off. So to be or not to be, this is a problem.

I used to use vi as my coding tools. I want expore a new tool called emacs. It may bring more reward in the future, but it seems very hard at the beginning.

Don't repeat yourself

When you are coding, remember that never do same thing twice. For example you want indent some lines.

1
2
3
4
5
auto main() -> int
{
std::cout << "indent me\n";
std::cout << "indent me again\n";
}

Never move to line 3, keypress 4 spaces and move to line 4, keypress 4 space again.

Use vi, there are many ways

  • move to line 3, shift v enter vi visual mode, j select line 4, shift > to increase indent
  • move to line 3, shift v enter vi visual mode, :normal i and press 4 spaces and enter
  • move to line 3, shift v enter vi visual mode, shift > and then move to line 4, press .
  • move to line 3, ctrl v block select, and j to select next line, shift i to insert 4 spaces, esc

Also, you can use awk and sed to achieve the same effects.

Actions on the code

Actions on the code, or code transformations, is a serial's operations on the code. Record all operations into tape, called macro, and the macro can be applied to some other places, mapping the code from origin state to desired state.

Operation space

All possible operations compose an Action space. AI should learn to choice some actions, transform the code to a stable state, a state may be pass compile or pass unit test. If AI can do this, we call it auto coding.

Learning from history and some basic rules

Bayesian learning

We init some prior rules to the bot. He will update the prior with posterior.

Reinforcement Learning

Use some reinforcement strategies to perform better actions on the code.

Interactive with human

Consider the indent example above, when I indent line 3, bot help me indent line 4, is it stable? Yes, done!

0%