DummyHead

  • Home

  • Tags30

  • Categories16

  • Archives32

Grokking原码, 补码, 反码

Posted on 2019-06-03 | In bitOperations | Comments:

基本概念

反码是个生造出来的概念.
所谓反码,英语里又叫ones’ complement(对1求补)
所谓补码,英语里又叫two’s complement(对2求补)

模的概念

首先灌输一个新的概念叫,模

什么是“模”,想象日常使用的钟表,它可以显示0~12点的时间,假设现在是2点钟,请用手动拨动时针的方式将时间减4小时,你会怎么做?

有两种方式:

  1. 逆时针将时针拨4小时
  2. 顺时针将时针拨8(12-4)小时

这里要讲的是第二种方式,为什么顺时针拨12-4也可以达到和正常思维的第一种方式一样的位置。
12就是模。
同样的,如果是十进制的两位数,80-10 和 80+90在不考虑百位数的基础上都是70。这里的90就是100-10得来的,这种情况下100就是模
模就好比是一个极限,在它的范围内,两个相加等于模的数互为补数,还是举100的例子
90和10, 55和45,68和32,互为补数
在模的范围内做减法,可以将“X-Y”的减法变更为“X+Y的补数“的加法,当然前提是不考虑百位数

思考题,上面举的例子是大数减小数,那么如果是小数减大数会怎么样呢?
如果是10-80,结果应该是-70,但如果按照10+(100-80),结果是30。
而很明显-70和30不是一回事,这里也没有百位数的问题,这种情况应该怎么破?
当初的那些先贤们想出来的办法很简单,就是把这两个数直接划上等号,正好顺便解决了负数的表达方式。再来仔细看看这两个数的关系:-70绝对值的补数就正好是30

所以在计算机中,负数的表达方式就是它绝对值的补数

但是问题又来了,看起来这个解决方式很完美了,但别忘了,30他已经代表了正数的30了,现在又要用来代表负数的-70,谁知道它出现的时候到底是代表哪个数?
为了解决这个问题,需要给这套规则划定一个范围,原来是0~99的正数,现在既然要用部分正数来代替负数了,那就要规定一个范围来使得一个数只代表一个含义,正好一人一半,0~49这个区间就代表正数,50~99的区间就用来代表各自补数的负值,例:98就代表-2

现在回到二进制的计算机世界

8位二进制数一共可以表示2的8次方,256个数,即0~255 (别忘了0也要占一位的),他们的极限就是256,即256是8位二进制数的模 ,应该不难理解吧,同上十进制的两位数0~99的模是100。
还是用二进制来说明清楚,8位二进制能表示的数的极限是
1 1 1 1 1 1 1 1, 就是255,在这基础上加0 0 0 0 0 0 0 1,出现了进一位 即 1 0 0 0 0 0 0 0 0
这个1 0 0 0 0 0 0 0 0就是8位二进制数的模,256

同样按照第二步讲的逻辑,一半的数0~127,代表其正数本身,另一半的数 128~255,代表其补数的负值,即“-1~-128”的区间。
而 “X-Y”的减法 就用 “X+Y的补数” 的加法来表示,完美! 唯一需要注意的事情是任何计算的输入值和输出结果值都需要严格遵守-128~127的范围,一旦溢出就会报错。
这也就是我们在编程里强调的为什么 byte+byte还得是byte,int+int还得是int,数据溢出问题也是每一个程序员都需要注意的问题。

这样一说是不是可以理解-128的补码是怎么来的了吧? 他就是256-|-128|=128
二进制的128是不是就是1 0 0 0 0 0 0 0 ?

最终问题,那书和老师为什么要用原码,反码来讲补码 ?

空穴来风,未必无因

那是因为计算机就是这样求负数的补码的,我们在键盘上敲一个负数的时候,计算机要把它用补码的形式存储下来,还记得上面我们讲的补码是怎么来的吗?

模-绝对值,这是不是个减法公式?但计算机没有减法逻辑,我们费了那么大的劲搞了一套补码的规则就是为了用加法来替代减法,但为了实现这么套规则,却跨不过一个坎,就是把负数计算成补码仍然是需要减法逻辑的。怎么办呢,那些伟大的先贤们 (膜拜)就想出了这么个办法:

首位不变,其余位取反后,再加一, 

“copy and complement”的求解方法

copy-and-complement

下面是吐槽

不知道是哪个书呆子教书,照搬了机器的逻辑,把取反加一的方法当做补码的计算逻辑就这么教下来了。搞笑的是,还保留了补码这个名字,照理说这种教法应该叫 取反加一码 更合理,你还补什么啊?

不仅如此,还搞出了个首位符号位的说法,弄出了个正0负0,还用负0来充当-128,真是不把人弄疯不罢休啊!!

保留符号的运算

retain-symbols

retain-symbols2

参考资料

  • https://www.zhihu.com/question/20458542/answer/40759880

Python Format String

Posted on 2019-06-01 | In fileManager -textProcessing | Comments:

Field Width and Alignment

默认左对齐

'hey {:10}'.format('hello') Specify width (Aign left, fill with spaces)
'{:010}'.format(2) Fill with zeroesOutput: 0000000002
'{:*^30}'.format('text') Specify width, align to centerOutput: *************text*************
Option Meaning, padding
'<' Forces the field to be left-aligned within the available space (this is the default for most objects).
'>' Forces the field to be right-aligned within the available space (this is the default for numbers).
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.
'^' Forces the field to be centered within the available space.

Member and Element Access

'{0}, {1}, {2}'.format(1, 2, 3) Access arguments by ordinal positionOutput: 1, 2, 3
'{}, {}, {}'.format(1, 2, 3) Implicit positional arguments (2.7 and above only)Output: 1, 2, 3
'{value1}, {value2}, {value2}'.format(value1=1, value2=2, value3=3) Access keyword arguments by nameOutput: 1, 2, 2
'{[1]}'.format(['first', 'second', 'third']) Access element by indexOutput: second
'{.name}'.format(sys.stdin) Access element attributeOutput: <stdin>
'{[name]}'.format({'name': 'something'}) Access element by keyOutput: something

Numerical Representation

'{:x}'.format(100) Hexadecimal representationOutput: 64
'{:X}'.format(3487) Hexadecimal representation (uppercase letters)Output: D9F
'{:#x}'.format(100) Hexadecimal representation (including the 0x)Output: 0x64
'{:b}'.format(100) Binary representationOutput: 1100100
'{:c}'.format(100) Character representationOutput: d
'{:d}'.format(100) Decimal representation (default)Output: 100
'{:,}'.format(1000000) With thousands separatorOutput: 1,000,000
'{:o}'.format(100) Octal representationOutput: 144
'{:n}'.format(100) Like d, but uses locale information for separatorsOutput: 100
'{:e}'.format(0.0000000001) Exponent notationOutput: 1.000000e-10
'{:E}'.format(0.0000000001) Exponent notation (capital ‘E’)Output: 1.000000E-10
'{:f}'.format(3/14.0) Fixed pointOutput: 0.214286
'{:g}'.format(3/14.0) General formatOutput: 0.214286
'{:%}'.format(0.66) PercentageOutput: 66.000000%
'{:.3}'.format(0.214286) PrecisionOutput: 0.214

Integers

Type Meaning
'b' Binary format. Outputs the number in base 2.
'c' Character. Converts the integer to the corresponding unicode character before printing.
'd' Decimal Integer. Outputs the number in base 10.
'o' Octal format. Outputs the number in base 8.
'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.
'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None The same as 'd'.

Floating numbers

Type Meaning
'e' Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6.
'E' Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.
'f' Fixed-point notation. Displays the number as a fixed-point number. The default precision is 6.
'F' Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.
'g' General format. For a given precision p >= 1, this rounds the number to psignificant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4<= exp < p, the number is formatted with presentation type 'f' and precisionp-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.
'G' General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.
'n' Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
None Similar to 'g', except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output of str() as altered by the other format modifiers.

Conversions

'{!r}'.format('string') Calling repr on argumentsOutput: 'string'
'{!s}'.format(1.53438987) Calling str on argumentsOutput: 1.53438987

Number Formattting

The following table shows various ways to format numbers using Python’s str.format(), including examples for both float formatting and integer formatting.

To run examples use print("FORMAT".format(NUMBER));
So to get the output of the first example, you would run: print("{:.2f}".format(3.1415926));

Number Format Output Description
3.1415926 {:.2f} 3.14 2 decimal places
3.1415926 {:+.2f} +3.14 2 decimal places with sign
-1 {:+.2f} -1.00 2 decimal places with sign
2.71828 {:.0f} 3 No decimal places
5 {:0>2d} 05 Pad number with zeros (left padding, width 2)
5 {:x<4d} 5xxx Pad number with x’s (right padding, width 4)
10 {:x<4d} 10xx Pad number with x’s (right padding, width 4)
1000000 {:,} 1,000,000 Number format with comma separator
0.25 {:.2%} 25.00% Format percentage
1000000000 {:.2e} 1.00e+09 Exponent notation
13 {:10d} 13 Right aligned (default, width 10)
13 {:<10d} 13 Left aligned (width 10)
13 {:^10d} 13 Center aligned (width 10)

Official Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 1) by position:
'{0}, {1}, {2}'.format('a', 'b', 'c')
'{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'{2}, {1}, {0}'.format('a', 'b', 'c')
'{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated

#2) by name
'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
'Coordinates: {latitude}, {longitude}'.format(**coord)

#3) by attributes
c = 3-5j
('The complex number {0} is formed from the real part {0.real} '
'and the imaginary part {0.imag}.').format(c)

class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return 'Point({self.x}, {self.y})'.format(self=self)
str(Point(4, 2))

#4) by arguments' items
coord = (3, 5)
'X: {0[0]}; Y: {0[1]}'.format(coord)

#5) 注意这里的aligned用了> < Y与regex的look around保持一直
'{:<30}'.format('left aligned')
'{:>30}'.format('right aligned')
'{:^30}'.format('centered')
'{:*^30}'.format('centered') # use '*' as a fill char

#6) Replacing %+f, %-f, and % f and specifying a sign:
'{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
'{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'

# 7) Replacing %x and %o and converting the value to different bases:
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
# with 0x, 0o, or 0b as prefix:
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)

Other Examples

Padding and aligning strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#alight right 
'%10s' % ('test',)
'{:>10}'.format('test')
test
#align left:
'%-10s' % ('test',)
'{:10}'.format('test')
'{:10}'.format('test')
test
#new style
'{:_<10}'.format('test')
test______

#new style
'{:^10}'.format('test')

Truncating Long Strings

1
2
3
'%.5s' % ('xylophone',) #注意后面的小数点呀是truncate 
'{:.5}'.format('xylophone')
xylop

Combining truncating and padding

1
2
3
'%-10.5s' % ('xylophone',)
'{:10.5}'.format('xylophone')
xylop

Numbers

1
2
3
4
5
6
7
8
9
10
11
'%d' % (42,)
'{:d}'.format(42)
42

'%f' % (3.141592653589793,)
'{:f}'.format(3.141592653589793)
3.141593

#signed numbers
'%+d' % (42,)
'{:+d}'.format(42)

Getitem and Getattr

1
2
3
4
5
6
person = {'first': 'Jean-Luc', 'last': 'Picard'}
'{p[first]} {p[last]}'.format(p=person)
class Plant(object):
type = 'tree'
'{p.type}'.format(p=Plant())
'{:{align}{width}}'.format('test', align='^', width='10')

Datetime

1
2
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

十种经典排序算法

Posted on 2019-05-26 | Edited on 2019-06-01 | In algorithms - sort | Comments:

1. 冒泡排序(Bubble Sort)

这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent pairs and swaps) them if they are in the wrong order.

物理模拟的理论源头.

1.1 Pseudocodes Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#basics 
procedure bubbleSort(A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure

#improved
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure

1.2 动图演示

img

1.3 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# compare to get the small and swap 
# repeat
def bubble_sort1(arr):
for _ in range(len(arr)): #cumbersome loop
# core logic
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
temp = arr[i-1] #目标位置.
arr[i-1] = arr[i]
arr[i] = temp #swap的逻辑可以先写后面的两行。

def bubble_sort2(arr):
#上浮和下沉
while True:
swap_counter = 0
for i in range(1, len(arr)):
if arr[i] < arr[i-1]: #move smaller up
arr[i-1], arr[i] = arr[i], arr[i-1]
swap_counter += 1
if swap_counter == 0:
return

2. 插入排序 Insertion Sort, 

关键点是将第一项作为sorted sequence的分析方法.

2.1 Psedocodes

1
2
3
4
5
6
7
8
9
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while

2.2 动态演示

Sorted Make room
Insertion sort.gif

2.3 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#psudocodes 
Move the pivot entry to a temporary location leaving a hole in List
while (there is a name above the hole and
that name is greater than the pivot):
move the name above the hole down into the hole
leaving a hole above the name
Move the pivot entry into the hole in List.

#解决方案只保留一项, 越少越好.
#in-place的实现
def insertion_sort(arr):#这个思路是最清晰的.
for i in range(1, len(arr)):
#将当前的pivot拿出
pivot = arr[i] #Move the pivot to a temporay location,
hole = i # and leave a hole
#找到比当前值大的,然后下沉. hole>0是因为第一项已经排好了.
while hole > 0 and arr[hole-1] > pivot:
#当上面有更大的,下沉, 因为是排序好的,所以想象lock整体下沉。
#
arr[hole] = arr[hole-1] #下沉填充hole
hole = hole- 1 #leave the hole,两步操作.
arr[hole] = pivot #insert sort就是这么来的.
return arr

3. 选择排序 Selection Sort

Psuedocodes: 从剩下的序列中选择最小值, 逐个浮上来。

3.1 算法描述

There are many different ways to sort the cards. Here’s a simple one, called selection sort, possibly similar to how you sorted the cards above:

  1. Find the smallest card. Swap it with the first card.
  2. Find the second-smallest card. Swap it with the second card.
  3. Find the third-smallest card. Swap it with the third card.
  4. Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted.

3.2 动图演示

Effects Demonstration
Selection sort animation.gif

3.3 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#要输出的是new_arr
def selection_sort3(arr): #基本思路.
arr = list(arr)
new_arr = []
while arr:
minimum = min(arr)
new_arr.append(arr.pop(minimum))
return new_arr

def selection_sortA(nums): #selection排序的核心是从subarray中找打最小值.
for i in range(len(nums)-1): #从subarray的第一项开始
min_idx = i #设置min_idx的初始值.
for j in range(i+1, len(nums)):#从subarray中选出最小值
if nums[j] < nums[min_idx]: #不断更新
min_idx = j #找到最小值的index,只进行index操作.
#循环终止后, i是当前值,
#swap the current value and the minial value
temp = nums[i]
nums[i] = nums[min_idx]
nums[min_idx] = temp

3.4 希尔排序(Shell Sort)

希尔排序是希尔(Donald Shell)于1959年提出的一种排序算法。希尔排序也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序,同时该算法是冲破O(n2)的第一批算法之一。本文会以图解的方式详细介绍希尔排序的基本思想及其代码实现。

等闲来无事再来了解.

4. 归并排序 (Merge Sort)

In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the order of equal elements is the same in the input and output. Merge sort is a divide and conquer algorithm that was invented by John von Neumannin 1945.[2] A detailed description and analysis of bottom-up mergesort appeared in a report by Goldstine and von Neumann as early as 1948.[3]

4.1 Pseudocodes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#Top-down implementation 
function merge_sort(list m)
// Base case. A list of zero or one elements is sorted, by definition.
if length of m ≤ 1 then
return m

// Recursive case. First, divide the list into equal-sized sublists
// consisting of the first half and second half of the list.
// This assumes lists start at index 0.
var left := empty list
var right := empty list
for each x with index i in m do
if i < (length of m)/2 then
add x to left
else
add x to right

// Recursively sort both sublists.
left := merge_sort(left)
right := merge_sort(right)

// Then merge the now-sorted sublists.
return merge(left, right)

#Bottom-up Implementation
function merge_sort(node head)
// return if empty list
if (head == nil)
return nil
var node array[32]; initially all nil
var node result
var node next
var int i
result = head
// merge nodes into array
while (result != nil)
next = result.next;
result.next = nil
for(i = 0; (i < 32) && (array[i] != nil); i += 1)
result = merge(array[i], result)
array[i] = nil
// do not go past end of array
if (i == 32)
i -= 1
array[i] = result
result = next
// merge array into single list
result = nil
for (i = 0; i < 32; i += 1)
result = merge(array[i], result)
return result

4.2 动图演示

File:Merge sort animation2.gif
enter image description here

4.3 Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#psuedocodes方案
from heapq import merge
def merge_sort1(m): #Postoder
#LRN遍历,
if len(m) <= 1:
return m
mid = len(m) // 2
left = merge_sort1(m[:mid])
right = merge_sort1(m[mid:])
result = list(merge(left, right))
return result

#step by step soluthon
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
def mergeSort(L):
if len(L) < 2:
return L[:]
else:
left = mergeSort(L[:mid])
right = mergeSort(L[mid:])
return merge(left, right)
#我的时间管理可能应该是tree的结构.

#in-place merge sort
def merge_inplace(A, start, mid, end) -> "None":
left = A[start:mid]
i = 0
j = 0

for c in range(start, end): #c for cur
if j >= len(right) or (i < len(left) and left[i] < right[j]): #注意shortcuit的问题.
A[c] = left[i]
i = i + 1
else:
A[c] = right[j]
j = j + 1

def mergeSort_inplace(A, lo, hi) -> "None":
if lo < hi - 1:
mid = (lo + hi) // 2
mergeSort_inplace(A,lo,mid)
mergeSort_inplace(A,mid,hi)
merge_inplace(A, lo, mid, hi)

归并排序是一种稳定的排序方法。和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是O(nlogn)的时间复杂度。代价是需要额外的内存空间。

归并算法的代价就是需要额外的存储空间.

5. 快速排序(Quick Sort)

Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of a random access file or an array in order. Developed by British computer scientist Tony Hoarein 1959[1] and published in 1961,[2] it is still a commonly used algorithm for sorting. When implemented well, it can be about two or three times faster than its main competitors, merge sort and heapsort.[3][contradictory]

5.1 算法描述

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are:

  1. Pick an element, called a pivot, from the array.
  2. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively) apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

5.2 动图演示

Effects Demonstration
Selection sort animation.gif

5.3 Implementation

1
2
3
4
5
6
7
8
def quicksort(arr):
if len(arr) < 2:
return arr #base case
else:
pivot = arr[0]
less = [i for i in arr[1:] if i <= pivot]
more = [i for i in arr[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(more)

Magit Documentation

Posted on 2019-05-25 | In linux - emacs - magit | Comments:

A Git Porcelain inside Emacs

It’s Magit! A Git Porcelain inside Emacs

Magit is an interface to the version control system Git, implemented as an Emacs package. Magit aspires to be a complete Git porcelain. While we cannot (yet) claim that Magit wraps and improves upon each and every Git command, it is complete enough to allow even experienced Git users to perform almost all of their daily version control tasks directly from within Emacs. While many fine Git clients exist, only Magit and Git itself deserve to be called porcelains. (less)

Staging and otherwise applying changes is one of the most important features in a Git porcelain and here Magit outshines anything else, including Git itself. Git’s own staging interface (git add --patch) is so cumbersome that many users only use it in exceptional cases. In Magit staging a hunk or even just part of a hunk is as trivial as staging all changes made to a file.

The most visible part of Magit’s interface is the status buffer, which displays information about the current repository. Its content is created by running several Git commands and making their output actionable. Among other things, it displays information about the current branch, lists unpulled and unpushed changes and contains sections displaying the staged and unstaged changes. That might sound noisy, but, since sections are collapsible, it’s not.

To stage or unstage a change one places the cursor on the change and then types s or u. The change can be a file or a hunk, or when the region is active (i.e. when there is a selection) several files or hunks, or even just part of a hunk. The change or changes that these commands - and many others - would act on are highlighted.

Magit also implements several other “apply variants” in addition to staging and unstaging. One can discard or reverse a change, or apply it to the working tree. Git’s own porcelain only supports this for staging and unstaging and you would have to do something like git diff ... | ??? | git apply ... to discard, revert, or apply a single hunk on the command line. In fact that’s exactly what Magit does internally (which is what lead to the term “apply variants”).

Magit isn’t just for Git experts, but it does assume some prior experience with Git as well as Emacs. That being said, many users have reported that using Magit was what finally taught them what Git it is capable off and how to use it to its fullest. Other users wished they had switched to Emacs sooner so that they would have gotten their hands on Magit earlier.

While one has to know the basic features of Emacs to be able to make full use of Magit, acquiring just enough Emacs skills doesn’t take long and is worth it, even for users who prefer other editors. Vim users are advised to give Evil the “Extensible VI Layer for Emacs”, and Spacemacs an “Emacs starter-kit focused on Evil” a try.

Magit provides a consistent and efficient Git porcelain. After a short learning period, you will be able to perform most of your daily version control tasks faster than you would on the command line. You will likely also start using features that seemed too daunting in the past.

Magit fully embraces Git. It exposes many advanced features using a simple but flexible interface instead of only wrapping the trivial ones like many GUI clients do. Of course Magit supports logging, cloning, pushing, and other commands that usually don’t fail in spectacular ways; but it also supports tasks that often cannot be completed in a single step. Magit fully supports tasks such as merging, rebasing, cherry-picking, reverting, and blaming by not only providing a command to initiate these tasks but also by displaying context sensitive information along the way and providing commands that are useful for resolving conflicts and resuming the sequence after doing so.

Magit wraps and in many cases improves upon at least the following Git porcelain commands: add, am, bisect, blame, branch, checkout, cherry, cherry-pick, clean, clone, commit, config, describe, diff, fetch, format-patch, init, log, merge, merge-tree, mv, notes, pull, rebase, reflog, remote, request-pull, reset, revert, rm, show, stash, submodule, and tag. Many more Magit porcelain commands are implemented on top of Git plumbing commands.

两点:staging and status buffer.

Introduction:
• Installation:
• Getting Started:
• Interface Concepts:
• Inspecting:
• Manipulating:
• Transferring:
• Miscellaneous:
• Customizing:
• Plumbing:
• FAQ:
• Debugging Tools:
• Keystroke Index:
• Command Index:
• Function Index:
• Variable Index:

3 Getting Started

This short tutorial describes the most essential features that many Magitians use on a daily basis. It only scratches the surface but should be enough to get you started.

IMPORTANT: It is safest if you clone some repository just for this tutorial. Alternatively you can use an existing local repository, but if you do that, then you should commit all uncommitted changes before proceeding.

To display information about the current Git repository, type M-x magit-status RET. You will be using this command a lot, and should therefore give it a global key binding. This is what we recommend:

1
(global-set-key (kbd "C-x g") 'magit-status)

Most Magit commands are commonly invoked from the status buffer. It can be considered the primary interface for interacting with Git using Magit. Many other Magit buffers may exist at a given time, but they are often created from this buffer.

Depending on what state your repository is in, this buffer may contain sections titled “Staged changes”, “Unstaged changes”, “Unmerged into origin/master”, “Unpushed to origin/master”, and many others.

Since we are starting from a safe state, which you can easily return to (by doing a git reset --hard PRE-MAGIT-STATE), there currently are not staged or unstaged changes. Edit some files and save the changes. Then go back to the status buffer, while at the same time refreshing it, by typing C-x g. (When the status buffer, or any Magit buffer for that matter, is the current buffer, then you can also use just g to refresh it).

Move between sections using p and n. Note that the bodies of some sections are hidden. Type TAB to expand or collapse the section at point. You can also use C-tab to cycle the visibility of the current section and its children. Move to a file section inside the section named “Unstaged changes” and type s to stage the changes you have made to that file. That file now appears under “Staged changes”.

Magit can stage and unstage individual hunks, not just complete files. Move to the file you have just staged, expand it using TAB, move to one of the hunks using n, and unstage just that by typing u. Note how the staging (s) and unstaging (u) commands operate on the change at point. Many other commands behave the same way.

You can also un-/stage just part of a hunk. Inside the body of a hunk section (move there using C-n), set the mark using C-SPC and move down until some added and/or removed lines fall inside the region but not all of them. Again type s to stage.

It is also possible to un-/stage multiple files at once. Move to a file section, type C-SPC, move to the next file using n, and then s to stage both files. Note that both the mark and point have to be on the headings of sibling sections for this to work. If the region looks like it does in other buffers, then it doesn’t select Magit sections that can be acted on as a unit.

And then of course you want to commit your changes. Type c. This shows the available commit commands and arguments in a buffer at the bottom of the frame. Each command and argument is prefixed with the key that invokes/sets it. Do not worry about this for now. We want to create a “normal” commit, which is done by typing c again.

Now two new buffers appear. One is for writing the commit message, the other shows a diff with the changes that you are about to committed. Write a message and then type C-c C-c to actually create the commit.

You probably don’t want to push the commit you just created because you just committed some random changes, but if that is not the case you could push it by typing P to show all the available push commands and arguments and then p to push to a branch with the same name as the local branch onto the remote configured as the push-remote. (If the push-remote is not configured yet, then you would first be prompted for the remote to push to.)

So far we have mentioned the commit, push, and log transient prefix commands. These are probably among the transients you will be using the most, but many others exist. To show a transient that lists all other transients (as well as the various apply commands and some other essential commands), type h. Try a few.

The key bindings in that transient correspond to the bindings in Magit buffers, including but not limited to the status buffer. So you could type h d to bring up the diff transient, but once you remember that “d” stands for “diff”, you would usually do so by just typing d. But this “prefix of prefixes” is useful even once you have memorized all the bindings, as it can provide easy access to Magit commands from non-Magit buffers. You should create a global key binding for this command too:

1
(global-set-key (kbd "C-x M-g") 'magit-dispatch)

In the same vein, you might also want to enable global-magit-file-mode to get some more Magit key bindings in regular file-visiting buffers (see Minor Mode for Buffers Visiting Files).

It is not necessary that you do so now, but if you stick with Magit, then it is highly recommended that you read the next section too.


Next: Interface Concepts, Previous: Installation, Up: Top [Contents][Index]

4 Interface Concepts

• Modes and Buffers:
• Sections:
• Transient Commands:
• Completion, Confirmation and the Selection:
• Running Git:

4.1 Modes and Buffers

Magit provides several major-modes. For each of these modes there usually exists only one buffer per repository. Separate modes and thus buffers exist for commits, diffs, logs, and some other things.

Besides these special purpose buffers, there also exists an overview buffer, called the status buffer. It’s usually from this buffer that the user invokes Git commands, or creates or visits other buffers.

In this manual we often speak about “Magit buffers”. By that we mean buffers whose major-modes derive from magit-mode.

  • M-x magit-toggle-buffer-lock (magit-toggle-buffer-lock)

    This command locks the current buffer to its value or if the buffer is already locked, then it unlocks it.Locking a buffer to its value prevents it from being reused to display another value. The name of a locked buffer contains its value, which allows telling it apart from other locked buffers and the unlocked buffer.Not all Magit buffers can be locked to their values; for example, it wouldn’t make sense to lock a status buffer.There can only be a single unlocked buffer using a certain major-mode per repository. So when a buffer is being unlocked and another unlocked buffer already exists for that mode and repository, then the former buffer is instead deleted and the latter is displayed in its place.

• Switching Buffers:
• Naming Buffers:
• Quitting Windows:
• Automatic Refreshing of Magit Buffers:
• Automatic Saving of File-Visiting Buffers:
• Automatic Reverting of File-Visiting Buffers:

4.2 Sections

Magit buffers are organized into nested sections, which can be collapsed and expanded, similar to how sections are handled in Org mode. Each section also has a type, and some sections also have a value. For each section type there can also be a local keymap, shared by all sections of that type.

Taking advantage of the section value and type, many commands operate on the current section, or when the region is active and selects sections of the same type, all of the selected sections. Commands that only make sense for a particular section type (as opposed to just behaving differently depending on the type) are usually bound in section type keymaps.

• Section Movement:
• Section Visibility:
• Section Hooks:
• Section Types and Values:
• Section Options:

4.3 Transient Commands

Many Magit commands are implemented as transient commands. First the user invokes a prefix command, which causes its infix arguments and suffix commands to be displayed in the echo area. The user then optionally sets some infix arguments and finally invokes one of the suffix commands.

This is implemented in the library transient. Earlier Magit releases used the package magit-popup and even earlier versions library magit-key-mode.

Transient is documented in (transient)Top.

  • C-c C-c (magit-dispatch)

    This transient prefix command binds most of Magit’s other prefix commands as suffix commands and displays them in a temporary buffer until one of them is invoked. Invoking such a sub-prefix causes the suffixes of that command to be bound and displayed instead of those of magit-dispatch.

This command is also, or especially, useful outside Magit buffers, so you should setup a global binding:

1
(global-set-key (kbd "C-x M-g") 'magit-dispatch)

Transient commands remember the used arguments for subsequent invocations. Two transients, the log and diff transients (see Logging and Diffing), may behave a bit differently, depending on the value of magit-use-sticky-arguments.

  • User Option: magit-use-sticky-arguments

    This option controls how the diff and log transients reuse arguments from existing buffers.When t (the default value), then the log or diff transients reuses the arguments from the current repository’s log or diff buffer, respectively. When no log or diff buffer exists for the current repository, these transients use the default value of magit-log-arguments or magit-diff-arguments.When current, log and diff transients will only reuse the arguments if the current buffer is derived from magit-log-mode or magit-diff-mode, respectively.When nil, the default value of magit-log-arguments or magit-diff-arguments is always used.


4.4 Completion, Confirmation and the Selection

• Action Confirmation:
• Completion and Confirmation:
• The Selection:
• The hunk-internal region:
• Support for Completion Frameworks:
• Additional Completion Options:

4.5 Running Git

• Viewing Git Output:
• Git Process Status:
• Running Git Manually:
• Git Executable:
• Global Git Arguments:

4.5.1 Viewing Git Output

Magit runs Git either for side-effects (e.g. when pushing) or to get some value (e.g. the name of the current branch).

When Git is run for side-effects, the process output is logged in a per-repository log buffer, which can be consulted using the magit-process command when things don’t go as expected.

The output/errors for up to ‘magit-process-log-max’ Git commands are retained.

  • $ (magit-process)

    This commands displays the process buffer for the current repository.

Inside that buffer, the usual key bindings for navigating and showing sections are available. There is one additional command.

  • k (magit-process-kill)

    This command kills the process represented by the section at point.

  • User Option: magit-git-debug

    When this is non-nil then the output of all calls to git are logged in the process buffer. This is useful when debugging, otherwise it just negatively affects performance.

5 Inspecting

The functionality provided by Magit can be roughly divided into three groups:

inspecting existing data,
manipulating existing data or adding new data,
transferring data. (划分的好.)

Of course that is a rather crude distinction that often falls short, but it’s more useful than no distinction at all. This section is concerned with inspecting data, the next two with manipulating and transferring it. Then follows a section about miscellaneous functionality, which cannot easily be fit into this distinction.

Of course other distinctions make sense too, e.g. Git’s distinction between porcelain and plumbing commands, which for the most part is equivalent to Emacs’ distinction between interactive commands and non-interactive functions. All of the sections mentioned before are mainly concerned with the porcelain – Magit’s plumbing layer is described later.

• Status Buffer:
• Repository List:
• Logging:
• Diffing:
• Ediffing:
• References Buffer:
• Bisecting:
• Visiting Blobs:
• Blaming:

5.1 Status Buffer

While other Magit buffers contain e.g. one particular diff or one particular log, the status buffer contains the diffs for staged and unstaged changes, logs for unpushed and unpulled commits, lists of stashes and untracked files, and information related to the current branch.

During certain incomplete operations – for example when a merge resulted in a conflict – additional information is displayed that helps proceeding with or aborting the operation.

The command magit-status displays the status buffer belonging to the current repository in another window. This command is used so often that it should be bound globally. We recommend using C-x g:

1
(global-set-key (kbd "C-x g") 'magit-status)
  • C-x g (magit-status)

    When invoked from within an existing Git repository, then this command shows the status of that repository in a buffer.If the current directory isn’t located within a Git repository, then this command prompts for an existing repository or an arbitrary directory, depending on the option magit-repository-directories, and the status for the selected repository is shown instead.If that option specifies any existing repositories, then the user is asked to select one of them.Otherwise the user is asked to select an arbitrary directory using regular file-name completion. If the selected directory is the top-level directory of an existing working tree, then the status buffer for that is shown.Otherwise the user is offered to initialize the selected directory as a new repository. After creating the repository its status buffer is shown.These fallback behaviors can also be forced using one or more prefix arguments:With two prefix arguments (or more precisely a numeric prefix value of 16 or greater) an arbitrary directory is read, which is then acted on as described above. The same could be accomplished using the command magit-init.With a single prefix argument an existing repository is read from the user, or if no repository can be found based on the value of magit-repository-directories, then the behavior is the same as with two prefix arguments.

  • User Option: magit-repository-directories

    List of directories that are Git repositories or contain Git repositories.Each element has the form (DIRECTORY . DEPTH). DIRECTORY has to be a directory or a directory file-name, a string. DEPTH, an integer, specifies the maximum depth to look for Git repositories. If it is 0, then only add DIRECTORY itself.This option controls which repositories are being listed by magit-list-repositories. It also affects magit-status (which see) in potentially surprising ways (see above).

  • Command: ido-enter-magit-status

    From an Ido prompt used to open a file, instead drop into magit-status. This is similar to ido-magic-delete-char, which, despite its name, usually causes a Dired buffer to be created.To make this command available, use something like:(add-hook 'ido-setup-hook (lambda () (define-key ido-completion-map (kbd \"C-x g\") 'ido-enter-magit-status)))Starting with Emacs 25.1 the Ido keymaps are defined just once instead of every time Ido is invoked, so now you can modify it like pretty much every other keymap:(define-key ido-common-completion-map (kbd \"C-x g\") 'ido-enter-magit-status)

• Status Sections:
• Status Header Sections:
• Status Module Sections:
• Status Options:

6 Manipulating

• Repository Setup:
• Staging and Unstaging:
• Applying:
• Committing:
• Branching:
• Merging:
• Resolving Conflicts:
• Rebasing:
• Cherry Picking:
• Resetting:
• Stashing:

7 Transferring

• Remotes:
• Fetching:
• Pulling:
• Pushing:
• Plain Patches:
• Maildir Patches:

8 Miscellaneous

• Tagging:
• Notes:
• Submodules:
• Subtree:
• Worktree:
• Common Commands:
• Wip Modes:
• Minor Mode for Buffers Visiting Files:
• Minor Mode for Buffers Visiting Blobs:

9 Customizing

Both Git and Emacs are highly customizable. Magit is both a Git porcelain as well as an Emacs package, so it makes sense to customize it using both Git variables as well as Emacs options. However this flexibility doesn’t come without problems, including but not limited to the following.

  • Some Git variables automatically have an effect in Magit without requiring any explicit support. Sometimes that is desirable - in other cases, it breaks Magit.

    When a certain Git setting breaks Magit but you want to keep using that setting on the command line, then that can be accomplished by overriding the value for Magit only by appending something like ("-c" "some.variable=compatible-value") to magit-git-global-arguments.

  • Certain settings like fetch.prune=true are respected by Magit commands (because they simply call the respective Git command) but their value is not reflected in the respective transient buffers. In this case the --prune argument in magit-fetch might be active or inactive, but that doesn’t keep the Git variable from being honored by the suffix commands anyway. So pruning might happen despite the --prune arguments being displayed in a way that seems to indicate that no pruning will happen.

I intend to address these and similar issues in a future release.

• Per-Repository Configuration:
• Essential Settings:

10 Plumbing

The following sections describe how to use several of Magit’s core abstractions to extend Magit itself or implement a separate extension.

A few of the low-level features used by Magit have been factored out into separate libraries/packages, so that they can be used by other packages, without having to depend on Magit. See (with-editor)Top for information about with-editor. transient doesn’t have a manual yet.

If you are trying to find an unused key that you can bind to a command provided by your own Magit extension, then checkout https://github.com/magit/magit/wiki/Plugin-Dispatch-Key-Registry.

• Calling Git:
• Section Plumbing:
• Refreshing Buffers:
• Conventions:

Appendix A FAQ

The next two nodes lists frequently asked questions. For a list of frequently and recentlyasked questions, i.e. questions that haven’t made it into the manual yet, seehttps://github.com/magit/magit/wiki/FAQ.

Please also use the Debugging Tools.

• FAQ - How to …?:
• FAQ - Issues and Errors:

github workflow

Posted on 2019-05-25 | In management | Comments:

准备工作

  1. 打开git bash,切换到桌面
  2. 新建 problems.doc 的Word文档 (用于记录操作过程中的问题,可以截图)
  3. 打开problems.doc文件(格式如下图左侧所示^_^)
1
2
3
cd ~/desktop #打开桌面
touch problems.doc #新建 Word文档
start problems.doc #打开文档.

0.prepare

  1. Fork English文件夹:(以我新注册账户doufukuai为例)

    doufukai(someone全拼)是新注册的账户,这里代表你,要用你的名字和账户替代.

    账户M-DFK(someone的首字母)代表我的账户.

    start www.github.com 打开GitHub网页

    (推荐使用Chrome浏览器)

    ​

    2) 从M-DFK账户fork,English库

    start https://github.com/M-DFK/English

    refork

初次作业流程

  1. 回到你的GitHub账户中的English库中,

    (备注, 账户doufukuai代表你的账户, M-DFK代表我的账户)

  2. 复制 库的地址.

    copy git link

  3. 在git bash中,使用git clone命令,可以将所有文件下载到本地.

    1
    2
    3
    4
    5
    6
    #切换到桌面
    cd ~/desktop
    git clone git@github.com:doufukuai/English.git
    #git clone 后面跟着的是你的地址,比如
    #@melody真的操作.
    #git clone https://github.com/liuzhen11/English.git

    'git@github.com:doufukuai/English.git’ 是刚才复制的地址.

    git clone

  4. 进入下载到桌面上的English文件,打开你的的文档 @someone.md 开始写作业.

    1
    2
    3
    4
    5
    #切换到english目录下
    cd english
    #打开你的作业文件,可以手动到english文件内打开,或者用下面的命令打开.
    start @someone.md
    #这里替换成你的文件, 比如 start @melody真

    homework

  5. 写完作业且保存后,使用git add命令将作业添加到staging 区,这一步看起来繁琐,却很有用.

    1
    2
    git add @someone.md 
    # git add @melody真.md
  6. 再将作业commit到Master分支

    1
    2
    git commit -m '@someone 2018-3-7'
    #git commit -m '@melody 2018-03-16'

    ​

    m是message的缩写,-前面的这个连接线不要漏掉.

    message的内容是 名字 + 日期 ‘@someone 2018-3-7’

  7. 将更新的作业推送到someone的GitHub网页账户上.(也称为origin分支)

    1
    git push origin master

    这条命令的意思是 push (someone更新的内容) to origin branch from master branch

    origin

  8. 完成,去网页里查看一下是否有变化.

    update

  9. 用git remote命令,将M-DFK的库与本地库相关联.(也称为upstream分支)

    1
    2
    git remote add upstream https://github.com/M-DFK/English.git
    #这里不做任何更改,照搬复制.

    不更改,整行复制,’https://github.com/M-DFK/English.git'是M-DFK的Enlish库.

    add upstream

  10. 检查是否添加成功

    git remote -v
    

    confirm remote

日常工作流程

以上是初始设置的流程, 以后不需要从重复上述操作.

下面是你每日交作业的标准流程.

  1. 写作业前:(将M-DFK库的最近更新下载到本地)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 1.切换到english文件夹下.
cd ~/desktop/english #切换到enligh文件夹下.

#如果换了一台设置好SSH的新电脑,不需要重复初次工作流程的步骤.
#先输入下面的命令, (初次工作流程的第九步)
#如果没有换新电脑,略过这一步.
git remote add upstream https://github.com/M-DFK/English.git

# 2. 写作业前:(将M-DFK库的最近更新下载到本地)
git fetch upstream #获取远程更新到本地
git merge upstream/master #与本地内容合并.
# 3. 打开你的文件写作业.
start @someone.md #打开@someone.md这个文件, 开始写作业.

# 4.写完作业后的操作
git add @someone.md
git commit -m '@someone2018-3-7'
git push origin master
#如果报错,输入以下命令,强制更新.
git push -f origin master
# f 是force 强制
# 4.最后一步, pull request
# 到你的github的english库中发起pull request

daily_work

  1. 关键的一步Pull Request, 登录你的GitHub账户,

    1 ) 新建 pull request

pull request

2) 填写内容后创建.

pr content

​ 3) 点击创建后,出现的界面

success

记录问题

不要忘记,创建的Word文件,用来记录问题, 和收集错误的截图.

最好能先百度找找, 将搜到的内容也存到里面.

命令行练习

practice

推荐资料:

1) 中文资料 Git教程 - 廖雪峰的官方网站

2) 英文资料:Working with forks - User Documentation

阅读资料过程中遇到的问题,也请放到problems.doc中.

Github同步设置

Posted on 2019-05-25 | In management - versionControl | Comments:

零, 下载和安装git for windows

原网址下载比较慢, 这是百度盘下载链接.https://pan.baidu.com/s/1uei5UkY21Ez4YDTlxWh9Gg

安装的时候一直点下一步,

安装成功后,桌面上会出现一个Git Bash的图标快捷键.

打开后,进入下一步操作.

imgi

一, 设置用户名和邮箱

首先注册一个github账户.

https://github.com/

官方指导:First time set up

以我新注册的新账户, 这里代表你,用你的账户替代yourname.
用户名: yourname
邮箱: someone@gmail.com为例.

  1. 分别复制输入命令, $这个符号不要复制,每复制一行回车.(以下相同), 用你的github账户的用户名和邮箱替代yourname的.
1
2
$ git config --global user.name "yourname"
$ git config --global user.email someone@gmail.com

  1. 核实下是否设置成功

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    $ git config user.name
    #如果反馈出 yourname,就是设置成功!
    $ git config user.email
    #会显示 someone@gmail.com

    gaowei@alpha:~/Documents/English/EnglishGit/01.GitCollection$ git config --list
    user.name=M-DFK
    user.email=gcpu.whisper@gmail.com
    core.repositoryformatversion=0
    core.filemode=true
    core.bare=false
    core.logallrefupdates=true
    core.ignorecase=true
    core.precomposeunicode=false
    remote.origin.url=https://github.com/M-DFK/English.git
    remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
    branch.master.remote=origin
    branch.master.merge=refs/heads/master

二,设置SSH, 连接Github

官方指导:Connect to Github

1. Generating a new SSH key

以下按照步骤复制黏贴到git bash中.

  1. Paste the text below, substituting in your GitHub email address.

    1
    $ ssh-keygen -t rsa -b 4096 -C "someone@gmail.com"
  2. save the SSH key

    1
    Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]

    [Press enter] 是按回车,不要输入任何内容,只按回车键.

  3. At the prompt, type a secure passphrase. For more information, see “Working with SSH key passphrases”.(设置密码,输入任意密码)

    1
    2
    Enter passphrase (empty for no passphrase): [Type a passphrase]
    Enter same passphrase again: [Type passphrase again]

    下面的图片,设置密码的时候,我两次输入的不一致,提示让我重新又设置了一遍.
    密码可以随意设置,在自己能记住的前提下.

    ssh_key

2. Adding your SSH key to the ssh-agent

  1. Run ssh-agent

    1
    eval $(ssh-agent -s)
  2. Add your SSH private key to the ssh-agent.

    1
    ssh-add ~/.ssh/id_rsa

三, 添加SSH key到Gibhub账户

官方指导

  1. 复制SSH key

    1
    2
    3
    4
    5
    6
    7
    8
    9
    cat ~/.ssh/id_rsa.pub 
    less ~/.ssh/id_rsa.pub
    #回车后,复制以下图片中的内容,'ssh开始,@gmail.com结束'的全部内容.
    #可以右键点复制,也可以用快捷键 Ctrl + Ins (注意不是快捷键 Ctrl + C)

    sudo apt-get install xclip
    # Downloads and installs xclip. If you don't have `apt-get`, you might need to use another installer (like `yum`)
    xclip -sel clip < ~/.ssh/id_rsa.pub
    # Copies the contents of the id_rsa.pub file to your clipboard

  2. 在网页中打开Github账户,进入设置(setting 选型)

  3. 进入

    ​

  4. 点 新建SSH Key

  5. 在空白框中黏贴刚才复制的内容,标题可以命名为日期

  6. 单击添加

  7. 网站会要求重新登录.

  8. 查看设置成功

Book-Shell Scripts

Posted on 2019-05-25 | In linux | Comments:

Shell Script

1. The Linux Command Line
倒着的Tree结构.
命令层:
上层
part1-23 part1-47 part1-85
树形结构的底部 part1-135 part1-161 part1-187 从底部的Filetree开始.
Additional info part1-211 part1-233
birdview the shell part1-3 part1-113 Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 513.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 659.pdf
2. Programming
programming Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 305.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 485.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 333.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 367.pdf
I/O Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 401.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 431.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 455.pdf
3. Advanced Shell Scripting
Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 571.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 541.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 597.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 627.pdf
4. Part VI Creating Practival Scripts
lRichard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 681.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 717.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 745.pdf
Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 775.pdf Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015 page 787.pdf

Emacs' Official Manual

Posted on 2019-05-23 | In linux - emacs | Comments:

0.Introduction

You are reading about GNU Emacs, the GNU incarnation of the advanced, self-documenting, customizable, extensible editor Emacs. (The ‘G’ in GNU (GNU’s Not Unix) is not silent.)

We call Emacs advanced because it can do much more than simple insertion and deletion of text. It can control subprocesses, indent programs automatically, show multiple files at once, and more. Emacs editing commands operate in terms of characters, words, lines, sentences, paragraphs, and pages, as well as expressions and comments in various programming languages.

Self-documenting means that at any time you can use special commands, known as help commands, to find out what your options are, or to find out what any command does, or to find all the commands that pertain to a given topic. See Help.

Customizable means that you can easily alter the behavior of Emacs commands in simple ways. For instance, if you use a programming language in which comments start with ‘<’ and end with ‘>’, you can tell the Emacs comment manipulation commands to use those strings (see Comments). To take another example, you can rebind the basic cursor motion commands (up, down, left and right) to any keys on the keyboard that you find comfortable. See Customization.

Extensible means that you can go beyond simple customization and create entirely new commands. New commands are simply programs written in the Lisp language, which are run by Emacs’s own Lisp interpreter. Existing commands can even be redefined in the middle of an editing session, without having to restart Emacs. Most of the editing commands in Emacs are written in Lisp; the few exceptions could have been written in Lisp but use C instead for efficiency. Writing an extension is programming, but non-programmers can use it afterwards. See Emacs Lisp Intro, if you want to learn Emacs Lisp programming.

1 The Organization of the Screen

On a graphical display, such as on GNU/Linux using the X Window System, Emacs occupies a graphical window. On a text terminal, Emacs occupies the entire terminal screen. We will use the term frame to mean a graphical window or terminal screen occupied by Emacs. Emacs behaves very similarly on both kinds of frames. It normally starts out with just one frame, but you can create additional frames if you wish (see Frames).

Each frame consists of several distinct regions. At the top of the frame is a menu bar, which allows you to access commands via a series of menus. On a graphical display, directly below the menu bar is a tool bar, a row of icons that perform editing commands when you click on them. At the very bottom of the frame is an echo area, where informative messages are displayed and where you enter information when Emacs asks for it.

The main area of the frame, below the tool bar (if one exists) and above the echo area, is called the window. Henceforth in this manual, we will use the word “window” in this sense. Graphical display systems commonly use the word “window” with a different meaning; but, as stated above, we refer to those graphical windows as “frames”.

An Emacs window is where the buffer—the text or other graphics you are editing or viewing—is displayed. On a graphical display, the window possesses a scroll bar on one side, which can be used to scroll through the buffer. The last line of the window is a mode line. This displays various information about what is going on in the buffer, such as whether there are unsaved changes, the editing modes that are in use, the current line number, and so forth.

When you start Emacs, there is normally only one window in the frame. However, you can subdivide this window horizontally or vertically to create multiple windows, each of which can independently display a buffer (see Windows).

At any time, one window is the selected window. On a graphical display, the selected window shows a more prominent cursor (usually solid and blinking); other windows show a less prominent cursor (usually a hollow box). On a text terminal, there is only one cursor, which is shown in the selected window. The buffer displayed in the selected window is called the current buffer, and it is where editing happens. Most Emacs commands implicitly apply to the current buffer; the text displayed in unselected windows is mostly visible for reference. If you use multiple frames on a graphical display, selecting a particular frame selects a window in that frame.

  • Point: The place in the text where editing commands operate.
  • Echo Area: Short messages appear at the bottom of the screen.
  • Mode Line: Interpreting the mode line.
  • Menu Bar: How to use the menu bar.

2 Kinds of User Input

GNU Emacs is primarily designed for use with the keyboard. While it is possible to use the mouse to issue editing commands through the menu bar and tool bar, that is not as efficient as using the keyboard. Therefore, this manual mainly documents how to edit with the keyboard.

Keyboard input into Emacs is based on a heavily-extended version of ASCII.

  • Simple characters, like ‘a’, ‘B’, ‘3’, ‘=’, and the space character (denoted as ), are entered by typing the corresponding key.
  • Control characters, such as , , , , , , and , are also entered this way, as are certain characters found on non-English keyboards (see International).
  • Emacs also recognizes control characters that are entered using modifier keys. Two commonly-used modifier keys are (usually labeled ), and (usually labeled )1. For example, Control-a is entered by holding down the key while pressing a; we will refer to this as C-a for short. Similarly, -a, or M-a for short, is entered by holding down the key and pressing a. Modifier keys can also be applied to non-alphanumerical characters, e.g., C- or M-.

分类清晰, User Input, 从这里设置键盘一类别,
1) Simple 2) Control 3) Modifier

You can also type Meta characters using two-character sequences starting with . Thus, you can enter M-a by typing a. You can enter C-M-a (holding down both and , then pressing a) by typing C-a. Unlike , is entered as a separate character. You don’t hold down while typing the next character; instead, press and release it, then enter the next character. This feature is useful on certain text terminals where the key does not function reliably.

On graphical displays, the window manager might block some keyboard inputs, including M-, M-, C-M-d and C-M-l. If you have this problem, you can either customize your window manager to not block those keys, or rebind the affected Emacs commands (see Customization).

Simple characters and control characters, as well as certain non-keyboard inputs such as mouse clicks, are collectively referred to as input events. For details about how Emacs internally handles input events, see Input Events.


3 Keys

Some Emacs commands are invoked by just one input event; for example, C-f moves forward one character in the buffer. Other commands take two or more input events to invoke, such as C-x C-f and C-x 4 C-f.

A key sequence, or key for short, is a sequence of one or more input events that is meaningful as a unit. If a key sequence invokes a command, we call it a complete key; for example,C-f, C-x C-f and C-x 4 C-f are all complete keys. If a key sequence isn’t long enough to invoke a command, we call it a prefix key; from the preceding example, we see that C-x and C-x 4 are prefix keys. Every key sequence is either a complete key or a prefix key.

A prefix key combines with the following input event to make a longer key sequence. For example, C-x is a prefix key, so typing C-x alone does not invoke a command; instead, Emacs waits for further input (if you pause for longer than a second, it echoes the C-x key to prompt for that input; see Echo Area). C-x combines with the next input event to make a two-event key sequence, which could itself be a prefix key (such as C-x 4), or a complete key (such as C-x C-f). There is no limit to the length of key sequences, but in practice they are seldom longer than three or four input events.

You can’t add input events onto a complete key. For example, because C-f is a complete key, the two-event sequence C-f C-k is two key sequences, not one.

By default, the prefix keys in Emacs are C-c, C-h, C-x, C-x , C-x @, C-x a, C-x n, C-x r, C-x v, C-x 4, C-x 5, C-x 6, , M-g, and M-o. ( and are aliases for C-h and C-x 6.) This list is not cast in stone; if you customize Emacs, you can make new prefix keys. You could even eliminate some of the standard ones, though this is not recommended for most users; for example, if you remove the prefix definition of C-x 4, then C-x 4 C-f becomes an invalid key sequence. See Key Bindings.

Typing the help character (C-h or ) after a prefix key displays a list of the commands starting with that prefix. The sole exception to this rule is : C-h is equivalent to C-M-h, which does something else entirely. You can, however, use to display a list of commands starting with .

4 Keys and Commands

This manual is full of passages that tell you what particular keys do. But Emacs does not assign meanings to keys directly. Instead, Emacs assigns meanings to named commands, and then gives keys their meanings by binding them to commands.

Every command has a name chosen by a programmer. The name is usually made of a few English words separated by dashes; for example, next-line or forward-word. Internally, each command is a special type of Lisp function, and the actions associated with the command are performed by running the function. See What Is a Function.

The bindings between keys and commands are recorded in tables called keymaps. See Keymaps.

When we say that “C-n moves down vertically one line” we are glossing over a subtle distinction that is irrelevant in ordinary use, but vital for Emacs customization. The command next-line does a vertical move downward. C-n has this effect because it is bound to next-line. If you rebind C-n to the command forward-word, C-n will move forward one word instead.

In this manual, we will often speak of keys like C-n as commands, even though strictly speaking the key is bound to a command. Usually, we state the name of the command which really does the work in parentheses after mentioning the key that runs it. For example, we will say that “The command C-n (next-line) moves point vertically down”, meaning that the command next-line moves vertically down, and the key C-n is normally bound to it.

Since we are discussing customization, we should tell you about variables. Often the description of a command will say, “To change this, set the variable mumble-foo.” A variable is a name used to store a value. Most of the variables documented in this manual are meant for customization: some command or other part of Emacs examines the variable and behaves differently according to the value that you set. You can ignore the information about variables until you are interested in customizing them. Then read the basic information on variables (see Variables) and the information about specific variables will make sense.

5 Entering Emacs

The usual way to invoke Emacs is with the shell command emacs. From a terminal window running a Unix shell on a GUI terminal, you can run Emacs in the background with emacs &; this way, Emacs won’t tie up the terminal window, so you can use it to run other shell commands. (For comparable methods of starting Emacs on MS-Windows, see Windows Startup.)

When Emacs starts up, the initial frame displays a special buffer named ‘GNU Emacs’. This startup screen contains information about Emacs and links to common tasks that are useful for beginning users. For instance, activating the ‘Emacs Tutorial’ link opens the Emacs tutorial; this does the same thing as the command C-h t (help-with-tutorial). To activate a link, either move point onto it and type , or click on it with mouse-1 (the left mouse button).

Using a command line argument, you can tell Emacs to visit one or more files as soon as it starts up. For example, emacs foo.txt starts Emacs with a buffer displaying the contents of the file ‘foo.txt’. This feature exists mainly for compatibility with other editors, which are designed to be launched from the shell for short editing sessions. If you call Emacs this way, the initial frame is split into two windows—one showing the specified file, and the other showing the startup screen. See Windows.

Generally, it is unnecessary and wasteful to start Emacs afresh each time you want to edit a file. The recommended way to use Emacs is to start it just once, just after you log in, and do all your editing in the same Emacs session. See Files, for information on visiting more than one file. If you use Emacs this way, the Emacs session accumulates valuable context, such as the kill ring, registers, undo history, and mark ring data, which together make editing more convenient. These features are described later in the manual.

To edit a file from another program while Emacs is running, you can use the emacsclient helper program to open a file in the existing Emacs session. See Emacs Server.

Emacs accepts other command line arguments that tell it to load certain Lisp files, where to put the initial frame, and so forth. See Emacs Invocation.

If the variable inhibit-startup-screen is non-nil, Emacs does not display the startup screen. In that case, if one or more files were specified on the command line, Emacs simply displays those files; otherwise, it displays a buffer named scratch, which can be used to evaluate Emacs Lisp expressions interactively. See Lisp Interaction. You can set the variable inhibit-startup-screen using the Customize facility (see Easy Customization), or by editing your initialization file (see Init File).1

You can also force Emacs to display a file or directory at startup by setting the variable initial-buffer-choice to a string naming that file or directory. The value of initial-buffer-choice may also be a function (of no arguments) that should return a buffer which is then displayed. If initial-buffer-choice is non-nil, then if you specify any files on the command line, Emacs still visits them, but does not display them initially.


6 Exiting Emacs

  • C-x C-c

    Kill Emacs (save-buffers-kill-terminal).

  • C-z

    On a text terminal, suspend Emacs; on a graphical display, iconify (or “minimize”) the selected frame (suspend-frame).

Killing Emacs means terminating the Emacs program. To do this, type C-x C-c (save-buffers-kill-terminal). A two-character key sequence is used to make it harder to type by accident. If there are any modified file-visiting buffers when you type C-x C-c, Emacs first offers to save these buffers. If you do not save them all, it asks for confirmation again, since the unsaved changes will be lost. Emacs also asks for confirmation if any subprocesses are still running, since killing Emacs will also kill the subprocesses (see Shell).

C-x C-c behaves specially if you are using Emacs as a server. If you type it from a client frame, it closes the client connection. See Emacs Server.

Emacs can, optionally, record certain session information when you kill it, such as the files you were visiting at the time. This information is then available the next time you start Emacs. See Saving Emacs Sessions.

If the value of the variable confirm-kill-emacs is non-nil, C-x C-c assumes that its value is a predicate function, and calls that function. If the result of the function call is non-nil, the session is killed, otherwise Emacs continues to run. One convenient function to use as the value of confirm-kill-emacs is the function yes-or-no-p. The default value of confirm-kill-emacs is nil.

If the value of the variable confirm-kill-processes is nil, C-x C-c does not ask for confirmation before killing subprocesses started by Emacs. The value is t by default.

To further customize what happens when Emacs is exiting, see Killing Emacs.

To kill Emacs without being prompted about saving, type M-x kill-emacs.

C-z runs the command suspend-frame. On a graphical display, this command minimizes (or iconifies) the selected Emacs frame, hiding it in a way that lets you bring it back later (exactly how this hiding occurs depends on the window system). On a text terminal, the C-z command suspends Emacs, stopping the program temporarily and returning control to the parent process (usually a shell); in most shells, you can resume Emacs after suspending it with the shell command %emacs.

Text terminals usually listen for certain special characters whose meaning is to kill or suspend the program you are running. This terminal feature is turned off while you are in Emacs. The meanings of C-z and C-x C-c as keys in Emacs were inspired by the use of C-z and C-c on several operating systems as the characters for stopping or killing a program, but that is their only relationship with the operating system. You can customize these keys to run any commands of your choice (see Keymaps).

7 Basic Editing Commands

Here we explain the basics of how to enter text, make corrections, and save the text in a file. If this material is new to you, we suggest you first run the Emacs learn-by-doing tutorial, by typing C-h t (help-with-tutorial).

  • Inserting Text: Inserting text by simply typing it.
  • Moving Point: Moving the cursor to the place where you want to change something.
  • Erasing: Deleting and killing text.
  • Basic Undo: Undoing recent changes in the text.
  • Files: Visiting, creating, and saving files.
  • Help: Asking what a character does.
  • Blank Lines: Making and deleting blank lines.
  • Continuation Lines: How Emacs displays lines too wide for the screen.
  • Position Info: What line, row, or column is point on?
  • Arguments: Numeric arguments for repeating a command N times.
  • Repeating: Repeating the previous command quickly.

basic editing, 重要的基本概念.
pointer moving,

8 The Minibuffer

The minibuffer is where Emacs commands read complicated arguments, such as file names, buffer names, Emacs command names, or Lisp expressions. We call it the “minibuffer” because it’s a special-purpose buffer with a small amount of screen space. You can use the usual Emacs editing commands in the minibuffer to edit the argument text.

  • Basic Minibuffer: Basic usage of the minibuffer.
  • Minibuffer File: Entering file names with the minibuffer.
  • Minibuffer Edit: How to edit in the minibuffer.
  • Completion: An abbreviation facility for minibuffer input.
  • Minibuffer History: Reusing recent minibuffer arguments.
  • Repetition: Re-executing commands that used the minibuffer.
  • Passwords: Entering passwords in the echo area.
  • Yes or No Prompts: Replying yes or no in the echo area.

9 Running Commands by Name

Every Emacs command has a name that you can use to run it. For convenience, many commands also have key bindings. You can run those commands by typing the keys, or run them by name. Most Emacs commands have no key bindings, so the only way to run them is by name. (See Key Bindings, for how to set up key bindings.)

By convention, a command name consists of one or more words, separated by hyphens; for example, auto-fill-mode or manual-entry. Command names mostly use complete English words to make them easier to remember.

To run a command by name, start with M-x, type the command name, then terminate it with . M-x uses the minibuffer to read the command name. The string ‘M-x’ appears at the beginning of the minibuffer as a prompt to remind you to enter a command name to be run. exits the minibuffer and runs the command. See Minibuffer, for more information on the minibuffer.

You can use completion to enter the command name. For example, to invoke the command forward-char, you can type

1
M-x forward-char <RET>

or

1
M-x forw <TAB> c <RET>

Note that forward-char is the same command that you invoke with the key C-f. The existence of a key binding does not stop you from running the command by name.

When M-x completes on commands, it ignores the commands that are declared obsolete; for these, you will have to type their full name. Obsolete commands are those for which newer, better alternatives exist, and which are slated for removal in some future Emacs release.

To cancel the M-x and not run a command, type C-g instead of entering the command name. This takes you back to command level.

To pass a numeric argument to the command you are invoking with M-x, specify the numeric argument before M-x. The argument value appears in the prompt while the command name is being read, and finally M-x passes the argument to that command. For example, to pass the numeric argument of 42 to the command forward-char you can type C-u 42 M-x forward-char .

When the command you run with M-x has a key binding, Emacs mentions this in the echo area after running the command. For example, if you type M-x forward-word, the message says that you can run the same command by typing M-f. You can turn off these messages by setting the variable suggest-key-bindings to nil. The value of suggest-key-bindingscan also be a number, in which case Emacs will show the binding for that many seconds before removing it from display. The default behavior is to display the binding for 2 seconds.

Commands that don’t have key bindings, can still be invoked after typing less than their full name at the ‘M-x’ prompt. Emacs mentions such shorthands in the echo area if they are significantly shorter than the full command name, and extended-command-suggest-shorter is non-nil. The setting of suggest-key-bindings affects these hints as well.

In this manual, when we speak of running a command by name, we often omit the that terminates the name. Thus we might say M-x auto-fill-mode rather than M-x auto-fill-mode . We mention the only for emphasis, such as when the command is followed by arguments.

M-x works by running the command execute-extended-command, which is responsible for reading the name of another command and invoking it.

10 Help

Emacs provides a wide variety of help commands, all accessible through the prefix key C-h (or, equivalently, the function key ). These help commands are described in the following sections. You can also type C-h C-h to view a list of help commands (help-for-help). You can scroll the list with and , then type the help command you want. To cancel, type C-g.

Many help commands display their information in a special help buffer. In this buffer, you can type and to scroll and type to follow hyperlinks. See Help Mode.

If you are looking for a certain feature, but don’t know what it is called or where to look, we recommend three methods. First, try an apropos command, then try searching the manual index, then look in the FAQ and the package keywords.

  • C-h a topics

    This searches for commands whose names match the argument topics. The argument can be a keyword, a list of keywords, or a regular expression (see Regexps). See Apropos.

  • C-h i d m emacs i topic

    This searches for topic in the indices of the Emacs Info manual, displaying the first match found. Press , to see subsequent matches. You can use a regular expression as topic.

  • C-h i d m emacs s topic

    Similar, but searches the text of the manual rather than the indices.

  • C-h C-f

    This displays the Emacs FAQ, using Info.

  • C-h p

    This displays the available Emacs packages based on keywords. See Package Keywords.

C-h or mean “help” in various other contexts as well. For instance, you can type them after a prefix key to view a list of the keys that can follow the prefix key. (You can also use ? in this context. A few prefix keys don’t support C-h or ? in this way, because they define other meanings for those inputs, but they all support .)

  • Help Summary: Brief list of all Help commands.
  • Key Help: Asking what a key does in Emacs.
  • Name Help: Asking about a command, variable or function name.
  • Apropos: Asking what pertains to a given topic.
  • Help Mode: Special features of Help mode and Help buffers.
  • Package Keywords: Finding Lisp libraries by keywords (topics).
  • Language Help: Help relating to international language support.
  • Misc Help: Other help commands.
  • Help Files: Commands to display auxiliary help files.
  • Help Echo: Help on active text and tooltips (balloon help’’).

11 The Mark and the Region

Many Emacs commands operate on an arbitrary contiguous part of the current buffer. To specify the text for such a command to operate on, you set the mark at one end of it, and move point to the other end. The text between point and the mark is called the region. The region always extends between point and the mark, no matter which one comes earlier in the text; each time you move point, the region changes.

Setting the mark at a position in the text also activates it. When the mark is active, we say also that the region is active; Emacs indicates its extent by highlighting the text within it, using the region face (see Face Customization).

After certain non-motion commands, including any command that changes the text in the buffer, Emacs automatically deactivates the mark; this turns off the highlighting. You can also explicitly deactivate the mark at any time, by typing C-g (see Quitting).

The above default behavior is known as Transient Mark mode. Disabling Transient Mark mode switches Emacs to an alternative behavior, in which the region is usually not highlighted. See Disabled Transient Mark.

Setting the mark in one buffer has no effect on the marks in other buffers. When you return to a buffer with an active mark, the mark is at the same place as before. When multiple windows show the same buffer, they can have different values of point, and thus different regions, but they all share one common mark position. See Windows. Ordinarily, only the selected window highlights its region; however, if the variable highlight-nonselected-windows is non-nil, each window highlights its own region.

There is another kind of region: the rectangular region. See Rectangles.

  • Setting Mark: Commands to set the mark.
  • Marking Objects: Commands to put region around textual units.
  • Using Region: Summary of ways to operate on contents of the region.
  • Mark Ring: Previous mark positions saved so you can go back there.
  • Global Mark Ring: Previous mark positions in various buffers.
  • Shift Selection: Using shifted cursor motion keys.
  • Disabled Transient Mark: Leaving regions unhighlighted by default.

12 Killing and Moving Text

In Emacs, killing means erasing text and copying it into the kill ring. Yanking means bringing text from the kill ring back into the buffer. (Some applications use the terms “cutting” and “pasting” for similar operations.) The kill ring is so-named because it can be visualized as a set of blocks of text arranged in a ring, which you can access in cyclic order. See Kill Ring.

Killing and yanking are the most common way to move or copy text within Emacs. It is very versatile, because there are commands for killing many different types of syntactic units.

  • Deletion and Killing: Commands that remove text.
  • Yanking: Commands that insert text.
  • Cut and Paste: Clipboard and selections on graphical displays.
  • Accumulating Text: Other methods to add text to the buffer.
  • Rectangles: Operating on text in rectangular areas.
  • CUA Bindings: Using C-x/C-c/C-v to kill and yank.

13 Registers

Emacs registers are compartments where you can save text, rectangles, positions, and other things for later use. Once you save text or a rectangle in a register, you can copy it into the buffer once or many times; once you save a position in a register, you can jump back to that position once or many times.

Each register has a name that consists of a single character, which we will denote by r; r can be a letter (such as ‘a’) or a number (such as ‘1’); case matters, so register ‘a’ is not the same as register ‘A’. You can also set a register in non-alphanumeric characters, for instance ‘*’ or ‘C-d’. Note, it’s not possible to set a register in ‘C-g’ or ‘ESC’, because these keys are reserved for quitting (see Quitting).

A register can store a position, a piece of text, a rectangle, a number, a window configuration, or a file name, but only one thing at any given time. Whatever you store in a register remains there until you store something else in that register. To see what register r contains, use M-x view-register:

  • M-x view-register r

    Display a description of what register r contains.

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 .

Bookmarks record files and positions in them, so you can return to those positions when you look at the file again. Bookmarks are similar in spirit to registers, so they are also documented in this chapter.

  • Position Registers: Saving positions in registers.
  • Text Registers: Saving text in registers.
  • Rectangle Registers: Saving rectangles in registers.
  • Configuration Registers: Saving window configurations in registers.
  • Number Registers: Numbers in registers.
  • File Registers: File names in registers.
  • Keyboard Macro Registers: Keyboard macros in registers.
  • Bookmarks: Bookmarks are like registers, but persistent.

14 Controlling the Display

Since only part of a large buffer fits in the window, Emacs has to show only a part of it. This chapter describes commands and variables that let you specify which part of the text you want to see, and how the text is displayed.

  • Scrolling: Commands to move text up and down in a window.
  • Recentering: A scroll command that centers the current line.
  • Auto Scrolling: Redisplay scrolls text automatically when needed.
  • Horizontal Scrolling: Moving text left and right in a window.
  • Narrowing: Restricting display and editing to a portion of the buffer.
  • View Mode: Viewing read-only buffers.
  • Follow Mode: Follow mode lets two windows scroll as one.
  • Faces: How to change the display style using faces.
  • Colors: Specifying colors for faces.
  • Standard Faces: The main predefined faces.
  • Text Scale: Increasing or decreasing text size in a buffer.
  • Font Lock: Minor mode for syntactic highlighting using faces.
  • Highlight Interactively: Tell Emacs what text to highlight.
  • Fringes: Enabling or disabling window fringes.
  • Displaying Boundaries: Displaying top and bottom of the buffer.
  • Useless Whitespace: Showing possibly spurious trailing whitespace.
  • Selective Display: Hiding lines with lots of indentation.
  • Optional Mode Line: Optional mode line display features.
  • Text Display: How text characters are normally displayed.
  • Cursor Display: Features for displaying the cursor.
  • Line Truncation: Truncating lines to fit the screen width instead of continuing them to multiple screen lines.
  • Visual Line Mode: Word wrap and screen line-based editing.
  • Display Custom: Information on variables for customizing display.

15 Searching and Replacement

需要关注的部分.

Like other editors, Emacs has commands to search for occurrences of a string. Emacs also has commands to replace occurrences of a string with a different string. There are also commands that do the same thing, but search for patterns instead of fixed strings.

You can also search multiple files under the control of xref (see Identifier Search) or through the Dired A command (see Operating on Files), or ask the grep program to do it (see Grep Searching).

  • Incremental Search: Search happens as you type the string.
  • Nonincremental Search: Specify entire string and then search.
  • Word Search: Search for sequence of words.
  • Symbol Search: Search for a source code symbol.
  • Regexp Search: Search for match for a regexp.
  • Regexps: Syntax of regular expressions.
  • Regexp Backslash: Regular expression constructs starting with `\’.
  • Regexp Example: A complex regular expression explained.
  • Lax Search: Search ignores some distinctions among similar characters, like letter-case.
  • Replace: Search, and replace some or all matches.
  • Other Repeating Search: Operating on all matches for some regexp.
  • Search Customizations: Various search customizations.

16 Commands for Fixing Typos

In this chapter we describe commands that are useful when you catch a mistake while editing. The most fundamental of these commands is the undo command C-/ (also bound to C-x u and C-_). This undoes a single command, or a part of a command (as in the case of query-replace), or several consecutive character insertions. Consecutive repetitions of C-/ undo earlier and earlier changes, back to the limit of the undo information available.

Aside from the commands described here, you can erase text using deletion commands such as (delete-backward-char). These were described earlier in this manual. See Erasing.

  • Undo: The Undo commands.
  • Transpose: Exchanging two characters, words, lines, lists…
  • Fixing Case: Correcting case of last word entered.
  • Spelling: Apply spelling checker to a word, or a whole file.

17 Keyboard Macros

device的部分.

In this chapter we describe how to record a sequence of editing commands so you can repeat it conveniently later.

A keyboard macro is a command defined by an Emacs user to stand for another sequence of keys. For example, if you discover that you are about to type C-n M-d C-d forty times, you can speed your work by defining a keyboard macro to do C-n M-d C-d, and then executing it 39 more times.

You define a keyboard macro by executing and recording the commands which are its definition. Put differently, as you define a keyboard macro, the definition is being executed for the first time. This way, you can see the effects of your commands, so that you don’t have to figure them out in your head. When you close the definition, the keyboard macro is defined and also has been, in effect, executed once. You can then do the whole thing over again by invoking the macro.

Keyboard macros differ from ordinary Emacs commands in that they are written in the Emacs command language rather than in Lisp. This makes it easier for the novice to write them, and makes them more convenient as temporary hacks. However, the Emacs command language is not powerful enough as a programming language to be useful for writing anything intelligent or general. For such things, Lisp must be used.

  • Basic Keyboard Macro: Defining and running keyboard macros.
  • Keyboard Macro Ring: Where previous keyboard macros are saved.
  • Keyboard Macro Counter: Inserting incrementing numbers in macros.
  • Keyboard Macro Query: Making keyboard macros do different things each time.
  • Save Keyboard Macro: Giving keyboard macros names; saving them in files.
  • Edit Keyboard Macro: Editing keyboard macros.
  • Keyboard Macro Step-Edit: Interactively executing and editing a keyboard macro.

18 File Handling

The operating system stores data permanently in named files, so most of the text you edit with Emacs comes from a file and is ultimately stored in a file.

To edit a file, you must tell Emacs to read the file and prepare a buffer containing a copy of the file’s text. This is called visiting the file. Editing commands apply directly to text in the buffer; that is, to the copy inside Emacs. Your changes appear in the file itself only when you save the buffer back into the file.

In addition to visiting and saving files, Emacs can delete, copy, rename, and append to files, keep multiple versions of them, and operate on file directories.

  • File Names: How to type and edit file-name arguments.
  • Visiting: Visiting a file prepares Emacs to edit the file.
  • Saving: Saving makes your changes permanent.
  • Reverting: Reverting cancels all the changes not saved.
  • Autorevert: Auto Reverting non-file buffers.
  • Auto Save: Auto Save periodically protects against loss of data.
  • File Aliases: Handling multiple names for one file.
  • Directories: Creating, deleting, and listing file directories.
  • Comparing Files: Finding where two files differ.
  • Diff Mode: Mode for editing file differences.
  • Copying and Naming: Copying, naming and renaming files.
  • Misc File Ops: Other things you can do on files.
  • Compressed Files: Accessing compressed files.
  • File Archives: Operating on tar, zip, jar etc. archive files.
  • Remote Files: Accessing files on other machines.
  • Quoted File Names: Quoting special characters in file names.
  • File Name Cache: Completion against a list of files you often use.
  • File Conveniences: Convenience Features for Finding Files.
  • Filesets: Handling sets of files.

19 Using Multiple Buffers

The text you are editing in Emacs resides in an object called a buffer. Each time you visit a file, a buffer is used to hold the file’s text. Each time you invoke Dired, a buffer is used to hold the directory listing. If you send a message with C-x m, a buffer is used to hold the text of the message. When you ask for a command’s documentation, that appears in a buffer named Help.

Each buffer has a unique name, which can be of any length. When a buffer is displayed in a window, its name is shown in the mode line (see Mode Line). The distinction between upper and lower case matters in buffer names. Most buffers are made by visiting files, and their names are derived from the files’ names; however, you can also create an empty buffer with any name you want. A newly started Emacs has several buffers, including one named scratch, which can be used for evaluating Lisp expressions and is not associated with any file (see Lisp Interaction).

At any time, one and only one buffer is selected; we call it the current buffer. We sometimes say that a command operates on “the buffer”; this really means that it operates on the current buffer. When there is only one Emacs window, the buffer displayed in that window is current. When there are multiple windows, the buffer displayed in the selected window is current. See Windows.

A buffer’s contents consist of a series of characters, each of which optionally carries a set of text properties (see Text properties) that can specify more information about that character.

Aside from its textual contents, each buffer records several pieces of information, such as what file it is visiting (if any), whether it is modified, and what major mode and minor modes are in effect (see Modes). These are stored in buffer-local variables—variables that can have a different value in each buffer. See Locals.

A buffer’s size cannot be larger than some maximum, which is defined by the largest buffer position representable by Emacs integers. This is because Emacs tracks buffer positions using that data type. For typical 64-bit machines, this maximum buffer size is 2^61 - 2 bytes, or about 2 EiB. For typical 32-bit machines, the maximum is usually 2^29 - 2 bytes, or about 512 MiB. Buffer sizes are also limited by the amount of memory in the system.

  • Select Buffer: Creating a new buffer or reselecting an old one.
  • List Buffers: Getting a list of buffers that exist.
  • Misc Buffer: Renaming; changing read-only status; copying text.
  • Kill Buffer: Killing buffers you no longer need.
  • Several Buffers: How to go through the list of all buffers and operate variously on several of them.
  • Indirect Buffers: An indirect buffer shares the text of another buffer.
  • Buffer Convenience: Convenience and customization features for buffer handling.

20 Multiple Windows

Emacs can split a frame into two or many windows. Multiple windows can display parts of different buffers, or different parts of one buffer. Multiple frames always imply multiple windows, because each frame has its own set of windows. Each window belongs to one and only one frame.

  • Basic Window: Introduction to Emacs windows.
  • Split Window: New windows are made by splitting existing windows.
  • Other Window: Moving to another window or doing something to it.
  • Pop Up Window: Finding a file or buffer in another window.
  • Change Window: Deleting windows and changing their sizes.
  • Displaying Buffers: How Emacs picks a window for displaying a buffer.
  • Window Convenience: Convenience functions for window handling.

21 Frames and Graphical Displays

When Emacs is started on a graphical display, e.g., on the X Window System, it occupies a graphical system-level display region. In this manual, we call this a frame, reserving the word “window” for the part of the frame used for displaying a buffer. A frame initially contains one window, but it can be subdivided into multiple windows (see Windows). A frame normally also contains a menu bar, tool bar, and echo area.

You can also create additional frames (see Creating Frames). All frames created in the same Emacs session have access to the same underlying buffers and other data. For instance, if a buffer is being shown in more than one frame, any changes made to it in one frame show up immediately in the other frames too.

Typing C-x C-c closes all the frames on the current display, and ends the Emacs session if it has no frames open on any other displays (see Exiting). To close just the selected frame, type C-x 5 0 (that is zero, not o).

This chapter describes Emacs features specific to graphical displays (particularly mouse commands), and features for managing multiple frames. On text terminals, many of these features are unavailable. However, it is still possible to create multiple frames on text terminals; such frames are displayed one at a time, filling the entire terminal screen (see Non-Window Terminals). It is also possible to use the mouse on some text terminals (see Text-Only Mouse, for doing so on GNU and Unix systems; and see MS-DOS Mouse, for doing so on MS-DOS). Menus are supported on all text terminals.

  • Mouse Commands: Moving, cutting, and pasting, with the mouse.
  • Word and Line Mouse: Mouse commands for selecting whole words or lines.
  • Mouse References: Using the mouse to select an item from a list.
  • Menu Mouse Clicks: Mouse clicks that bring up menus.
  • Mode Line Mouse: Mouse clicks on the mode line.
  • Creating Frames: Creating additional Emacs frames with various contents.
  • Frame Commands: Iconifying, deleting, and switching frames.
  • Fonts: Changing the frame font.
  • Speedbar: How to make and use a speedbar frame.
  • Multiple Displays: How one Emacs instance can talk to several displays.
  • Frame Parameters: Changing the colors and other modes of frames.
  • Scroll Bars: How to enable and disable scroll bars; how to use them.
  • Window Dividers: Window separators that can be dragged with the mouse.
  • Drag and Drop: Using drag and drop to open files and insert text.
  • Menu Bars: Enabling and disabling the menu bar.
  • Tool Bars: Enabling and disabling the tool bar.
  • Dialog Boxes: Controlling use of dialog boxes.
  • Tooltips: Displaying information at the current mouse position.
  • Mouse Avoidance: Preventing the mouse pointer from obscuring text.
  • Non-Window Terminals: Multiple frames on terminals that show only one.
  • Text-Only Mouse: Using the mouse in text terminals.

23 Major and Minor Modes

Emacs contains many editing modes that alter its basic behavior in useful ways. These are divided into major modes and minor modes.

Major modes provide specialized facilities for working on a particular file type, such as a C source file (see Programs), or a particular type of non-file buffer, such as a shell buffer (see Shell). Major modes are mutually exclusive; each buffer has one and only one major mode at any time.

Minor modes are optional features which you can turn on or off, not necessarily specific to a type of file or buffer. For example, Auto Fill mode is a minor mode in which breaks lines between words as you type (see Auto Fill). Minor modes are independent of one another, and of the selected major mode.

  • Major Modes: Text mode vs. Lisp mode vs. C mode…
  • Minor Modes: Each minor mode is a feature you can turn on independently of any others.
  • Choosing Modes: How modes are chosen when visiting files.

24 Indentation

Indentation refers to inserting or adjusting whitespace characters (space and/or tab characters) at the beginning of a line of text. This chapter documents indentation commands and options which are common to Text mode and related modes, as well as programming language modes. See Program Indent, for additional documentation about indenting in programming modes.

The simplest way to perform indentation is the key. In most major modes, this runs the command indent-for-tab-command. (In C and related modes, runs the command c-indent-line-or-region, which behaves similarly, see C Indent).

  • Insert whitespace, or indent the current line, in a mode-appropriate way (indent-for-tab-command). If the region is active, indent all the lines within it.

The exact behavior of depends on the major mode. In Text mode and related major modes, normally inserts some combination of space and tab characters to advance point to the next tab stop (see Tab Stops). For this purpose, the position of the first non-whitespace character on the preceding line is treated as an additional tab stop, so you can use to align point with the preceding line. If the region is active (see Using Region), acts specially: it indents each line in the region so that its first non-whitespace character is aligned with the preceding line.

In programming modes, indents the current line of code in a way that makes sense given the code in the preceding lines. If the region is active, all the lines in the region are indented this way. If point was initially within the current line’s indentation, it is repositioned to the first non-whitespace character on the line.

If you just want to insert a tab character in the buffer, type C-q (see Inserting Text).

  • Indentation Commands: More commands for performing indentation.
  • Tab Stops: Stop points for indentation in Text modes.
  • Just Spaces: Using only space characters for indentation.
  • Indent Convenience: Optional indentation features.

22 International Character Set Support

Emacs supports a wide variety of international character sets, including European and Vietnamese variants of the Latin alphabet, as well as Arabic scripts, Brahmic scripts (for languages such as Bengali, Hindi, and Thai), Cyrillic, Ethiopic, Georgian, Greek, Han (for Chinese and Japanese), Hangul (for Korean), Hebrew and IPA. Emacs also supports various encodings of these characters that are used by other internationalized software, such as word processors and mailers.

Emacs allows editing text with international characters by supporting all the related activities:

  • You can visit files with non-ASCII characters, save non-ASCII text, and pass non-ASCII text between Emacs and programs it invokes (such as compilers, spell-checkers, and mailers). Setting your language environment (see Language Environments) takes care of setting up the coding systems and other options for a specific language or culture. Alternatively, you can specify how Emacs should encode or decode text for each command; see Text Coding.

  • You can display non-ASCII characters encoded by the various scripts. This works by using appropriate fonts on graphics displays (see Defining Fontsets), and by sending special codes to text displays (see Terminal Coding). If some characters are displayed incorrectly, refer to Undisplayable Characters, which describes possible problems and explains how to solve them.

  • Characters from scripts whose natural ordering of text is from right to left are reordered for display (see Bidirectional Editing). These scripts include Arabic, Hebrew, Syriac, Thaana, and a few others.

  • You can insert non-ASCII characters or search for them. To do that, you can specify an input method (see Select Input Method) suitable for your language, or use the default input method set up when you choose your language environment. If your keyboard can produce non-ASCII characters, you can select an appropriate keyboard coding system (see Terminal Coding), and Emacs will accept those characters. Latin-1 characters can also be input by using the C-x 8 prefix, see Unibyte Mode.

    With the X Window System, your locale should be set to an appropriate value to make sure Emacs interprets keyboard input correctly; see locales.

The rest of this chapter describes these issues in detail.

  • International Chars: Basic concepts of multibyte characters.
  • Language Environments: Setting things up for the language you use.
  • Input Methods: Entering text characters not on your keyboard.
  • Select Input Method: Specifying your choice of input methods.
  • Coding Systems: Character set conversion when you read and write files, and so on.
  • Recognize Coding: How Emacs figures out which conversion to use.
  • Specify Coding: Specifying a file’s coding system explicitly.
  • Output Coding: Choosing coding systems for output.
  • Text Coding: Choosing conversion to use for file text.
  • Communication Coding: Coding systems for interprocess communication.
  • File Name Coding: Coding systems for file names.
  • Terminal Coding: Specifying coding systems for converting terminal input and output.
  • Fontsets: Fontsets are collections of fonts that cover the whole spectrum of characters.
  • Defining Fontsets: Defining a new fontset.
  • Modifying Fontsets: Modifying an existing fontset.
  • Undisplayable Characters: When characters don’t display.
  • Unibyte Mode: You can pick one European character set to use without multibyte characters.
  • Charsets: How Emacs groups its internal character codes.
  • Bidirectional Editing: Support for right-to-left scripts.

25 Commands for Human Languages

This chapter describes Emacs commands that act on text, by which we mean sequences of characters in a human language (as opposed to, say, a computer programming language). These commands act in ways that take into account the syntactic and stylistic conventions of human languages: conventions involving words, sentences, paragraphs, and capital letters. There are also commands for filling, which means rearranging the lines of a paragraph to be approximately equal in length. These commands, while intended primarily for editing text, are also often useful for editing programs.

Emacs has several major modes for editing human-language text. If the file contains ordinary text, use Text mode, which customizes Emacs in small ways for the syntactic conventions of text. Outline mode provides special commands for operating on text with an outline structure. See Outline Mode.

Org mode extends Outline mode and turns Emacs into a full-fledged organizer: you can manage TODO lists, store notes and publish them in many formats. See the Org Info manual, which is distributed with Emacs.

Emacs has other major modes for text which contains embedded commands, such as TeX and LaTeX (see TeX Mode); HTML and SGML (see HTML Mode); XML (see the nXML mode Info manual, which is distributed with Emacs); and Groff and Nroff (see Nroff Mode).

If you need to edit ASCII art pictures made out of text characters, use Picture mode, a special major mode for editing such pictures. See Picture Mode.

  • Words: Moving over and killing words.
  • Sentences: Moving over and killing sentences.
  • Paragraphs: Moving over paragraphs.
  • Pages: Moving over pages.
  • Quotation Marks: Inserting quotation marks.
  • Filling: Filling or justifying text.
  • Case: Changing the case of text.
  • Text Mode: The major modes for editing text files.
  • Outline Mode: Editing outlines.
  • Org Mode: The Emacs organizer.
  • TeX Mode: Editing TeX and LaTeX files.
  • HTML Mode: Editing HTML and SGML files.
  • Nroff Mode: Editing input to the nroff formatter.
  • Enriched Text: Editing text enriched with fonts, colors, etc.
  • Text Based Tables: Commands for editing text-based tables.
  • Two-Column: Splitting text columns into separate windows.

26 Editing Programs

This chapter describes Emacs features for facilitating editing programs. Some of the things these features can do are:

  • Find or move over top-level definitions (see Defuns).
  • Apply the usual indentation conventions of the language (see Program Indent).
  • Balance parentheses (see Parentheses).
  • Insert, kill or align comments (see Comments).
  • Highlight program syntax (see Font Lock).

  • Program Modes: Major modes for editing programs.

  • Defuns: Commands to operate on major top-level parts of a program.
  • Program Indent: Adjusting indentation to show the nesting.
  • Parentheses: Commands that operate on parentheses.
  • Comments: Inserting, killing, and aligning comments.
  • Documentation: Getting documentation of functions you plan to call.
  • Hideshow: Displaying blocks selectively.
  • Symbol Completion: Completion on symbol names of your program or language.
  • MixedCase Words: Dealing with identifiersLikeThis.
  • Semantic: Suite of editing tools based on source code parsing.
  • Misc for Programs: Other Emacs features useful for editing programs.
  • C Modes: Special commands of C, C++, Objective-C, Java, IDL, Pike and AWK modes.
  • Asm Mode: Asm mode and its special features.
  • Fortran: Fortran mode and its special features.

27 Compiling and Testing Programs

The previous chapter discusses the Emacs commands that are useful for making changes in programs. This chapter deals with commands that assist in the process of compiling and testing programs.

  • Compilation: Compiling programs in languages other than Lisp (C, Pascal, etc.).

  • Compilation Mode: The mode for visiting compiler errors.

  • Compilation Shell: Customizing your shell properly for use in the compilation buffer.

  • Grep Searching: Searching with grep.

    功能不错.

  • Flymake: Finding syntax errors on the fly.

  • Debuggers: Running symbolic debuggers for non-Lisp programs.

  • Executing Lisp: Various modes for editing Lisp programs, with different facilities for running the Lisp programs.

  • Libraries: How Lisp programs are loaded into Emacs.

  • Eval: Executing a single Lisp expression in Emacs.

  • Interaction: Executing Lisp in an Emacs buffer.

  • External Lisp: Communicating through Emacs with a separate Lisp.

功能性的部分. Project management,,

28 Maintaining Large Programs

This chapter describes Emacs features for maintaining medium- to large-size programs and packages. These features include:

  • Unified interface to Support for Version Control Systems (VCS) that record the history of changes to source files.
  • A specialized mode for maintaining ChangeLog files that provide a chronological log of program changes.
  • Xref, a set of commands for displaying definitions of symbols (a.k.a. “identifiers”) and their references.
  • EDE, the Emacs’s own IDE.
  • A mode for merging changes to program sources made on separate branches of development.

If you are maintaining a large Lisp program, then in addition to the features described here, you may find the Emacs Lisp Regression Testing (ERT) library useful (see ERT).

  • Version Control: Using version control systems.
  • Change Log: Maintaining a change history for your program.
  • Xref: Find definitions and references of any function, method, struct, macro, … in your program.
  • EDE: An integrated development environment for Emacs.
  • Emerge: A convenient way of merging two versions of a program.

29 Abbrevs

A defined abbrev is a word which expands, if you insert it, into some different text. Abbrevs are defined by the user to expand in specific ways. For example, you might define ‘foo’ as an abbrev expanding to ‘find outer otter’. Then you could insert ‘find outer otter ’ into the buffer by typing f o o .

A second kind of abbreviation facility is called dynamic abbrev expansion. You use dynamic abbrev expansion with an explicit command to expand the letters in the buffer before point by looking for other words in the buffer that start with those letters. See Dynamic Abbrevs.

A third kind, hippie expansion, generalizes abbreviation expansion. See Hippie Expansion.

  • Abbrev Concepts: Fundamentals of defined abbrevs.
  • Defining Abbrevs: Defining an abbrev, so it will expand when typed.
  • Expanding Abbrevs: Controlling expansion: prefixes, canceling expansion.
  • Editing Abbrevs: Viewing or editing the entire list of defined abbrevs.
  • Saving Abbrevs: Saving the entire list of abbrevs for another session.
  • Dynamic Abbrevs: Abbreviations for words already in the buffer.
  • Dabbrev Customization: What is a word, for dynamic abbrevs. Case handling.

30 Dired, the Directory Editor

Dired makes an Emacs buffer containing a listing of a directory, and optionally some of its subdirectories as well. You can use the normal Emacs commands to move around in this buffer, and special Dired commands to operate on the listed files. Dired works with both local and remote directories.

The Dired buffer is normally read-only, and inserting text in it is not allowed (however, the Wdired mode allows that, see Wdired). Ordinary printing characters such as d and x are redefined for special Dired commands. Some Dired commands mark or flag the current file (that is, the file on the current line); other commands operate on the marked files or on the flagged files. You first mark certain files in order to operate on all of them with one command.

The Dired-X package provides various extra features for Dired mode. See Dired-X.

You can also view a list of files in a directory with C-x C-d (list-directory). Unlike Dired, this command does not allow you to operate on the listed files. See Directories.

  • Enter: How to invoke Dired.
  • Navigation: Special motion commands in the Dired buffer.
  • Deletion: Deleting files with Dired.
  • Flagging Many Files: Flagging files based on their names.
  • Visit: Other file operations through Dired.
  • Marks vs Flags: Flagging for deletion vs marking.
  • Operating on Files: How to copy, rename, print, compress, etc. either one file or several files.
  • Shell Commands in Dired: Running a shell command on the marked files.
  • Transforming File Names: Using patterns to rename multiple files.
  • Comparison in Dired: Running diff by way of Dired.
  • Subdirectories in Dired: Adding subdirectories to the Dired buffer.
  • Subdir Switches: Subdirectory switches in Dired.
  • Subdirectory Motion: Moving across subdirectories, and up and down.
  • Hiding Subdirectories: Making subdirectories visible or invisible.
  • Updating: Discarding lines for files of no interest.
  • Find: Using find to choose the files for Dired.
  • Wdired: Operating on files by editing the Dired buffer.
  • Image-Dired: Viewing image thumbnails in Dired.
  • Misc: Various other features.

31 The Calendar and the Diary

掌握的部分.

Emacs provides the functions of a desk calendar, with a diary of planned or past events. It also has facilities for managing your appointments, and keeping track of how much time you spend working on certain projects.

To enter the calendar, type M-x calendar. This displays a three-month calendar centered on the current month, with point on the current date. With a numeric argument, as in C-u M-x calendar, it prompts you for the month and year to be the center of the three-month calendar. The calendar uses its own buffer, whose major mode is Calendar mode.

mouse-3 in the calendar brings up a menu of operations on a particular date; mouse-2 brings up a menu of commonly used calendar features that are independent of any particular date. To exit the calendar, type q.

  • Calendar Motion: Moving through the calendar; selecting a date.
  • Scroll Calendar: Bringing earlier or later months onto the screen.
  • Counting Days: How many days are there between two dates?
  • General Calendar: Exiting or recomputing the calendar.
  • Writing Calendar Files: Writing calendars to files of various formats.
  • Holidays: Displaying dates of holidays.
  • Sunrise/Sunset: Displaying local times of sunrise and sunset.
  • Lunar Phases: Displaying phases of the moon.
  • Other Calendars: Converting dates to other calendar systems.
  • Diary: Displaying events from your diary.
  • Daylight Saving: How to specify when daylight saving time is active.
  • Time Intervals: Keeping track of time intervals.
  • Advanced Calendar/Diary Usage: Advanced Calendar/Diary customization.

32 Sending Mail

To send an email message from Emacs, type C-x m. This switches to a buffer named unsent mail, where you can edit the text and headers of the message. When done, type C-c C-s or C-c C-c to send it.

  • C-x m

    Begin composing mail (compose-mail).

  • C-x 4 m

    Likewise, in another window (compose-mail-other-window).

  • C-x 5 m

    Likewise, but in a new frame (compose-mail-other-frame).

  • C-c C-s

    In the mail buffer, send the message (message-send).

  • C-c C-c

    In the mail buffer, send the message and bury the buffer (message-send-and-exit).

The mail buffer is an ordinary Emacs buffer, so you can switch to other buffers while composing the mail. If you want to send another mail before finishing the current one, type C-x m again to open a new mail buffer whose name has a different numeric suffix (see Misc Buffer). If you invoke the command with a prefix argument, C-u C-x m, Emacs switches back to the last mail buffer, and asks if you want to erase the message in that buffer; if you answer no, this lets you pick up editing the message where you left off.

The command C-x 4 m (compose-mail-other-window) does the same as C-x m, except it displays the mail buffer in a different window. The command C-x 5 m (compose-mail-other-frame) does it in a new frame.

When you type C-c C-c or C-c C-s to send the mail, Emacs may ask you how it should deliver the mail—either directly via SMTP, or using some other method. See Mail Sending, for details.

  • Format: Format of a mail message.
  • Headers: Details of some standard mail header fields.
  • Aliases: Abbreviating and grouping mail addresses.
  • Commands: Special commands for editing mail being composed.
  • Signature: Adding a signature to every message.
  • Amuse: Distracting the NSA; adding fortune messages.
  • Methods: Using alternative mail-composition methods.

33 Reading Mail with Rmail

Rmail is an Emacs subsystem for reading and disposing of mail that you receive. Rmail stores mail messages in files called Rmail files. Reading the messages in an Rmail file is done in a special major mode, Rmail mode, which redefines most letters to run commands for managing mail.

Emacs also comes with a much more sophisticated and flexible subsystem for reading mail, called Gnus. Gnus is a very large package, and is therefore described in its own manual, see Top.

  • Basic: Basic concepts of Rmail, and simple use.
  • Scroll: Scrolling through a message.
  • Motion: Moving to another message.
  • Deletion: Deleting and expunging messages.
  • Inbox: How mail gets into the Rmail file.
  • Files: Using multiple Rmail files.
  • Output: Copying messages out to files.
  • Labels: Classifying messages by labeling them.
  • Attrs: Certain standard labels, called attributes.
  • Reply: Sending replies to messages you are viewing.
  • Summary: Summaries show brief info on many messages.
  • Sort: Sorting messages in Rmail.
  • Display: How Rmail displays a message; customization.
  • Coding: How Rmail handles decoding character sets.
  • Editing: Editing message text and headers in Rmail.
  • Digest: Extracting the messages from a digest message.
  • Rot13: Reading messages encoded in the rot13 code.
  • Movemail: More details of fetching new mail.
  • Remote Mailboxes: Retrieving mail from remote mailboxes.
  • Other Mailbox Formats: Retrieving mail from local mailboxes in various formats.

34 Email and Usenet News with Gnus

Reading and writing email with emacs - Emacs Stack Exchange

Gnus is an Emacs package primarily designed for reading and posting Usenet news. It can also be used to read and respond to messages from a number of other sources—email, remote directories, digests, and so on. Here we introduce Gnus and describe several basic features. For full details, see Gnus.

  • Buffers of Gnus: The group, summary, and article buffers.

  • Gnus Startup: What you should know about starting Gnus.

  • Gnus Group Buffer: A short description of Gnus group commands.

  • Gnus Summary Buffer: A short description of Gnus summary commands.

35 Host Security

Emacs runs inside an operating system such as GNU/Linux, and relies on the operating system to check security constraints such as accesses to files. The default settings for Emacs are designed for typical use; they may require some tailoring in environments where security is more of a concern, or less of a concern, than usual. For example, file-local variables can be risky, and you can set the variable enable-local-variables to :safe or (even more conservatively) to nil; conversely, if your files can all be trusted and the default checking for these variables is irritating, you can set enable-local-variables to :all. See Safe File Variables.

See Security Considerations, for more information about security considerations when using Emacs as part of a larger application.

36 Network Security

Whenever Emacs establishes any network connection, it passes the established connection to the Network Security Manager (NSM). NSM is responsible for enforcing the network security under your control. Currently, this works by using the Transport Layer Security (TLS) features.

The network-security-level variable determines the security level that NSM enforces. If its value is low, no security checks are performed.

If this variable is medium (which is the default), a number of checks will be performed. If as result NSM determines that the network connection might not be trustworthy, it will make you aware of that, and will ask you what to do about the network connection.

You can decide to register a permanent security exception for an unverified connection, a temporary exception, or refuse the connection entirely.

Below is a list of the checks done on the medium level.

  • unable to verify a TLS certificate

    If the connection is a TLS, SSL or STARTTLS connection, NSM will check whether the certificate used to establish the identity of the server we’re connecting to can be verified.While an invalid certificate is often the cause for concern (there could be a Man-in-the-Middle hijacking your network connection and stealing your password), there may be valid reasons for going ahead with the connection anyway. For instance, the server may be using a self-signed certificate, or the certificate may have expired. It’s up to you to determine whether it’s acceptable to continue with the connection.

  • a self-signed certificate has changed

    If you’ve previously accepted a self-signed certificate, but it has now changed, that could mean that the server has just changed the certificate, but it might also mean that the network connection has been hijacked.

  • previously encrypted connection now unencrypted

    If the connection is unencrypted, but it was encrypted in previous sessions, this might mean that there is a proxy between you and the server that strips away STARTTLSannouncements, leaving the connection unencrypted. This is usually very suspicious.

  • talking to an unencrypted service when sending a password

    When connecting to an IMAP or POP3 server, these should usually be encrypted, because it’s common to send passwords over these connections. Similarly, if you’re sending email via SMTP that requires a password, you usually want that connection to be encrypted. If the connection isn’t encrypted, NSM will warn you.

If network-security-level is high, the following checks will be made, in addition to the above:

  • a validated certificate changes the public key

    Servers change their keys occasionally, and that is normally nothing to be concerned about. However, if you are worried that your network connections are being hijacked by agencies who have access to pliable Certificate Authorities which issue new certificates for third-party services, you may want to keep track of these changes.

  • Diffie-Hellman low prime bits

    When doing the public key exchange, the number of prime bits should be high to ensure that the channel can’t be eavesdropped on by third parties. If this number is too low, you will be warned.

  • RC4 stream cipher

    The RC4 stream cipher is believed to be of low quality and may allow eavesdropping by third parties.

  • SSL1, SSL2 and SSL3

    The protocols older than TLS1.0 are believed to be vulnerable to a variety of attacks, and you may want to avoid using these if what you’re doing requires higher security.

Finally, if network-security-level is paranoid, you will also be notified the first time NSM sees any new certificate. This will allow you to inspect all the certificates from all the connections that Emacs makes.

The following additional variables can be used to control details of NSM operation:

  • nsm-settings-file

    This is the file where NSM stores details about connections. It defaults to ~/.emacs.d/network-security.data.

  • nsm-save-host-names

    By default, host names will not be saved for non-STARTTLS connections. Instead a host/port hash is used to identify connections. This means that one can’t casually read the settings file to see what servers the user has connected to. If this variable is t, NSM will also save host names in the nsm-settings-file.

37 Document Viewing

DocView mode is a major mode for viewing DVI, PostScript (PS), PDF, OpenDocument, and Microsoft Office documents. It provides features such as slicing, zooming, and searching inside documents. It works by converting the document to a set of images using the gs (GhostScript) or mudraw/pdfdraw (MuPDF) commands and other external tools 1, and displaying those images.

When you visit a document file that can be displayed with DocView mode, Emacs automatically uses that mode 2. As an exception, when you visit a PostScript file, Emacs switches to PS mode, a major mode for editing PostScript files as text; however, it also enables DocView minor mode, so you can type C-c C-c to view the document with DocView. In either DocView mode or DocView minor mode, repeating C-c C-c (doc-view-toggle-display) toggles between DocView and the underlying file contents.

When you visit a file which would normally be handled by DocView mode but some requirement is not met (e.g., you operate in a terminal frame or Emacs has no PNG support), you are queried if you want to view the document’s contents as plain text. If you confirm, the buffer is put in text mode and DocView minor mode is activated. Thus, by typing C-c C-cyou switch to the fallback mode. With another C-c C-c you return to DocView mode. The plain text contents can also be displayed from within DocView mode by typing C-c C-t(doc-view-open-text).

You can explicitly enable DocView mode with the command M-x doc-view-mode. You can toggle DocView minor mode with M-x doc-view-minor-mode.

When DocView mode starts, it displays a welcome screen and begins formatting the file, page by page. It displays the first page once that has been formatted.

To kill the DocView buffer, type k (doc-view-kill-proc-and-buffer). To bury it, type q (quit-window).

  • Navigation: Navigating DocView buffers.
  • Searching: Searching inside documents.
  • Slicing: Specifying which part of a page is displayed.
  • Conversion: Influencing and triggering conversion.

38 Running Shell Commands from Emacs

基本的命令能调动,
program invoke editors.

Emacs has commands for passing single command lines to shell subprocesses, and for running a shell interactively with input and output to an Emacs buffer, and for running a shell in a terminal emulator window.

  • M-! cmd

    Run the shell command cmd and display the output (shell-command).

  • M-| cmd

    Run the shell command cmd with region contents as input; optionally replace the region with the output (shell-command-on-region).

  • M-& cmd

    Run the shell command cmd asynchronously, and display the output (async-shell-command).

  • M-x shell

    Run a subshell with input and output through an Emacs buffer. You can then give commands interactively.

  • M-x term

    Run a subshell with input and output through an Emacs buffer. You can then give commands interactively. Full terminal emulation is available.

Whenever you specify a relative file name for an executable program (either in the cmd argument to one of the above commands, or in other contexts), Emacs searches for the program in the directories specified by the variable exec-path. The value of this variable must be a list of directories; the default value is initialized from the environment variable PATH when Emacs is started (see General Variables).

M-x eshell invokes a shell implemented entirely in Emacs. It is documented in its own manual. See Eshell.

  • Single Shell: How to run one shell command and return.
  • Interactive Shell: Permanent shell taking input via Emacs.
  • Shell Mode: Special Emacs commands used with permanent shell.
  • Shell Prompts: Two ways to recognize shell prompts.
  • History: Repeating previous commands in a shell buffer.
  • Directory Tracking: Keeping track when the subshell changes directory.
  • Options: Options for customizing Shell mode.
  • Terminal emulator: An Emacs window as a terminal emulator.
  • Term Mode: Special Emacs commands used in Term mode.
  • Remote Host: Connecting to another computer.
  • Serial Terminal: Connecting to a serial port.

39 Using Emacs as a Server

Various programs can invoke your choice of editor to edit a particular piece of text.

这话说得真绕弯儿.
Using Emacs as a Server

For instance, version control programs invoke an editor to enter version control logs (see Version Control), and the Unix mail utility invokes an editor to enter a message to send. By convention, your choice of editor is specified by the environment variable EDITOR. If you setEDITOR to ‘emacs’, Emacs would be invoked, but in an inconvenient way—by starting a new Emacs process. This is inconvenient because the new Emacs process doesn’t share buffers, a command history, or other kinds of information with any existing Emacs process.

You can solve this problem by setting up Emacs as an edit server, so that it “listens” for external edit requests and acts accordingly. There are various ways to start an Emacs server:

  • Run the command server-start in an existing Emacs process: either type M-x server-start, or put the expression (server-start) in your init file (see Init File). The existing Emacs process is the server; when you exit Emacs, the server dies with the Emacs process.

  • Run Emacs as a daemon, using one of the ‘–daemon’ command-line options. See Initial Options. When Emacs is started this way, it calls server-start after initialization and does not open an initial frame. It then waits for edit requests from clients.

  • If your operating system uses systemd to manage startup, you can automatically start Emacs in daemon mode when you login using the supplied systemd unit file. To activate this:

    1
    2
    systemctl --user enable emacs
    # 此方法不可行.

    (If your Emacs was installed into a non-standard location, you may need to copy the emacs.service file to a standard directory such as ~/.config/systemd/user/.)

  • An external process can invoke the Emacs server when a connection event occurs upon a specified socket and pass the socket to the new Emacs server process. An instance of this is the socket functionality of systemd: the systemd service creates a socket and listens for connections on it; when emacsclient connects to it for the first time, systemd can launch the Emacs server and hand over the socket to it for servicing emacsclient connections. A setup to use this functionality could be:

    ~/.config/systemd/user/emacs.socket:

    1
    2
    3
    4
    [Socket]
    ListenStream=/path/to/.emacs.socket
    [Install]
    WantedBy=sockets.target

    (The emacs.service file described above must also be installed.)

    The ListenStream path will be the path that Emacs listens for connections from emacsclient; this is a file of your choice.

Once an Emacs server is started, you can use a shell command called emacsclient to connect to the Emacs process and tell it to visit a file. You can then set the EDITOR environment variable to ‘emacsclient’, so that external programs will use the existing Emacs process for editing.1

You can run multiple Emacs servers on the same machine by giving each one a unique server name, using the variable server-name. For example, M-x set-variable server-name “foo” sets the server name to ‘foo’. The emacsclient program can specify a server by name, using the ‘-s’ or the ‘-f’ option (see emacsclient Options), depending on whether or not the server uses a TCP socket (see TCP Emacs server).

If you want to run multiple Emacs daemons (see Initial Options), you can give each daemon its own server name like this:

1
emacs --daemon=foo

If you have defined a server by a unique server name, it is possible to connect to the server from another Emacs instance and evaluate Lisp expressions on the server, using the server-eval-at function. For instance, (server-eval-at "foo" '(+ 1 2)) evaluates the expression (+ 1 2) on the ‘foo’ server, and returns 3. (If there is no server with that name, an error is signaled.) Currently, this feature is mainly useful for developers.

  • TCP Emacs server: Listening to a TCP socket.
  • Invoking emacsclient: Connecting to the Emacs server.
  • emacsclient Options: Emacs client startup options.

39.1 TCP Emacs server

An Emacs server usually listens to connections on a local Unix domain socket. Some operating systems, such as MS-Windows, do not support local sockets; in that case, the server uses TCP sockets instead. In some cases it is useful to have the server listen on a TCP socket even if local sockets are supported, e.g., if you need to contact the Emacs server from a remote machine. You can set server-use-tcp to non-nil to have Emacs listen on a TCP socket instead of a local socket. This is the default if your OS does not support local sockets.

If the Emacs server is set to use TCP, it will by default listen on a random port on the localhost interface. This can be changed to another interface and/or a fixed port using the variables server-host and server-port.

A TCP socket is not subject to file system permissions. To retain some control over which users can talk to an Emacs server over TCP sockets, the emacsclient program must send an authorization key to the server. This key is normally randomly generated by the Emacs server. This is the recommended mode of operation.

If needed, you can set the authorization key to a static value by setting the server-auth-key variable. The key must consist of 64 ASCII printable characters except for space (this means characters from ‘!’ to ‘~’, or from decimal code 33 to 126). You can use M-x server-generate-key to get a random key.

When you start a TCP Emacs server, Emacs creates a server file containing the TCP information to be used by emacsclient to connect to the server. The variable server-auth-dirspecifies the default directory containing the server file; by default, this is ~/.emacs.d/server/. In the absence of a local socket with file permissions, the permissions of this directory determine which users can have their emacsclient processes talk to the Emacs server. If server-name is an absolute file name, the server file is created where specified by that file name.

To tell emacsclient to connect to the server over TCP with a specific server file, use the ‘-f’ or ‘–server-file’ option, or set the EMACS_SERVER_FILE environment variable (see emacsclient Options). If server-auth-dir is set to a non-standard value, or if server-name is set to an absolute file name, emacsclient needs an absolute file name to the server file, as the default server-auth-dir is hard-coded in emacsclient to be used as the directory for resolving relative filenames.

39.2 Invoking emacsclient

The simplest way to use the emacsclient program is to run the shell command ‘emacsclient file’, where file is a file name. This connects to an Emacs server, and tells that Emacs process to visit file in one of its existing frames—either a graphical frame, or one in a text terminal (see Frames). You can then select that frame to begin editing.

If there is no Emacs server, the emacsclient program halts with an error message (you can prevent this from happening by using the ‘–alternate-editor=””’ option to emacsclient, see emacsclient Options). If the Emacs process has no existing frame—which can happen if it was started as a daemon (see Emacs Server)—then Emacs opens a frame on the terminal in which you called emacsclient.

You can also force emacsclient to open a new frame on a graphical display using the ‘-c’ option, or on a text terminal using the ‘-t’ option. See emacsclient Options.

If you are running on a single text terminal, you can switch between emacsclient’s shell and the Emacs server using one of two methods: (i) run the Emacs server and emacsclienton different virtual terminals, and switch to the Emacs server’s virtual terminal after calling emacsclient; or (ii) call emacsclient from within the Emacs server itself, using Shell mode (see Interactive Shell) or Term mode (see Term Mode); emacsclient blocks only the subshell under Emacs, and you can still use Emacs to edit the file.

When you finish editing file in the Emacs server, type C-x # (server-edit) in its buffer. This saves the file and sends a message back to the emacsclient program, telling it to exit. Programs that use EDITOR usually wait for the editor—in this case emacsclient—to exit before doing something else.

You can also call emacsclient with multiple file name arguments: ‘emacsclient file1 file2 …’ tells the Emacs server to visit file1, file2, and so forth. Emacs selects the buffer visiting file1, and buries the other buffers at the bottom of the buffer list (see Buffers). The emacsclient program exits once all the specified files are finished (i.e., once you have typed C-x # in each server buffer).

Finishing with a server buffer also kills the buffer, unless it already existed in the Emacs session before the server was asked to create it. However, if you set server-kill-new-buffers to nil, then a different criterion is used: finishing with a server buffer kills it if the file name matches the regular expression server-temp-file-regexp. This is set up to distinguish certain temporary files.

Each C-x # checks for other pending external requests to edit various files, and selects the next such file. You can switch to a server buffer manually if you wish; you don’t have to arrive at it with C-x #. But C-x # is the way to tell emacsclient that you are finished.

If you set the value of the variable server-window to a window or a frame, C-x # always displays the next server buffer in that window or in that frame.

39.3 emacsclient Options

You can pass some optional arguments to the emacsclient program, such as:

1
emacsclient -c +12 file1 +4:3 file2

The ‘+line’ or ‘+line:column’ arguments specify line numbers, or line and column numbers, for the next file argument. These behave like the command line arguments for Emacs itself. See Action Arguments.

The other optional arguments recognized by emacsclient are listed below:

  • ‘-a command’

  • ‘–alternate-editor=command’

    Specify a shell command to run if emacsclient fails to contact Emacs. This is useful when running emacsclient in a script. The command may include arguments, which may be quoted “like this”. Currently, escaping of quotes is not supported.As a special exception, if command is the empty string, then emacsclient starts Emacs in daemon mode (as ‘emacs –daemon’) and then tries connecting again.The environment variable ALTERNATE_EDITOR has the same effect as the ‘-a’ option. If both are present, the latter takes precedence.

  • ‘-c’

  • ‘–create-frame’

    Create a new graphical client frame, instead of using an existing Emacs frame. See below for the special behavior of C-x C-c in a client frame. If Emacs cannot create a new graphical frame (e.g., if it cannot connect to the X server), it tries to create a text terminal client frame, as though you had supplied the ‘-t’ option instead.On MS-Windows, a single Emacs session cannot display frames on both graphical and text terminals, nor on multiple text terminals. Thus, if the Emacs server is running on a text terminal, the ‘-c’ option, like the ‘-t’ option, creates a new frame in the server’s current text terminal. See Windows Startup.If you omit a filename argument while supplying the ‘-c’ option, the new frame displays the scratch buffer by default. You can customize this behavior with the variable initial-buffer-choice (see Entering Emacs).

  • ‘-F alist’

  • ‘–frame-parameters=alist’

    Set the parameters for a newly-created graphical frame (see Frame Parameters).

  • ‘-d display’

  • ‘–display=display’

    Tell Emacs to open the given files on the X display display (assuming there is more than one X display available).

  • ‘-e’

  • ‘–eval’

    Tell Emacs to evaluate some Emacs Lisp code, instead of visiting some files. When this option is given, the arguments to emacsclient are interpreted as a list of expressions to evaluate, not as a list of files to visit.

  • ‘-f server-file’

  • ‘–server-file=server-file’

    Specify a server file (see TCP Emacs server) for connecting to an Emacs server via TCP. Alternatively, you can set the EMACS_SERVER_FILE environment variable to point to the server file. (The command-line option overrides the environment variable.)An Emacs server usually uses a local socket to listen for connections, but also supports connections over TCP. To connect to a TCP Emacs server, emacsclient needs to read a server file containing the connection details of the Emacs server. The name of this file is specified with this option, either as a file name relative to ~/.emacs.d/server or as an absolute file name. See TCP Emacs server.

  • ‘-n’

  • ‘–no-wait’

    Let emacsclient exit immediately, instead of waiting until all server buffers are finished. You can take as long as you like to edit the server buffers within Emacs, and they are not killed when you type C-x # in them.

  • ‘–parent-id id’

    Open an emacsclient frame as a client frame in the parent X window with id id, via the XEmbed protocol. Currently, this option is mainly useful for developers.

  • ‘-q’

  • ‘–quiet’

    Do not let emacsclient display messages about waiting for Emacs or connecting to remote server sockets.

  • ‘-u’

  • ‘–suppress-output’

    Do not let emacsclient display results returned from the server. Mostly useful in combination with ‘-e’ when the evaluation performed is for side-effect rather than result.

  • ‘-s server-name’

  • ‘–socket-name=server-name’

    Connect to the Emacs server named server-name. (This option is not supported on MS-Windows.) The server name is given by the variable server-name on the Emacs server. If this option is omitted, emacsclient connects to the first server it finds. If you set server-name of the Emacs server to an absolute file name, give the same absolute file name as server-name to this option to instruct emacsclient to connect to that server.

  • ‘-t’

  • ‘–tty’

  • ‘-nw’

    Create a new client frame on the current text terminal, instead of using an existing Emacs frame. This behaves just like the ‘-c’ option, described above, except that it creates a text terminal frame (see Non-Window Terminals).On MS-Windows, ‘-t’ behaves just like ‘-c’ if the Emacs server is using the graphical display, but if the Emacs server is running on a text terminal, it creates a new frame in the current text terminal.

  • ‘-T tramp-prefix’

  • ‘–tramp-prefix=tramp-prefix’

    Set the prefix to add to filenames for Emacs to locate files on remote machines (see Remote Files) using TRAMP (see The Tramp Manual). This is mostly useful in combination with using the Emacs server over TCP (see TCP Emacs server). By ssh-forwarding the listening port and making the server-file available on a remote machine, programs on the remote machine can use emacsclient as the value for the EDITOR and similar environment variables, but instead of talking to an Emacs server on the remote machine, the files will be visited in the local Emacs session using TRAMP.Setting the environment variable EMACSCLIENT_TRAMP has the same effect as using the ‘-T’ option. If both are specified, the command-line option takes precedence.For example, assume two hosts, ‘local’ and ‘remote’, and that the local Emacs listens on tcp port 12345. Assume further that /home is on a shared file system, so that the server file ~/.emacs.d/server/server is readable on both hosts.

    1
    2
    3
    4
    5
    local$ ssh -R12345:localhost:12345 remote
    remote$ export EDITOR="emacsclient \
    --server-file=server \
    --tramp=/ssh:remote:"
    remote$ $EDITOR /tmp/foo.txt #Should open in local emacs.

The new graphical or text terminal frames created by the ‘-c’ or ‘-t’ options are considered client frames. Any new frame that you create from a client frame is also considered a client frame. If you type C-x C-c (save-buffers-kill-terminal) in a client frame, that command does not kill the Emacs session as it normally does (see Exiting). Instead, Emacs deletes the client frame; furthermore, if the client frame has an emacsclient waiting to regain control (i.e., if you did not supply the ‘-n’ option), Emacs deletes all other frames of the same client, and marks the client’s server buffers as finished, as though you had typed C-x # in all of them. If it so happens that there are no remaining frames after the client frame(s) are deleted, the Emacs session exits.

As an exception, when Emacs is started as a daemon, all frames are considered client frames, and C-x C-c never kills Emacs. To kill a daemon session, type M-x kill-emacs.

Note that the ‘-t’ and ‘-n’ options are contradictory: ‘-t’ says to take control of the current text terminal to create a new client frame, while ‘-n’ says not to take control of the text terminal. If you supply both options, Emacs visits the specified files(s) in an existing frame rather than a new client frame, negating the effect of ‘-t’.

40 Printing Hard Copies

Device的部分.

Emacs provides commands for printing hardcopies of either an entire buffer or part of one. You can invoke the printing commands directly, as detailed below, or using the ‘File’ menu on the menu bar.

Aside from the commands described in this section, you can also print hardcopies from Dired (see Operating on Files) and the diary (see Displaying the Diary). You can also “print” an Emacs buffer to HTML with the command M-x htmlfontify-buffer, which converts the current buffer to a HTML file, replacing Emacs faces with CSS-based markup. Furthermore, Org mode allows you to print Org files to a variety of formats, such as PDF (see Org Mode).

  • M-x print-buffer

    Print hardcopy of current buffer with page headings containing the file name and page number.

  • M-x lpr-buffer

    Print hardcopy of current buffer without page headings.

  • M-x print-region

    Like print-buffer but print only the current region.

  • M-x lpr-region

    Like lpr-buffer but print only the current region.

On most operating systems, the above hardcopy commands submit files for printing by calling the lpr program. To change the printer program, customize the variable lpr-command. To specify extra switches to give the printer program, customize the list variable lpr-switches. Its value should be a list of option strings, each of which should start with ‘-’ (e.g., the option string "-w80" specifies a line width of 80 columns). The default is the empty list, nil.

To specify the printer to use, set the variable printer-name. The default, nil, specifies the default printer. If you set it to a printer name (a string), that name is passed to lpr with the ‘-P’ switch; if you are not using lpr, you should specify the switch with lpr-printer-switch.

The variable lpr-headers-switches similarly specifies the extra switches to use to make page headers. The variable lpr-add-switches controls whether to supply ‘-T’ and ‘-J’ options (suitable for lpr) to the printer program: nil means don’t add them (this should be the value if your printer program is not compatible with lpr).

  • PostScript: Printing buffers or regions as PostScript.
  • PostScript Variables: Customizing the PostScript printing commands.
  • Printing

41 Sorting Text

Emacs provides several commands for sorting text in the buffer. All operate on the contents of the region. They divide the text of the region into many sort records, identify a sort key for each record, and then reorder the records into the order determined by the sort keys. The records are ordered so that their keys are in alphabetical order, or, for numeric sorting, in numeric order. In alphabetic sorting, all upper-case letters ‘A’ through ‘Z’ come before lower-case ‘a’, in accordance with the ASCII character sequence (but sort-fold-case, described below, can change that).

The various sort commands differ in how they divide the text into sort records and in which part of each record is used as the sort key. Most of the commands make each line a separate sort record, but some commands use paragraphs or pages as sort records. Most of the sort commands use each entire sort record as its own sort key, but some use only a portion of the record as the sort key.

  • M-x sort-lines

    Divide the region into lines, and sort by comparing the entire text of a line. A numeric argument means sort into descending order.

  • M-x sort-paragraphs

    Divide the region into paragraphs, and sort by comparing the entire text of a paragraph (except for leading blank lines). A numeric argument means sort into descending order.

  • M-x sort-pages

    Divide the region into pages, and sort by comparing the entire text of a page (except for leading blank lines). A numeric argument means sort into descending order.

  • M-x sort-fields

    Divide the region into lines, and sort by comparing the contents of one field in each line. Fields are defined as separated by whitespace, so the first run of consecutive non-whitespace characters in a line constitutes field 1, the second such run constitutes field 2, etc.Specify which field to sort by with a numeric argument: 1 to sort by field 1, etc.; the default is 1. A negative argument means count fields from the right instead of from the left; thus, minus 1 means sort by the last field. If several lines have identical contents in the field being sorted, they keep the same relative order that they had in the original buffer.

  • M-x sort-numeric-fields

    Like M-x sort-fields except the specified field is converted to an integer for each line, and the numbers are compared. ‘10’ comes before ‘2’ when considered as text, but after it when considered as a number. By default, numbers are interpreted according to sort-numeric-base, but numbers beginning with ‘0x’ or ‘0’ are interpreted as hexadecimal and octal, respectively.

  • M-x sort-columns

    Like M-x sort-fields except that the text within each line used for comparison comes from a fixed range of columns. With a prefix argument, sort in reverse order. See below for more details on this command.

  • M-x reverse-region

    Reverse the order of the lines in the region. This is useful for sorting into descending order by fields, since those sort commands do not have a feature for doing that.

For example, if the buffer contains this:

1
2
3
4
5
On systems where clash detection (locking of files being edited) is
implemented, Emacs also checks the first time you modify a buffer
whether the file has changed on disk since it was last visited or
saved. If it has, you are asked to confirm that you want to change
the buffer.

applying M-x sort-lines to the entire buffer produces this:

1
2
3
4
5
On systems where clash detection (locking of files being edited) is
implemented, Emacs also checks the first time you modify a buffer
saved. If it has, you are asked to confirm that you want to change
the buffer.
whether the file has changed on disk since it was last visited or

where the upper-case ‘O’ sorts before all lower-case letters. If you use C-u 2 M-x sort-fields instead, you get this:

1
2
3
4
5
implemented, Emacs also checks the first time you modify a buffer
saved. If it has, you are asked to confirm that you want to change
the buffer.
On systems where clash detection (locking of files being edited) is
whether the file has changed on disk since it was last visited or

where the sort keys were ‘Emacs’, ‘If’, ‘buffer’, ‘systems’ and ‘the’.

M-x sort-columns requires more explanation. You specify the columns by putting point at one of the columns and the mark at the other column. Because this means you cannot put point or the mark at the beginning of the first line of the text you want to sort, this command uses an unusual definition of “region”: all of the line point is in is considered part of the region, and so is all of the line the mark is in, as well as all the lines in between.

For example, to sort a table by information found in columns 10 to 15, you could put the mark on column 10 in the first line of the table, and point on column 15 in the last line of the table, and then run sort-columns. Equivalently, you could run it with the mark on column 15 in the first line and point on column 10 in the last line.

This can be thought of as sorting the rectangle specified by point and the mark, except that the text on each line to the left or right of the rectangle moves along with the text inside the rectangle. See Rectangles.

Many of the sort commands ignore case differences when comparing, if sort-fold-case is non-nil.

42 Editing Pictures

To edit a picture made out of text characters (for example, a picture of the division of a register into fields, as a comment in a program), use the command M-x picture-mode to enter Picture mode.

In Picture mode, editing is based on the quarter-plane model of text, according to which the text characters lie studded on an area that stretches infinitely far to the right and downward. The concept of the end of a line does not exist in this model; the most you can say is where the last nonblank character on the line is found.

Of course, Emacs really always considers text as a sequence of characters, and lines really do have ends. But Picture mode replaces the most frequently-used commands with variants that simulate the quarter-plane model of text. They do this by inserting spaces or by converting tabs to spaces.

Most of the basic editing commands of Emacs are redefined by Picture mode to do essentially the same thing but in a quarter-plane way. In addition, Picture mode defines various keys starting with the C-c prefix to run special picture editing commands.

One of these keys, C-c C-c, is particularly important. Often a picture is part of a larger file that is usually edited in some other major mode. Picture mode records the name of the previous major mode so you can use the C-c C-c command (picture-mode-exit) later to go back to that mode. C-c C-c also deletes spaces from the ends of lines, unless given a numeric argument.

The special commands of Picture mode all work in other modes (provided the picture library is loaded), but are not bound to keys except in Picture mode. The descriptions below talk of moving “one column” and so on, but all the picture mode commands handle numeric arguments as their normal equivalents do.

Turning on Picture mode runs the hook picture-mode-hook. Additional extensions to Picture mode can be found in artist.el.

  • Basic Picture: Basic concepts and simple commands of Picture Mode.
  • Insert in Picture: Controlling direction of cursor motion after self-inserting characters.
  • Tabs in Picture: Various features for tab stops and indentation.
  • Rectangles in Picture: Clearing and superimposing rectangles.

43 Editing Binary Files

There is a special major mode for editing binary files: Hexl mode. To use it, use M-x hexl-find-file instead of C-x C-f to visit the file. This command converts the file’s contents to hexadecimal and lets you edit the translation. When you save the file, it is converted automatically back to binary.

You can also use M-x hexl-mode to translate an existing buffer into hex. This is useful if you visit a file normally and then discover it is a binary file.

Ordinary text characters overwrite in Hexl mode. This is to reduce the risk of accidentally spoiling the alignment of data in the file. There are special commands for insertion. Here is a list of the commands of Hexl mode:

  • C-M-d

    Insert a byte with a code typed in decimal.

  • C-M-o

    Insert a byte with a code typed in octal.

  • C-M-x

    Insert a byte with a code typed in hex.

  • C-x [

    Move to the beginning of a 1k-byte page.

  • C-x ]

    Move to the end of a 1k-byte page.

  • M-g

    Move to an address specified in hex.

  • M-j

    Move to an address specified in decimal.

  • C-c C-c

    Leave Hexl mode, going back to the major mode this buffer had before you invoked hexl-mode.

Other Hexl commands let you insert strings (sequences) of binary bytes, move by shorts or ints, etc.; type C-h a hexl- for details.

44 Saving Emacs Sessions

Use the desktop library to save the state of Emacs from one session to another. Once you save the Emacs desktop—the buffers, their file names, major modes, buffer positions, and so on—then subsequent Emacs sessions reload the saved desktop. By default, the desktop also tries to save the frame and window configuration. To disable this, set desktop-restore-frames to nil. (See that variable’s documentation for some related options that you can customize to fine-tune this behavior.)

Information about buffers visiting remote files is not saved by default. Customize the variable desktop-files-not-to-save to change this.

When the desktop restores the frame and window configuration, it uses the recorded values of frame parameters, disregarding any settings for those parameters you have in your init file (see Init File). This means that frame parameters such as fonts and faces for the restored frames will come from the desktop file, where they were saved when you exited your previous Emacs session; any settings for those parameters in your init file will be ignored. To disable this, customize the value of frameset-filter-alist to filter out the frame parameters you don’t want to be restored.

You can save the desktop manually with the command M-x desktop-save. You can also enable automatic saving of the desktop when you exit Emacs, and automatic restoration of the last saved desktop when Emacs starts: use the Customization buffer (see Easy Customization) to set desktop-save-mode to t for future sessions, or add this line in your init file (see Init File):

1
(desktop-save-mode 1)

If you turn on desktop-save-mode in your init file, then when Emacs starts, it looks for a saved desktop in the current directory. (More precisely, it looks in the directories specified by desktop-path, and uses the first desktop it finds.) Thus, you can have separate saved desktops in different directories, and the starting directory determines which one Emacs reloads. You can save the current desktop and reload one saved in another directory by typing M-x desktop-change-dir. Typing M-x desktop-revert reverts to the desktop previously reloaded.

Specify the option ‘–no-desktop’ on the command line when you don’t want it to reload any saved desktop. This turns off desktop-save-mode for the current session. Starting Emacs with the ‘–no-init-file’ option also disables desktop reloading, since it bypasses the init file, where desktop-save-mode is usually turned on.

By default, all the buffers in the desktop are restored in one go. However, this may be slow if there are a lot of buffers in the desktop. You can specify the maximum number of buffers to restore immediately with the variable desktop-restore-eager; the remaining buffers are restored lazily, when Emacs is idle.

Type M-x desktop-clear to empty the Emacs desktop. This kills all buffers except for internal ones, and clears the global variables listed in desktop-globals-to-clear. If you want this to preserve certain buffers, customize the variable desktop-clear-preserve-buffers-regexp, whose value is a regular expression matching the names of buffers not to kill.

If you want to save minibuffer history from one session to another, use the savehist library.

While Emacs runs with desktop-save-mode turned on, it by default auto-saves the desktop whenever any of it changes. The variable desktop-auto-save-timeout determines how frequently Emacs checks for modifications to your desktop.

The file in which Emacs saves the desktop is locked while the session runs, to avoid inadvertently overwriting it from another Emacs session. That lock is normally removed when Emacs exits, but if Emacs or your system crashes, the lock stays, and when you restart Emacs, it will by default ask you whether to use the locked desktop file. You can avoid the question by customizing the variable desktop-load-locked-desktop to either nil, which means never load the desktop in this case, or t, which means load the desktop without asking.

When Emacs starts in daemon mode, it cannot ask you any questions, so if it finds the desktop file locked, it will not load it, unless desktop-load-locked-desktop is t. Note that restoring the desktop in daemon mode is somewhat problematic for other reasons: e.g., the daemon cannot use GUI features, so parameters such as frame position, size, and decorations cannot be restored. For that reason, you may wish to delay restoring the desktop in daemon mode until the first client connects, by calling desktop-read in a hook function that you add to after-make-frame-functions (see Creating Frames).

45 Recursive Editing Levels

A recursive edit is a situation in which you are using Emacs commands to perform arbitrary editing while in the middle of another Emacs command. For example, when you type C-rinside of a query-replace, you enter a recursive edit in which you can change the current buffer. On exiting from the recursive edit, you go back to the query-replace. See Query Replace.

Exiting the recursive edit means returning to the unfinished command, which continues execution. The command to exit is C-M-c (exit-recursive-edit).

You can also abort the recursive edit. This is like exiting, but also quits the unfinished command immediately. Use the command C-] (abort-recursive-edit) to do this. See Quitting.

The mode line shows you when you are in a recursive edit by displaying square brackets around the parentheses that always surround the major and minor mode names. Every window’s mode line shows this in the same way, since being in a recursive edit is true of Emacs as a whole rather than any particular window or buffer.

It is possible to be in recursive edits within recursive edits. For example, after typing C-r in a query-replace, you may type a command that enters the debugger. This begins a recursive editing level for the debugger, within the recursive editing level for C-r. Mode lines display a pair of square brackets for each recursive editing level currently in progress.

Exiting the inner recursive edit (such as with the debugger c command) resumes the command running in the next level up. When that command finishes, you can then use C-M-c to exit another recursive editing level, and so on. Exiting applies to the innermost level only. Aborting also gets out of only one level of recursive edit; it returns immediately to the command level of the previous recursive edit. If you wish, you can then abort the next recursive editing level.

Alternatively, the command M-x top-level aborts all levels of recursive edits, returning immediately to the top-level command reader. It also exits the minibuffer, if it is active.

The text being edited inside the recursive edit need not be the same text that you were editing at top level. It depends on what the recursive edit is for. If the command that invokes the recursive edit selects a different buffer first, that is the buffer you will edit recursively. In any case, you can switch buffers within the recursive edit in the normal manner (as long as the buffer-switching keys have not been rebound). You could probably do all the rest of your editing inside the recursive edit, visiting files and all. But this could have surprising effects (such as stack overflow) from time to time. So remember to exit or abort the recursive edit when you no longer need it.

In general, we try to minimize the use of recursive editing levels in GNU Emacs. This is because they constrain you to go back in a particular order—from the innermost level toward the top level. When possible, we present different activities in separate buffers so that you can switch between them as you please. Some commands switch to a new major mode which provides a command to switch back. These approaches give you more flexibility to go back to unfinished tasks in the order you choose.

46 Hyperlinking and Web Navigation Features

The following subsections describe convenience features for handling URLs and other types of links occurring in Emacs buffer text.

  • EWW: A web browser in Emacs.
  • Embedded WebKit Widgets: Embedding browser widgets in Emacs buffers.
  • Browse-URL: Following URLs.
  • Goto Address mode: Activating URLs.
  • FFAP: Finding files etc. at point.

47 Games and Other Amusements

The animate package makes text dance (e.g., M-x animate-birthday-present).

M-x blackbox, M-x mpuz and M-x 5x5 are puzzles. blackbox challenges you to determine the location of objects inside a box by tomography. mpuz displays a multiplication puzzle with letters standing for digits in a code that you must guess—to guess a value, type a letter and then the digit you think it stands for. The aim of 5x5 is to fill in all the squares.

M-x bubbles is a game in which the object is to remove as many bubbles as you can in the smallest number of moves.

M-x decipher helps you to cryptanalyze a buffer which is encrypted in a simple monoalphabetic substitution cipher.

M-x dissociated-press scrambles the text in the current Emacs buffer, word by word or character by character, writing its output to a buffer named Dissociation. A positive argument tells it to operate character by character, and specifies the number of overlap characters. A negative argument tells it to operate word by word, and specifies the number of overlap words. Dissociated Press produces results fairly like those of a Markov chain, but is however, an independent, ignoriginal invention; it techniquitously copies several consecutive characters from the sample text between random jumps, unlike a Markov chain which would jump randomly after each word or character. Keep dissociwords out of your documentation, if you want it to be well userenced and properbose.

M-x dunnet runs a text-based adventure game.

If you want a little more personal involvement, try M-x gomoku, which plays the game Go Moku with you.

If you are a little bit bored, you can try M-x hanoi. If you are considerably bored, give it a numeric argument. If you are very, very bored, try an argument of 9. Sit back and watch.

M-x life runs Conway’s Game of Life cellular automaton.

M-x morse-region converts the text in the region to Morse code; M-x unmorse-region converts it back. M-x nato-region converts the text in the region to NATO phonetic alphabet; M-x denato-region converts it back.

M-x pong, M-x snake and M-x tetris are implementations of the well-known Pong, Snake and Tetris games.

M-x solitaire plays a game of solitaire in which you jump pegs across other pegs.

The command M-x zone plays games with the display when Emacs is idle.

“Real Programmers” deploy M-x butterfly, which uses butterflies to flip a bit on the drive platter, see https://xkcd.com/378.

Finally, if you find yourself frustrated, try describing your problems to the famous psychotherapist Eliza. Just do M-x doctor. End each input by typing twice.

48 Emacs Lisp Packages

Emacs includes a facility that lets you easily download and install packages that implement additional features. Each package is a separate Emacs Lisp program, sometimes including other components such as an Info manual.

M-x list-packages brings up a buffer named Packages with a list of all packages. You can install or uninstall packages via this buffer. See Package Menu.

The command C-h P (describe-package) prompts for the name of a package, and displays a help buffer describing the attributes of the package and the features that it implements.

By default, Emacs downloads packages from a package archive maintained by the Emacs developers and hosted by the GNU project. Optionally, you can also download packages from archives maintained by third parties. See Package Installation.

For information about turning an Emacs Lisp program into an installable package, See Packaging.

  • Package Menu: Buffer for viewing and managing packages.
  • Package Installation: Options for package installation.
  • Package Files: Where packages are installed.

49 Customization

This chapter describes some simple methods to customize the behavior of Emacs.

Apart from the methods described here, see X Resources for information about using X resources to customize Emacs, and see Keyboard Macros for information about recording and replaying keyboard macros. Making more far-reaching and open-ended changes involves writing Emacs Lisp code; see Emacs Lisp.

  • Easy Customization: Convenient way to browse and change settings.
  • Variables: Many Emacs commands examine Emacs variables to decide what to do; by setting variables, you can control their functioning.
  • Key Bindings: The keymaps say what command each key runs. By changing them, you can redefine keys.
  • Init File: How to write common customizations in the initialization file.
  • Authentication: Keeping persistent authentication information.

49.4 The Emacs Initialization File

When Emacs is started, it normally tries to load a Lisp program from an initialization file, or init file for short. This file, if it exists, specifies how to initialize Emacs for you. Emacs looks for your init file using the filenames ~/.emacs, ~/.emacs.el, or ~/.emacs.d/init.el; you can choose to use any one of these three names (see Find Init). Here, ~/ stands for your home directory.

You can use the command line switch ‘-q’ to prevent loading your init file, and ‘-u’ (or ‘–user’) to specify a different user’s init file (see Initial Options).

There can also be a default init file, which is the library named default.el, found via the standard search path for libraries. The Emacs distribution contains no such library; your site may create one for local customizations. If this library exists, it is loaded whenever you start Emacs (except when you specify ‘-q’). But your init file, if any, is loaded first; if it setsinhibit-default-init non-nil, then default is not loaded.

Your site may also have a site startup file; this is named site-start.el, if it exists. Like default.el, Emacs finds this file via the standard search path for Lisp libraries. Emacs loads this library before it loads your init file. To inhibit loading of this library, use the option ‘–no-site-file’. See Initial Options. We recommend against using site-start.elfor changes that some users may not like. It is better to put them in default.el, so that users can more easily override them.

You can place default.el and site-start.el in any of the directories which Emacs searches for Lisp libraries. The variable load-path (see Lisp Libraries) specifies these directories. Many sites put these files in a subdirectory named site-lisp in the Emacs installation directory, such as /usr/local/share/emacs/site-lisp.

Byte-compiling your init file is not recommended (see Byte Compilation). It generally does not speed up startup very much, and often leads to problems when you forget to recompile the file. A better solution is to use the Emacs server to reduce the number of times you have to start Emacs (see Emacs Server). If your init file defines many functions, consider moving them to a separate (byte-compiled) file that you load in your init file.

If you are going to write actual Emacs Lisp programs that go beyond minor customization, you should read the Emacs Lisp Reference Manual. See Emacs Lisp.

  • Init Syntax: Syntax of constants in Emacs Lisp.
  • Init Examples: How to do some things with an init file.
  • Terminal Init: Each terminal type can have an init file.
  • Find Init: How Emacs finds the init file.
  • Init Non-ASCII: Using non-ASCII characters in an init file.

50 Quitting and Aborting

  • C-g

  • C- (MS-DOS only)

    Quit: cancel running or partially typed command.

  • C-]

    Abort innermost recursive editing level and cancel the command which invoked it (abort-recursive-edit).

  • Either quit or abort, whichever makes sense (keyboard-escape-quit).

  • M-x top-level

    Abort all recursive editing levels that are currently executing.

  • C-/

  • C-x u

  • C-_

    Cancel a previously made change in the buffer contents (undo).

There are two ways of canceling a command before it has finished: quitting with C-g, and aborting with C-] or M-x top-level. Quitting cancels a partially typed command, or one which is still running. Aborting exits a recursive editing level and cancels the command that invoked the recursive edit (see Recursive Edit).

Quitting with C-g is the way to get rid of a partially typed command, or a numeric argument that you don’t want. Furthermore, if you are in the middle of a command that is running, C-g stops the command in a relatively safe way. For example, if you quit out of a kill command that is taking a long time, either your text will all still be in the buffer, or it will all be in the kill ring, or maybe both. If the region is active, C-g deactivates the mark, unless Transient Mark mode is off (see Disabled Transient Mark). If you are in the middle of an incremental search, C-g behaves specially; it may take two successive C-g characters to get out of a search. See Incremental Search, for details.

On MS-DOS, the character C- serves as a quit character like C-g. The reason is that it is not feasible, on MS-DOS, to recognize C-g while a command is running, between interactions with the user. By contrast, it is feasible to recognize C- at all times. See MS-DOS Keyboard.

C-g works by setting the variable quit-flag to t the instant C-g is typed; Emacs Lisp checks this variable frequently, and quits if it is non-nil. C-g is only actually executed as a command if you type it while Emacs is waiting for input. In that case, the command it runs is keyboard-quit.

On a text terminal, if you quit with C-g a second time before the first C-g is recognized, you activate the emergency-escape feature and return to the shell. See Emergency Escape.

There are some situations where you cannot quit. When Emacs is waiting for the operating system to do something, quitting is impossible unless special pains are taken for the particular system call within Emacs where the waiting occurs. We have done this for the system calls that users are likely to want to quit from, but it’s possible you will encounter a case not handled. In one very common case—waiting for file input or output using NFS—Emacs itself knows how to quit, but many NFS implementations simply do not allow user programs to stop waiting for NFS when the NFS server is hung.

Aborting with C-] (abort-recursive-edit) is used to get out of a recursive editing level and cancel the command which invoked it. Quitting with C-g does not do this, and could not do this, because it is used to cancel a partially typed command within the recursive editing level. Both operations are useful. For example, if you are in a recursive edit and type C-u 8to enter a numeric argument, you can cancel that argument with C-g and remain in the recursive edit.

The sequence (keyboard-escape-quit) can either quit or abort. (We defined it this way because means “get out” in many PC programs.) It can cancel a prefix argument, clear a selected region, or get out of a Query Replace, like C-g. It can get out of the minibuffer or a recursive edit, like C-]. It can also get out of splitting the frame into multiple windows, as with C-x 1. One thing it cannot do, however, is stop a command that is running. That’s because it executes as an ordinary command, and Emacs doesn’t notice it until it is ready for the next command.

The command M-x top-level is equivalent to enough C-] commands to get you out of all the levels of recursive edits that you are in; it also exits the minibuffer if it is active. C-]gets you out one level at a time, but M-x top-level goes out all levels at once. Both C-] and M-x top-level are like all other commands, and unlike C-g, in that they take effect only when Emacs is ready for a command. C-] is an ordinary key and has its meaning only because of its binding in the keymap. See Recursive Edit.

C-/ (undo) is not strictly speaking a way of canceling a command, but you can think of it as canceling a command that already finished executing. See Undo, for more information about the undo facility.

2.Orgmode Document Strucure

Posted on 2019-05-22 | In linux - emacs - orgmode | Comments:

Org is an outliner. Outlines allow a document to be organized in a hierarchical structure, which, least for me, is the best representation of notes and thoughts. An overview of this structure is achieved by folding, i.e., hiding large parts of the document to show only the general document structure and the parts currently being worked on. Org greatly simplifies the use of outlines by compressing the entire show and hide functionalities into a single command, org-cycle, which is bound to the TAB key.

• Headlines: How to typeset Org tree headlines.
• Visibility Cycling: Show and hide, much simplified.
• Motion: Jumping to other headlines.
• Structure Editing: Changing sequence and level of headlines.
• Sparse Trees: Matches embedded in context.
• Plain Lists: Additional structure within an entry.
• Drawers: Tucking stuff away.
• Blocks: Folding blocks.
• Creating Footnotes: How footnotes are defined in Org’s syntax.

2.1 Headlines

最大的收获便是:
org-cycle-separator-lines 此功能可以控制.

Headlines define the structure of an outline tree. The headlines in Org start with one or more stars, on the left margin3. For example:

1
2
3
4
5
6
7
* Top level headline
** Second level
*** Third level
some text
*** Third level
more text
* Another top level headline

The name defined in org-footnote-section is reserved. Do not use it as a title for your own headings.

Some people find the many stars too noisy and would prefer an outline that has whitespace followed by a single star as headline starters. See Clean View.

An empty line after the end of a subtree is considered part of it and is hidden when the subtree is folded. However, if you leave at least two empty lines, one empty line remains visible after folding the subtree, in order to structure the collapsed view. See the variable org-cycle-separator-lines to modify this behavior.

See the variables org-special-ctrl-a/e, org-special-ctrl-k, and org-ctrl-k-protect-subtree to configure special behavior of C-a, C-e, and C-k in headlines. Note also that clocking only works with headings indented less than 30 stars.

2.2 Visibility Cycling

• Global and local cycling: Cycling through various visibility states.
• Initial visibility: Setting the initial visibility state.
• Catching invisible edits: Preventing mistakes when editing invisible parts.

2.2.1 Global and local cycling

Tab and S-Tab, 其余无关紧要.

Outlines make it possible to hide parts of the text in the buffer. Org uses just two commands, bound to TAB and S-TAB to change the visibility in the buffer.

  • TAB (org-cycle)

    Subtree cycling: Rotate current subtree among the states,

    1
    2
    3
    ,-> FOLDED -> CHILDREN -> SUBTREE --.
    '----------------------------------------------------'
    #有意思的一点, display的是subtree

    Point must be on a headline for this to work4.

  • S-TAB (org-global-cycle)

  • C-u TAB

    Global cycling: Rotate the entire buffer among the states,

    1
    2
    3
    ,-> OVERVIEW -> CONTENTS -> SHOW ALL --.
    '---------------------------------------------------------'
    #棒呀.

    When S-TAB is called with a numeric prefix argument N, the CONTENTS view up to headlines of level N are shown. Note that inside tables (see Tables), S-TAB jumps to the previous field instead.You can run global cycling using TAB only if point is at the very beginning of the buffer, but not on a headline, and org-cycle-global-at-bob is set to a non-nil value.

    前面两个足够, 后面的用不到.

  • C-u C-u TAB (org-set-startup-visibility)

    Switch back to the startup visibility of the buffer (see Initial visibility).

  • C-u C-u C-u TAB (outline-show-all)

    Show all, including drawers.

  • C-c C-r (org-reveal)

    Reveal context around point, showing the current entry, the following heading and the hierarchy above. Useful for working near a location that has been exposed by a sparse tree command (see Sparse Trees) or an agenda command (see Agenda Commands). With a prefix argument show, on each level, all sibling headings. With a double prefix argument, also show the entire subtree of the parent.

  • C-c C-k (outline-show-branches)

    Expose all the headings of the subtree, CONTENTS view for just one subtree.

  • C-c TAB (outline-show-children)

    Expose all direct children of the subtree. With a numeric prefix argument N, expose all children down to level N.

  • C-c C-x b (org-tree-to-indirect-buffer)

    Show the current subtree in an indirect buffer5. With a numeric prefix argument, N, go up to level N and then take that tree. If N is negative then go up that many levels. With a C-u prefix, do not remove the previously used indirect buffer.

  • C-c C-x v (org-copy-visible)

    Copy the visible text in the region into the kill ring.

  1. See, however, the option org-cycle-emulate-tab.
  2. The indirect buffer contains the entire buffer, but is narrowed to the current tree. Editing the indirect buffer also changes the original buffer, but without affecting visibility in that buffer. For more information about indirect buffers, see (emacs)GNU Emacs Manual.

2.2.2 Initial visibility

When Emacs first visits an Org file, the global state is set to OVERVIEW, i.e., only the top level headlines are visible6. This can be configured through the variable org-startup-folded, or on a per-file basis by adding one of the following lines anywhere in the buffer:

1
2
3
4
#+STARTUP: overview
#+STARTUP: content
#+STARTUP: showall
#+STARTUP: showeverything

Furthermore, any entries with a ‘VISIBILITY’ property (see Properties and Columns) get their visibility adapted accordingly. Allowed values for this property are ‘folded’, ‘children’, ‘content’, and ‘all’.

  • C-u C-u TAB (org-set-startup-visibility)

    Switch back to the startup visibility of the buffer, i.e., whatever is requested by startup options and ‘VISIBILITY’ properties in individual entries.

2.2.3 Catching invisible edits

Sometimes you may inadvertently edit an invisible part of the buffer and be confused on what has been edited and how to undo the mistake. Setting org-catch-invisible-edits to non-nil helps preventing this. See the docstring of this option on how Org should catch invisible edits and process them.

2.3 Motion

The following commands jump to other headlines in the buffer.

  • C-c C-n (outline-next-visible-heading)

    Next heading.

  • C-c C-p (outline-previous-visible-heading)

    Previous heading.

  • C-c C-f (org-forward-same-level)

    Next heading same level.

  • C-c C-b (org-backward-same-level)

    Previous heading same level.

  • C-c C-u (outline-up-heading)

    Backward to higher level heading.

  • C-c C-j (org-goto)

    Jump to a different place without changing the current outline visibility. Shows the document structure in a temporary buffer, where you can use the following keys to find your destination:TABCycle visibility.DOWN / nnnnnnnnUPNext/previous visible headline.RETSelect this location./Do a Sparse-tree searchThe following keys work if you turn off org-goto-auto-isearchn / pNext/previous visible headline.f / bNext/previous headline same level.uOne level up.0 … 9Digit argument.qQuit.See also the variable org-goto-interface.

没啥用, 不必要如此精确的操作.

2.4 Structure Editing

不必要, 最基本的操作可以解决问题.

  • M-RET (org-meta-return)

    Insert a new heading, item or row.If the command is used at the beginning of a line, and if there is a heading or a plain list item (see Plain Lists) at point, the new heading/item is created before the current line. When used at the beginning of a regular line of text, turn that line into a heading.When this command is used in the middle of a line, the line is split and the rest of the line becomes the new item or headline. If you do not want the line to be split, customize org-M-RET-may-split-line.Calling the command with a C-u prefix unconditionally inserts a new heading at the end of the current subtree, thus preserving its contents. With a double C-u C-u prefix, the new heading is created at the end of the parent subtree instead.

  • C-RET (org-insert-heading-respect-content)

    Insert a new heading at the end of the current subtree.

  • M-S-RET (org-insert-todo-heading)

    Insert new TODO entry with same level as current heading. See also the variable org-treat-insert-todo-heading-as-state-change.

  • C-S-RET (org-insert-todo-heading-respect-content)

    Insert new TODO entry with same level as current heading. Like C-RET, the new headline is inserted after the current subtree.

  • TAB (org-cycle)

    In a new entry with no text yet, the first TAB demotes the entry to become a child of the previous one. The next TAB makes it a parent, and so on, all the way to top level. Yet another TAB, and you are back to the initial level.

  • M-LEFT (org-do-promote)

    Promote current heading by one level.

  • M-RIGHT (org-do-demote)

    Demote current heading by one level.

  • M-S-LEFT (org-promote-subtree)

    Promote the current subtree by one level.

  • M-S-RIGHT (org-demote-subtree)

    Demote the current subtree by one level.

  • M-UP (org-move-subtree-up)

    Move subtree up, i.e., swap with previous subtree of same level.

  • M-DOWN (org-move-subtree-down)

    Move subtree down, i.e., swap with next subtree of same level.

  • C-c @ (org-mark-subtree)

    Mark the subtree at point. Hitting repeatedly marks subsequent subtrees of the same level as the marked subtree.

  • C-c C-x C-w (org-cut-subtree)

    Kill subtree, i.e., remove it from buffer but save in kill ring. With a numeric prefix argument N, kill N sequential subtrees.

  • C-c C-x M-w (org-copy-subtree)

    Copy subtree to kill ring. With a numeric prefix argument N, copy the N sequential subtrees.

  • C-c C-x C-y (org-paste-subtree)

    Yank subtree from kill ring. This does modify the level of the subtree to make sure the tree fits in nicely at the yank position. The yank level can also be specified with a numeric prefix argument, or by yanking after a headline marker like ‘**’.

  • C-y (org-yank)

    Depending on the variables org-yank-adjusted-subtrees and org-yank-folded-subtrees, Org’s internal yank command pastes subtrees folded and in a clever way, using the same command as C-c C-x C-y. With the default settings, no level adjustment takes place, but the yanked tree is folded unless doing so would swallow text previously visible. Any prefix argument to this command forces a normal yank to be executed, with the prefix passed along. A good way to force a normal yank is C-u C-y. If you use yank-pop after a yank, it yanks previous kill items plainly, without adjustment and folding.

  • C-c C-x c (org-clone-subtree-with-time-shift)

    Clone a subtree by making a number of sibling copies of it. You are prompted for the number of copies to make, and you can also specify if any timestamps in the entry should be shifted. This can be useful, for example, to create a number of tasks related to a series of lectures to prepare. For more details, see the docstring of the command org-clone-subtree-with-time-shift.

  • C-c C-w (org-refile)

    Refile entry or region to a different location. See Refile and Copy.

  • C-c ^ (org-sort)

    Sort same-level entries. When there is an active region, all entries in the region are sorted. Otherwise the children of the current headline are sorted. The command prompts for the sorting method, which can be alphabetically, numerically, by time—first timestamp with active preferred, creation time, scheduled time, deadline time—by priority, by TODO keyword—in the sequence the keywords have been defined in the setup—or by the value of a property. Reverse sorting is possible as well. You can also supply your own function to extract the sorting key. With a C-u prefix, sorting is case-sensitive.

  • C-x n s (org-narrow-to-subtree)

    Narrow buffer to current subtree.

  • C-x n b (org-narrow-to-block)

    Narrow buffer to current block.

  • C-x n w (widen)

    Widen buffer to remove narrowing.

  • C-c * (org-toggle-heading)

    Turn a normal line or plain list item into a headline—so that it becomes a subheading at its location. Also turn a headline into a normal line by removing the stars. If there is an active region, turn all lines in the region into headlines. If the first line in the region was an item, turn only the item lines into headlines. Finally, if the first line is a headline, remove the stars from all headlines in the region.

When there is an active region—i.e., when Transient Mark mode is active—promotion and demotion work on all headlines in the region. To select a region of headlines, it is best to place both point and mark at the beginning of a line, mark at the beginning of the first headline, and point at the line just after the last headline to change. Note that when point is inside a table (see Tables), the Meta-Cursor keys have different functionality.

2.5 Sparse Trees

An important feature of Org mode is the ability to construct sparse trees for selected information in an outline tree, so that the entire document is folded as much as possible, but the selected information is made visible along with the headline structure above it7. Just try it out and you will see immediately how it works.

Org mode contains several commands creating such trees, all these commands can be accessed through a dispatcher:

  • C-c / (org-sparse-tree)

    This prompts for an extra key to select a sparse-tree creating command.

  • C-c / r or C-c / / (org-occur)

    Prompts for a regexp and shows a sparse tree with all matches. If the match is in a headline, the headline is made visible. If the match is in the body of an entry, headline and body are made visible. In order to provide minimal context, also the full hierarchy of headlines above the match is shown, as well as the headline following the match. Each match is also highlighted; the highlights disappear when the buffer is changed by an editing command, or by pressing C-c C-c8. When called with a C-u prefix argument, previous highlights are kept, so several calls to this command can be stacked.

  • M-g n or M-g M-n (next-error)

    Jump to the next sparse tree match in this buffer.

  • M-g p or M-g M-p (previous-error) (M-g g就是go的含义)

    Jump to the previous sparse tree match in this buffer.

For frequently used sparse trees of specific search strings, you can use the variable org-agenda-custom-commands to define fast keyboard access to specific sparse trees. These commands will then be accessible through the agenda dispatcher (see Agenda Dispatcher). For example:

1
2
(setq org-agenda-custom-commands
'(("f" occur-tree "FIXME")))

defines the key f as a shortcut for creating a sparse tree matching the string ‘FIXME’.

The other sparse tree commands select headings based on TODO keywords, tags, or properties and are discussed later in this manual.

To print a sparse tree, you can use the Emacs command ps-print-buffer-with-faces which does not print invisible parts of the document. Or you can use the command C-c C-e v to export only the visible part of the document and print the resulting file.

  1. See also the variable org-show-context-detail to decide how much context is shown around each match.
  2. This depends on the option org-remove-highlights-with-change.

2.6 Plain Lists

关键的是几个转换的命令,
C-c C-* Turn全部, 尤其是checkbox, 日后将会常用

Within an entry of the outline tree, hand-formatted lists can provide additional structure. They also provide a way to create lists of checkboxes (see Checkboxes). Org supports editing such lists, and every exporter (see Exporting) can parse and format them.

Org knows ordered lists, unordered lists, and description lists.

  • Unordered list items start with ‘-’, ‘+’, or ‘*’9 as bullets.
  • Ordered list items start with a numeral followed by either a period or a right parenthesis10, such as ‘1.’ or ‘1)’11 If you want a list to start with a different value—e.g., 20—start the text of the item with ‘[@20]’12. Those constructs can be used in any item of the list in order to enforce a particular numbering.
  • Description list items are unordered list items, and contain the separator ‘::’ to distinguish the description term from the description.

Items belonging to the same list must have the same indentation on the first line. In particular, if an ordered list reaches number ‘10.’, then the 2-digit numbers must be written left-aligned with the other numbers in the list. An item ends before the next line that is less or equally indented than its bullet/number.

A list ends whenever every item has ended, which means before any line less or equally indented than items at top level. It also ends before two blank lines. In that case, all items are closed. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
* Lord of the Rings
My favorite scenes are (in this order)
1. The attack of the Rohirrim
2. Eowyn's fight with the witch king
+ this was already my favorite scene in the book
+ I really like Miranda Otto.
3. Peter Jackson being shot by Legolas
- on DVD only
He makes a really funny face when it happens.
But in the end, no individual scenes matter but the film as a whole.
Important actors in this film are:
- Elijah Wood :: He plays Frodo
- Sean Astin :: He plays Sam, Frodo's friend. I still remember him
very well from his role as Mikey Walsh in /The Goonies/.

Org supports these lists by tuning filling and wrapping commands to deal with them correctly, and by exporting them properly (see Exporting). Since indentation is what governs the structure of these lists, many structural constructs like ‘#+BEGIN_’ blocks can be indented to signal that they belong to a particular item.

If you find that using a different bullet for a sub-list—than that used for the current list-level—improves readability, customize the variable org-list-demote-modify-bullet. To get a greater difference of indentation between items and theirs sub-items, customize org-list-indent-offset.

The following commands act on items when point is in the first line of an item—the line with the bullet or number. Some of them imply the application of automatic rules to keep list structure intact. If some of these actions get in your way, configure org-list-automatic-rules to disable them individually.

  • TAB (org-cycle)

    Items can be folded just like headline levels. Normally this works only if point is on a plain list item. For more details, see the variable org-cycle-include-plain-lists. If this variable is set to integrate, plain list items are treated like low-level headlines. The level of an item is then given by the indentation of the bullet/number. Items are always subordinate to real headlines, however; the hierarchies remain completely separated. In a new item with no text yet, the first TAB demotes the item to become a child of the previous one. Subsequent TABs move the item to meaningful levels in the list and eventually get it back to its initial position.

  • M-RET (org-insert-heading)

    Insert new item at current level. With a prefix argument, force a new heading (see Structure Editing). If this command is used in the middle of an item, that item is split in two, and the second part becomes the new item13. If this command is executed before item’s body, the new item is created before the current one.

  • M-S-RET

    Insert a new item with a checkbox (see Checkboxes).

  • S-UP

  • S-DOWN

    Jump to the previous/next item in the current list, but only if org-support-shift-select is off14. If not, you can still use paragraph jumping commands like C-UP and C-DOWN to quite similar effect.

  • M-UP

  • M-DOWN

    Move the item including subitems up/down15, i.e., swap with previous/next item of same indentation. If the list is ordered, renumbering is automatic.

  • M-LEFT

  • M-RIGHT

    Decrease/increase the indentation of an item, leaving children alone.

  • M-S-LEFT

  • M-S-RIGHT

    Decrease/increase the indentation of the item, including subitems. Initially, the item tree is selected based on current indentation. When these commands are executed several times in direct succession, the initially selected region is used, even if the new indentation would imply a different hierarchy. To use the new hierarchy, break the command chain by moving point.As a special case, using this command on the very first item of a list moves the whole list. This behavior can be disabled by configuring org-list-automatic-rules. The global indentation of a list has no influence on the text after the list.

  • C-c C-c

    If there is a checkbox (see Checkboxes) in the item line, toggle the state of the checkbox. In any case, verify bullets and indentation consistency in the whole list.

  • C-c -

    Cycle the entire list level through the different itemize/enumerate bullets (‘-’, ‘+’, ‘*’, ‘1.’, ‘1)’) or a subset of them, depending on org-plain-list-ordered-item-terminator, the type of list, and its indentation. With a numeric prefix argument N, select the Nth bullet from this list. If there is an active region when calling this, selected text is changed into an item. With a prefix argument, all lines are converted to list items. If the first line already was a list item, any item marker is removed from the list. Finally, even without an active region, a normal line is converted into a list item.

  • C-c *

    Turn a plain list item into a headline—so that it becomes a subheading at its location. See Structure Editing, for a detailed explanation.

  • C-c C-*

    Turn the whole plain list into a subtree of the current heading. Checkboxes (see Checkboxes) become TODO, respectively DONE, keywords when unchecked, respectively checked.

  • S-LEFT

  • S-RIGHT

    This command also cycles bullet styles when point is in on the bullet or anywhere in an item line, details depending on org-support-shift-select.

  • C-c ^

    Sort the plain list. Prompt for the sorting method: numerically, alphabetically, by time, or by custom function.

2.7 Drawers

最重要的基本概念之一.

Sometimes you want to keep information associated with an entry, but you normally do not want to see it. For this, Org mode has drawers. They can contain anything but a headline and another drawer. Drawers look like this:

1
2
3
4
5
6
** This is a headline
Still outside the drawer
:DRAWERNAME:
This is inside the drawer.
:END:
After the drawer.

You can interactively insert a drawer at point by calling org-insert-drawer, which is bound to C-c C-x d. With an active region, this command puts the region inside the drawer. With a prefix argument, this command calls org-insert-property-drawer, which creates a ‘PROPERTIES’ drawer right below the current headline. Org mode uses this special drawer for storing properties (seeProperties and Columns). You cannot use it for anything else.

Completion over drawer keywords is also possible using M-TAB16.

Visibility cycling (see Visibility Cycling) on the headline hides and shows the entry, but keep the drawer collapsed to a single line. In order to look inside the drawer, you need to move point to the drawer line and press TAB there.

You can also arrange for state change notes (see Tracking TODO state changes) and clock times (see Clocking Work Time) to be stored in a ‘LOGBOOK’ drawer. If you want to store a quick note there, in a similar way to state changes, use

  • C-c C-z

    Add a time-stamped note to the ‘LOGBOOK’ drawer.

     手动插入便可.

## 2.8 Blocks

了解其formal概念是block即可.
文本编辑中的基本概念. 与HTML贯通起来.

Org mode uses ‘#+BEGIN’ … ‘#+END’ blocks for various purposes from including source code examples (see Literal Examples) to capturing time logging information (see Clocking Work Time). These blocks can be folded and unfolded by pressing TAB in the ‘#+BEGIN’ line. You can also get all blocks folded at startup by configuring the variable org-hide-block-startup or on a per-file basis by using

1
2
#+STARTUP: hideblocks
#+STARTUP: nohideblocks

2.9 Creating Footnotes

构建方式与markdown不同.

Org mode supports the creation of footnotes.

A footnote is started by a footnote marker in square brackets in column 0, no indentation allowed. It ends at the next footnote definition, headline, or after two consecutive empty lines. The footnote reference is simply the marker in square brackets, inside text. Markers always start with ‘fn:’. For example:

1
2
3
The Org homepage[fn:1] now looks a lot better than it used to.
...
[fn:1] The link is: https://orgmode.org

Org mode extends the number-based syntax to named footnotes and optional inline definition. Here are the valid references:

  • ‘[fn:NAME]’

    A named footnote reference, where NAME is a unique label word, or, for simplicity of automatic creation, a number.

  • ‘[fn:: This is the inline definition of this footnote]’

    A LaTeX-like anonymous footnote where the definition is given directly at the reference point.

  • ‘[fn:NAME: a definition]’

    An inline definition of a footnote, which also specifies a name for the note. Since Org allows multiple references to the same note, you can then use ‘[fn:NAME]’ to create additional references.

Footnote labels can be created automatically, or you can create names yourself. This is handled by the variable org-footnote-auto-label and its corresponding ‘STARTUP’ keywords. See the docstring of that variable for details.

The following command handles footnotes:

  • C-c C-x f

    The footnote action command.When point is on a footnote reference, jump to the definition. When it is at a definition, jump to the—first—reference.Otherwise, create a new footnote. Depending on the variable org-footnote-define-inline17, the definition is placed right into the text as part of the reference, or separately into the location determined by the variable org-footnote-section.When this command is called with a prefix argument, a menu of additional options is offered:sSort the footnote definitions by reference sequence.rRenumber the simple ‘fn:N’ footnotes.SShort for first r, then s action.nRename all footnotes into a ‘fn:1’ … ‘fn:n’ sequence.dDelete the footnote at point, including definition and references.Depending on the variable org-footnote-auto-adjust18, renumbering and sorting footnotes can be automatic after each insertion or deletion.

  • C-c C-c

    If point is on a footnote reference, jump to the definition. If it is at the definition, jump back to the reference. When called at a footnote location with a prefix argument, offer the same menu as C-c C-x f.

  • C-c C-o or mouse-1/2

    Footnote labels are also links to the corresponding definition or reference, and you can use the usual commands to follow these links.

7.Orgmode Properties and Columns

Posted on 2019-05-22 | In linux - emacs - orgmode | Comments:

A property is a key-value pair associated with an entry. Properties can be set so they are associated with a single entry, with every entry in a tree, or with every entry in an Org file.

There are two main applications for properties in Org mode. First, properties are like tags, but with a value. Imagine maintaining a file where you document bugs and plan releases for a piece of software. Instead of using tags like ‘release_1’, ‘release_2’, you can use a property, say ‘Release’, that in different subtrees has different values, such as ‘1.0’ or ‘2.0’. Second, you can use properties to implement (very basic) database capabilities in an Org buffer. Imagine keeping track of your music CDs, where properties could be things such as the album, artist, date of release, number of tracks, and so on.

Properties can be conveniently edited and viewed in column view (see Column View).

• Property Syntax: How properties are spelled out.
• Special Properties: Access to other Org mode features.
• Property Searches: Matching property values.
• Property Inheritance: Passing values down a tree.
• Column View: Tabular viewing and editing.

7.1 Property Syntax

这里先看一眼就完事.

Properties are key–value pairs. When they are associated with a single entry or with a tree they need to be inserted into a special drawer (see Drawers) with the name ‘PROPERTIES’, which has to be located right below a headline, and its planning line (see Deadlines and Scheduling) when applicable. Each property is specified on a single line, with the key—surrounded by colons—first, and the value after it. Keys are case-insensitive. Here is an example:

1
2
3
4
5
6
7
8
9
10
* CD collection
** Classic
*** Goldberg Variations
:PROPERTIES:
:Title: Goldberg Variations
:Composer: J.S. Bach
:Artist: Glenn Gould
:Publisher: Deutsche Grammophon
:NDisks: 1
:END:

Depending on the value of org-use-property-inheritance, a property set this way is associated either with a single entry, or with the sub-tree defined by the entry, see Property Inheritance.

You may define the allowed values for a particular property ‘Xyz’ by setting a property ‘Xyz_ALL’. This special property is inherited, so if you set it in a level 1 entry, it applies to the entire tree. When allowed values are defined, setting the corresponding property becomes easier and is less prone to typing errors. For the example with the CD collection, we can pre-define publishers and the number of disks in a box like this:

1
2
3
4
5
* CD collection
:PROPERTIES:
:NDisks_ALL: 1 2 3 4
:Publisher_ALL: "Deutsche Grammophon" Philips EMI
:END:

If you want to set properties that can be inherited by any entry in a file, use a line like:

1
#+PROPERTY: NDisks_ALL 1 2 3 4

If you want to add to the value of an existing property, append a ‘+’ to the property name. The following results in the property ‘var’ having the value ‘foo=1 bar=2’.

1
2
#+PROPERTY: var  foo=1
#+PROPERTY: var+ bar=2

It is also possible to add to the values of inherited properties. The following results in the ‘Genres’ property having the value ‘Classic Baroque’ under the ‘Goldberg Variations’ subtree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
* CD collection
** Classic
:PROPERTIES:
:Genres: Classic
:END:
*** Goldberg Variations
:PROPERTIES:
:Title: Goldberg Variations
:Composer: J.S. Bach
:Artist: Glenn Gould
:Publisher: Deutsche Grammophon
:NDisks: 1
:Genres+: Baroque
:END:

Note that a property can only have one entry per drawer.

Property values set with the global variable org-global-properties can be inherited by all entries in all Org files.

The following commands help to work with properties:

  • M-TAB (pcomplete)

    After an initial colon in a line, complete property keys. All keys used in the current file are offered as possible completions.

  • C-c C-x p (org-set-property)

    Set a property. This prompts for a property name and a value. If necessary, the property drawer is created as well.

  • C-u M-x org-insert-drawer

    Insert a property drawer into the current entry. The drawer is inserted early in the entry, but after the lines with planning information like deadlines.

  • C-c C-c (org-property-action)

    With point in a property drawer, this executes property commands.

  • C-c C-c s (org-set-property)

    Set a property in the current entry. Both the property and the value can be inserted using completion.

  • S-RIGHT (org-property-next-allowed-values)

  • S-LEFT (org-property-previous-allowed-value)

    Switch property at point to the next/previous allowed value.

  • C-c C-c d (org-delete-property)

    Remove a property from the current entry.

  • C-c C-c D (org-delete-property-globally)

    Globally remove a property, from all entries in the current file.

  • C-c C-c c (org-compute-property-at-point)

    Compute the property at point, using the operator and scope from the nearest column format definition.

7.2 Special Properties

reserved properties, 看一样便可,

Special properties provide an alternative access method to Org mode features, like the TODO state or the priority of an entry, discussed in the previous chapters. This interface exists so that you can include these states in a column view (see Column View), or to use them in queries. The following property names are special and should not be used as keys in the properties drawer:

‘ALLTAGS’ All tags, including inherited ones.
‘BLOCKED’ t if task is currently blocked by children or siblings.
‘CATEGORY’ The category of an entry.
‘CLOCKSUM’ The sum of CLOCK intervals in the subtree. org-clock-sum
must be run first to compute the values in the current buffer.
‘CLOCKSUM_T’ The sum of CLOCK intervals in the subtree for today.
org-clock-sum-today must be run first to compute the
values in the current buffer.
‘CLOSED’ When was this entry closed?
‘DEADLINE’ The deadline time string, without the angular brackets.
‘FILE’ The filename the entry is located in.
‘ITEM’ The headline of the entry.
‘PRIORITY’ The priority of the entry, a string with a single letter.
‘SCHEDULED’ The scheduling timestamp, without the angular brackets.
‘TAGS’ The tags defined directly in the headline.
‘TIMESTAMP’ The first keyword-less timestamp in the entry.
‘TIMESTAMP_IA’ The first inactive timestamp in the entry.
‘TODO’ The TODO keyword of the entry.

7.3 Property Searches

search是至关重要的一点.

To create sparse trees and special lists with selection based on properties, the same commands are used as for tag searches (see Tag Searches).

  • C-c / m or C-c \ (org-match-sparse-tree)

    Create a sparse tree with all matching entries. With a C-u prefix argument, ignore headlines that are not a TODO line.

  • M-x org-agenda m, org-tags-view

    Create a global list of tag/property matches from all agenda files.

  • M-x org-agenda M (org-tags-view)

    Create a global list of tag matches from all agenda files, but check only TODO items and force checking of subitems (see the option org-tags-match-list-sublevels).

The syntax for the search string is described in Matching tags and properties.

There is also a special command for creating sparse trees based on a single property:

  • C-c / p

    Create a sparse tree based on the value of a property. This first prompts for the name of a property, and then for a value. A sparse tree is created with all entries that define this property with the given value. If you enclose the value in curly braces, it is interpreted as a regular expression and matched against the property valu

7.4 Property Inheritance

有点意思了, 能将全部的内容打穿.

The outline structure of Org documents lends itself to an inheritance model of properties: if the parent in a tree has a certain property, the children can inherit this property. Org mode does not turn this on by default, because it can slow down property searches significantly and is often not needed. However, if you find inheritance useful, you can turn it on by setting the variable org-use-property-inheritance. It may be set to t to make all properties inherited from the parent, to a list of properties that should be inherited, or to a regular expression that matches inherited properties. If a property has the value nil, this is interpreted as an explicit un-define of the property, so that inheritance search stops at this value and returns nil.

Org mode has a few properties for which inheritance is hard-coded, at least for the special applications for which they are used:

  • COLUMNS

    The ‘COLUMNS’ property defines the format of column view (see Column View). It is inherited in the sense that the level where a ‘COLUMNS’ property is defined is used as the starting point for a column view table, independently of the location in the subtree from where columns view is turned on.

  • CATEGORY

    For agenda view, a category set through a ‘CATEGORY’ property applies to the entire subtree.

  • ARCHIVE

    For archiving, the ‘ARCHIVE’ property may define the archive location for the entire subtree (see Moving subtrees).

  • LOGGING

    The ‘LOGGING’ property may define logging settings for an entry or a subtree (see Tracking TODO state changes).

7.5 Column View

A great way to view and edit properties in an outline tree is column view. In column view, each outline node is turned into a table row. Columns in this table provide access to properties of the entries. Org mode implements columns by overlaying a tabular structure over the headline of each item. While the headlines have been turned into a table row, you can still change the visibility of the outline tree. For example, you get a compact table by switching to “contents” view—S-TAB S-TAB, or simply c while column view is active—but you can still open, read, and edit the entry below each headline. Or, you can switch to column view after executing a sparse tree command and in this way get a table only for the selected items. Column view also works in agenda buffers (see Agenda Views) where queries have collected selected items, possibly from a number of files.

• Defining columns: The COLUMNS format property.
• Using column view: How to create and use column view.
• Capturing column view: A dynamic block for column view.

7.5.1 Defining columns

Setting up a column view first requires defining the columns. This is done by defining a column format line.

• Scope of column definitions: Where defined, where valid?
• Column attributes: Appearance and content of a column.

有点复杂, 不知道有啥用.

7.5.1.1 Scope of column definitions

To define a column format for an entire file, use a line like:

1
#+COLUMNS: %25ITEM %TAGS %PRIORITY %TODO

To specify a format that only applies to a specific tree, add a ‘COLUMNS’ property to the top node of that tree, for example:

1
2
3
4
** Top node for columns view
:PROPERTIES:
:COLUMNS: %25ITEM %TAGS %PRIORITY %TODO
:END:

If a ‘COLUMNS’ property is present in an entry, it defines columns for the entry itself, and for the entire subtree below it. Since the column definition is part of the hierarchical structure of the document, you can define columns on level 1 that are general enough for all sublevels, and more specific columns further down, when you edit a deeper part of the tree.

7.5.1.2 Column attributes

A column definition sets the attributes of a column. The general definition looks like this:

1
%[WIDTH]PROPERTY[(TITLE)][{SUMMARY-TYPE}]

Except for the percent sign and the property name, all items are optional. The individual parts have the following meaning:

  • WIDTH

    An integer specifying the width of the column in characters. If omitted, the width is determined automatically.

  • PROPERTY

    The property that should be edited in this column. Special properties representing meta data are allowed here as well (see Special Properties).

  • TITLE

    The header text for the column. If omitted, the property name is used.

  • SUMMARY-TYPE

    The summary type. If specified, the column values for parent nodes are computed from the children57.Supported summary types are:‘+’Sum numbers in this column.‘+;%.1f’Like ‘+’, but format result with ‘%.1f’.‘$’Currency, short for ‘+;%.2f’.‘min’Smallest number in column.‘max’Largest number.‘mean’Arithmetic mean of numbers.‘X’Checkbox status, ‘[X]’ if all children are ‘[X]’.‘X/’Checkbox status, ‘[n/m]’.‘X%’Checkbox status, ‘[n%]’.‘:’Sum times, HH:MM, plain numbers are hours.‘:min’Smallest time value in column.‘:max’Largest time value.‘:mean’Arithmetic mean of time values.‘@min’Minimum age58 (in days/hours/mins/seconds).‘@max’Maximum age (in days/hours/mins/seconds).‘@mean’Arithmetic mean of ages (in days/hours/mins/seconds).‘est+’Add low-high estimates.You can also define custom summary types by setting org-columns-summary-types.

The ‘est+’ summary type requires further explanation. It is used for combining estimates, expressed as low-high ranges. For example, instead of estimating a particular task will take 5 days, you might estimate it as 5–6 days if you’re fairly confident you know how much work is required, or 1–10 days if you do not really know what needs to be done. Both ranges average at 5.5 days, but the first represents a more predictable delivery.

When combining a set of such estimates, simply adding the lows and highs produces an unrealistically wide result. Instead, ‘est+’ adds the statistical mean and variance of the subtasks, generating a final estimate from the sum. For example, suppose you had ten tasks, each of which was estimated at 0.5 to 2 days of work. Straight addition produces an estimate of 5 to 20 days, representing what to expect if everything goes either extremely well or extremely poorly. In contrast, ‘est+’ estimates the full job more realistically, at 10–15 days.

Here is an example for a complete columns definition, along with allowed values59.

1
2
3
4
5
:COLUMNS:  %25ITEM %9Approved(Approved?){X} %Owner %11Status \
%10Time_Estimate{:} %CLOCKSUM %CLOCKSUM_T
:Owner_ALL: Tammy Mark Karl Lisa Don
:Status_ALL: "In progress" "Not started yet" "Finished" ""
:Approved_ALL: "[ ]" "[X]"

The first column, ‘%25ITEM’, means the first 25 characters of the item itself, i.e., of the headline. You probably always should start the column definition with the ‘ITEM’ specifier. The other specifiers create columns ‘Owner’ with a list of names as allowed values, for ‘Status’ with four different possible values, and for a checkbox field ‘Approved’. When no width is given after the ‘%’ character, the column is exactly as wide as it needs to be in order to fully display all values. The ‘Approved’ column does have a modified title (‘Approved?’, with a question mark). Summaries are created for the ‘Time_Estimate’ column by adding time duration expressions like HH:MM, and for the ‘Approved’ column, by providing an ‘[X]’ status if all children have been checked. The ‘CLOCKSUM’ and ‘CLOCKSUM_T’ columns are special, they lists the sums of CLOCK intervals in the subtree, either for all clocks or just for today.

7.5.2 Using column view

平白叙述, 没有应用实例.

Turning column view on or off

  • C-c C-x C-c (org-columns)

    Turn on column view. If point is before the first headline in the file, column view is turned on for the entire file, using the ‘#+COLUMNS’ definition. If point is somewhere inside the outline, this command searches the hierarchy, up from point, for a ‘COLUMNS’ property that defines a format. When one is found, the column view table is established for the tree starting at the entry that contains the ‘COLUMNS’ property. If no such property is found, the format is taken from the ‘#+COLUMNS’ line or from the variable org-columns-default-format, and column view is established for the current entry and its subtree.

  • r or g (org-columns-redo)

    Recreate the column view, to include recent changes made in the buffer.

  • q (org-columns-quit)

    Exit column view.

Editing values

  • LEFT, RIGHT, UP, DOWN

    Move through the column view from field to field.

  • 1..9,0

    Directly select the Nth allowed value, 0 selects the 10th value.

  • n or S-RIGHT (org-columns-next-allowed-value)

  • p or S-LEFT (org-columns-previous-allowed-value)

    Switch to the next/previous allowed value of the field. For this, you have to have specified allowed values for a property.

  • e (org-columns-edit-value)

    Edit the property at point. For the special properties, this invokes the same interface that you normally use to change that property. For example, the tag completion or fast selection interface pops up when editing a ‘TAGS’ property.

  • C-c C-c (org-columns-set-tags-or-toggle)
    n
    When there is a checkbox at point, toggle it.

  • v (org-columns-show-value)

    View the full value of this property. This is useful if the width of the column is smaller than that of the value.

  • a (org-columns-edit-allowed)

    Edit the list of allowed values for this property. If the list is found in the hierarchy, the modified values is stored there. If no list is found, the new value is stored in the first entry that is part of the current column view.

Modifying column view on-the-fly

  • < (org-columns-narrow)

  • (org-columns-widen)

    Make the column narrower/wider by one character.

  • S-M-RIGHT (org-columns-new)

    Insert a new column, to the left of the current column.

  • S-M-LEFT (org-columns-delete)

    Delete the current column.

7.5.3 Capturing column view

弄得这么负责, 有啥鸟用.

Since column view is just an overlay over a buffer, it cannot be exported or printed directly. If you want to capture a column view, use a ‘columnview’ dynamic block (see Dynamic Blocks). The frame of this block looks like this:

1
2
3
* The column view
#+BEGIN: columnview :hlines 1 :id "label"
#+END:

This dynamic block has the following parameters:

  • ‘:id’

    This is the most important parameter. Column view is a feature that is often localized to a certain (sub)tree, and the capture block might be at a different location in the file. To identify the tree whose view to capture, you can use four values:‘local’Use the tree in which the capture block is located.‘global’Make a global view, including all headings in the file.‘file:FILENAME’Run column view at the top of the FILENAME file.‘LABEL’Call column view in the tree that has an ‘ID’ property with the value LABEL. You can use M-x org-id-copy to create a globally unique ID for the current entry and copy it to the kill-ring.

  • ‘:hlines’

    When t, insert an hline after every line. When a number N, insert an hline before each headline with level <= N.

  • ‘:vlines’

    When non-nil, force column groups to get vertical lines.

  • ‘:maxlevel’

    When set to a number, do not capture entries below this level.

  • ‘:skip-empty-rows’

    When non-nil, skip rows where the only non-empty specifier of the column view is ‘ITEM’.

  • ‘:indent’

    When non-nil, indent each ‘ITEM’ field according to its level.

  • ‘:format’

    Specify a column attribute (see Column attributes) for the dynamic block.

The following commands insert or update the dynamic block:

  • C-c C-x i (org-insert-columns-dblock)

    Insert a dynamic block capturing a column view. Prompt for the scope or ID of the view.

  • C-c C-c C-c C-x C-u (org-dblock-update)

    Update dynamic block at point. point needs to be in the ‘#+BEGIN’ line of the dynamic block.

  • C-u C-c C-x C-u (org-update-all-dblocks)

    Update all dynamic blocks (see Dynamic Blocks). This is useful if you have several clock table blocks, column-capturing blocks or other dynamic blocks in a buffer.

You can add formulas to the column view table and you may add plotting instructions in front of the table—these survive an update of the block. If there is a ‘TBLFM’ keyword after the table, the table is recalculated automatically after an update.

An alternative way to capture and process property values into a table is provided by Eric Schulte’s ‘org-collector.el’, which is a contributed package60. It provides a general API to collect properties from entries in a certain scope, and arbitrary Lisp expressions to process these values before inserting them into a table or a dynamic block.

1234

Gabriel

32 posts
16 categories
30 tags
GitHub
© 2019 Gabriel
Powered by Hexo v3.8.0
|
Theme – NexT.Mist v7.1.1