Emacs Lisp Reference Manual
Emacs Lisp Reference Manual
Short Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 Lisp Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4 Strings and Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6 Sequences, Arrays, and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . 87
7 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
10 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
14 Writing Customization Definitions . . . . . . . . . . . . . . . . . . . . . . 185
15 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16 Byte Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
17 Advising Emacs Lisp Functions . . . . . . . . . . . . . . . . . . . . . . . . 226
18 Debugging Lisp Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
19 Reading and Printing Lisp Objects . . . . . . . . . . . . . . . . . . . . . 268
20 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
21 Command Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
22 Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
23 Major and Minor Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
24 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
25 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
26 Backups and Auto-Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
27 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
28 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
29 Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
30 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
31 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
32 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
33 Non-ASCII Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
34 Searching and Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
35 Syntax Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
ii
Table of Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Lisp History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.1 Some Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.2 nil and t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3.3 Evaluation Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.4 Printing Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.5 Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.6 Buffer Text Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.7 Format of Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.7.1 A Sample Function Description . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.7.2 A Sample Variable Description. . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Version Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.1 Integer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2 Floating Point Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 Type Predicates for Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.4 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.5 Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.7 Rounding Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.8 Bitwise Operations on Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.9 Standard Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.10 Random Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.1 Lists and Cons Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.2 Predicates on Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.3 Accessing Elements of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.4 Building Cons Cells and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.5 Modifying List Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.6 Modifying Existing List Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.6.1 Altering List Elements with setcar . . . . . . . . . . . . . . . . . . . . . . 73
5.6.2 Altering the CDR of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.6.3 Functions that Rearrange Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.7 Using Lists as Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.8 Association Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.9 Managing a Fixed-Size Ring of Objects . . . . . . . . . . . . . . . . . . . . . . . . 84
7 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.1 Creating Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.2 Hash Table Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.3 Defining Hash Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.4 Other Hash Table Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.1 Symbol Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.2 Defining Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.3 Creating and Interning Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.4 Property Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.4.1 Property Lists and Association Lists . . . . . . . . . . . . . . . . . . . . . 107
8.4.2 Property List Functions for Symbols . . . . . . . . . . . . . . . . . . . . . 108
8.4.3 Property Lists Outside Symbols . . . . . . . . . . . . . . . . . . . . . . . . . 108
vi
9 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9.1 Kinds of Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.1.1 Self-Evaluating Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.1.2 Symbol Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.1.3 Classification of List Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.1.4 Symbol Function Indirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.1.5 Evaluation of Function Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
9.1.6 Lisp Macro Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
9.1.7 Special Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.1.8 Autoloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2 Quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.3 Eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
11 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
11.1 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
11.2 Variables that Never Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
11.3 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
11.4 When a Variable is “Void” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
11.5 Defining Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
11.6 Tips for Defining Variables Robustly . . . . . . . . . . . . . . . . . . . . . . . . 141
11.7 Accessing Variable Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
11.8 How to Alter a Variable Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
11.9 Scoping Rules for Variable Bindings . . . . . . . . . . . . . . . . . . . . . . . . . 145
11.9.1 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
11.9.2 Extent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
11.9.3 Implementation of Dynamic Scoping . . . . . . . . . . . . . . . . . . . 146
11.9.4 Proper Use of Dynamic Scoping . . . . . . . . . . . . . . . . . . . . . . . . 147
11.10 Buffer-Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
11.10.1 Introduction to Buffer-Local Variables . . . . . . . . . . . . . . . . . 148
11.10.2 Creating and Deleting Buffer-Local Bindings . . . . . . . . . . 149
11.10.3 The Default Value of a Buffer-Local Variable . . . . . . . . . . 152
11.11 Frame-Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
vii
12 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
12.1 What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
12.2 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.2.1 Components of a Lambda Expression . . . . . . . . . . . . . . . . . . . 162
12.2.2 A Simple Lambda-Expression Example . . . . . . . . . . . . . . . . . 162
12.2.3 Other Features of Argument Lists . . . . . . . . . . . . . . . . . . . . . . 163
12.2.4 Documentation Strings of Functions . . . . . . . . . . . . . . . . . . . . 164
12.3 Naming a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
12.4 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
12.5 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
12.6 Mapping Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
12.7 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
12.8 Accessing Function Cell Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
12.9 Declaring Functions Obsolete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
12.10 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
12.11 Determining whether a Function is Safe to Call . . . . . . . . . . . . 174
12.12 Other Topics Related to Functions . . . . . . . . . . . . . . . . . . . . . . . . . 174
13 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
13.1 A Simple Example of a Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
13.2 Expansion of a Macro Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
13.3 Macros and Byte Compilation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
13.4 Defining Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
13.5 Backquote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
13.6 Common Problems Using Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
13.6.1 Wrong Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
13.6.2 Evaluating Macro Arguments Repeatedly . . . . . . . . . . . . . . . 180
13.6.3 Local Variables in Macro Expansions . . . . . . . . . . . . . . . . . . . 182
13.6.4 Evaluating Macro Arguments in Expansion . . . . . . . . . . . . . 182
13.6.5 How Many Times is the Macro Expanded? . . . . . . . . . . . . . 183
13.7 Indenting Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
15 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.1 How Programs Do Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.2 Load Suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
15.3 Library Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
15.4 Loading Non-ASCII Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
15.5 Autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
15.6 Repeated Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
15.7 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
15.8 Which File Defined a Certain Symbol . . . . . . . . . . . . . . . . . . . . . . . 211
15.9 Unloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
15.10 Hooks for Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
20 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
20.1 Introduction to Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
20.2 Reading Text Strings with the Minibuffer . . . . . . . . . . . . . . . . . . . 279
20.3 Reading Lisp Objects with the Minibuffer . . . . . . . . . . . . . . . . . . . 281
20.4 Minibuffer History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
20.5 Initial Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
20.6 Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
20.6.1 Basic Completion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
20.6.2 Completion and the Minibuffer . . . . . . . . . . . . . . . . . . . . . . . . . 288
20.6.3 Minibuffer Commands that Do Completion . . . . . . . . . . . . . 289
x
22 Keymaps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
22.1 Key Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
22.2 Keymap Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
22.3 Format of Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
22.4 Creating Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
22.5 Inheritance and Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
22.6 Prefix Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
22.7 Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
22.8 Searching the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
22.9 Controlling the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
22.10 Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
22.11 Functions for Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
22.12 Changing Key Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
22.13 Remapping Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
22.14 Keymaps for Translating Sequences of Events . . . . . . . . . . . . . . 365
22.15 Commands for Binding Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
22.16 Scanning Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
22.17 Menu Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
22.17.1 Defining Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
22.17.1.1 Simple Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
22.17.1.2 Extended Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
22.17.1.3 Menu Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
22.17.1.4 Alias Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
22.17.2 Menus and the Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
22.17.3 Menus and the Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
22.17.4 Menu Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
22.17.5 The Menu Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
22.17.6 Tool bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
22.17.7 Modifying Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
24 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
24.1 Documentation Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
24.2 Access to Documentation Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
24.3 Substituting Key Bindings in Documentation . . . . . . . . . . . . . . . . 428
24.4 Describing Characters for Help Messages . . . . . . . . . . . . . . . . . . . . 429
24.5 Help Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
25 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
25.1 Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
25.1.1 Functions for Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
25.1.2 Subroutines of Visiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
25.2 Saving Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
25.3 Reading from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
25.4 Writing to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
25.5 File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
25.6 Information about Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
25.6.1 Testing Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
25.6.2 Distinguishing Kinds of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
25.6.3 Truenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
25.6.4 Other Information about Files. . . . . . . . . . . . . . . . . . . . . . . . . . 447
25.6.5 How to Locate Files in Standard Places . . . . . . . . . . . . . . . . 449
25.7 Changing File Names and Attributes . . . . . . . . . . . . . . . . . . . . . . . . 450
xiii
27 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
27.1 Buffer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
27.2 The Current Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
27.3 Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
27.4 Buffer File Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
27.5 Buffer Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
27.6 Buffer Modification Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
27.7 Read-Only Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
27.8 The Buffer List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
27.9 Creating Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
27.10 Killing Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
27.11 Indirect Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
27.12 The Buffer Gap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
28 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
28.1 Basic Concepts of Emacs Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 497
28.2 Splitting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
28.3 Deleting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
28.4 Selecting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
28.5 Cyclic Ordering of Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
28.6 Buffers and Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
28.7 Displaying Buffers in Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
28.8 Choosing a Window for Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
28.9 Windows and Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
28.10 The Window Start Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
xiv
29 Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
29.1 Creating Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
29.2 Multiple Displays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
29.3 Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
29.3.1 Access to Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
29.3.2 Initial Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
29.3.3 Window Frame Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
29.3.3.1 Basic Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
29.3.3.2 Position Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
29.3.3.3 Size Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
29.3.3.4 Layout Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
29.3.3.5 Buffer Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
29.3.3.6 Window Management Parameters . . . . . . . . . . . . . . . . . 536
29.3.3.7 Cursor Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
29.3.3.8 Color Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
29.3.4 Frame Size And Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
29.3.5 Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
29.4 Frame Titles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
29.5 Deleting Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
29.6 Finding All Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
29.7 Frames and Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
29.8 Minibuffers and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
29.9 Input Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
29.10 Visibility of Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
29.11 Raising and Lowering Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
29.12 Frame Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
29.13 Mouse Tracking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
29.14 Mouse Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
29.15 Pop-Up Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
29.16 Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
29.17 Pointer Shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
29.18 Window System Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
29.19 Drag and Drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
29.20 Color Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
29.21 Text Terminal Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
29.22 X Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
29.23 Display Feature Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
xv
30 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
30.1 Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
30.2 Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
30.2.1 Motion by Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
30.2.2 Motion by Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
30.2.3 Motion to an End of the Buffer. . . . . . . . . . . . . . . . . . . . . . . . . 561
30.2.4 Motion by Text Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
30.2.5 Motion by Screen Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
30.2.6 Moving over Balanced Expressions . . . . . . . . . . . . . . . . . . . . . 566
30.2.7 Skipping Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
30.3 Excursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
30.4 Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
31 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
31.1 Overview of Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
31.2 Predicates on Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
31.3 Functions that Create Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
31.4 Information from Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
31.5 Marker Insertion Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
31.6 Moving Marker Positions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
31.7 The Mark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
31.8 The Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
32 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
32.1 Examining Text Near Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
32.2 Examining Buffer Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
32.3 Comparing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
32.4 Inserting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
32.5 User-Level Insertion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
32.6 Deleting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
32.7 User-Level Deletion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
32.8 The Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
32.8.1 Kill Ring Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
32.8.2 Functions for Killing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
32.8.3 Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
32.8.4 Functions for Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
32.8.5 Low-Level Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
32.8.6 Internals of the Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
32.9 Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
32.10 Maintaining Undo Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
32.11 Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
32.12 Margins for Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
32.13 Adaptive Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
32.14 Auto Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
32.15 Sorting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
32.16 Counting Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
32.17 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
xvi
37 Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
37.1 Functions that Create Subprocesses . . . . . . . . . . . . . . . . . . . . . . . . . 705
37.2 Shell Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
37.3 Creating a Synchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
37.4 Creating an Asynchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . 710
37.5 Deleting Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
37.6 Process Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
37.7 Sending Input to Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
37.8 Sending Signals to Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715
37.9 Receiving Output from Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
37.9.1 Process Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
37.9.2 Process Filter Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
37.9.3 Decoding Process Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
37.9.4 Accepting Output from Processes . . . . . . . . . . . . . . . . . . . . . . 721
37.10 Sentinels: Detecting Process Status Changes . . . . . . . . . . . . . . . 721
37.11 Querying Before Exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
37.12 Transaction Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
37.13 Network Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
37.14 Network Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
37.15 Datagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
37.16 Low-Level Network Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
37.16.1 make-network-process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
37.16.2 Network Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
37.16.3 Testing Availability of Network Features . . . . . . . . . . . . . . 730
37.17 Misc Network Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
37.18 Packing and Unpacking Byte Arrays . . . . . . . . . . . . . . . . . . . . . . . 732
37.18.1 Describing Data Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
37.18.2 Functions to Unpack and Pack Bytes . . . . . . . . . . . . . . . . . . 734
37.18.3 Examples of Byte Unpacking and Packing . . . . . . . . . . . . . 735
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
Chapter 1: Introduction 1
1 Introduction
Most of the GNU Emacs text editor is written in the programming language called Emacs
Lisp. You can write new code in Emacs Lisp and install it as an extension to the editor.
However, Emacs Lisp is more than a mere “extension language”; it is a full computer
programming language in its own right. You can use it as you would any other programming
language.
Because Emacs Lisp is designed for use in an editor, it has special features for scanning
and parsing text as well as features for handling files, buffers, displays, subprocesses, and
so on. Emacs Lisp is closely integrated with the editing facilities; thus, editing commands
are functions that can also conveniently be called from Lisp programs, and parameters for
customization are ordinary Lisp variables.
This manual attempts to be a full description of Emacs Lisp. For a beginner’s introduc-
tion to Emacs Lisp, see An Introduction to Emacs Lisp Programming, by Bob Chassell, also
published by the Free Software Foundation. This manual presumes considerable familiarity
with the use of Emacs for editing; see The GNU Emacs Manual for this basic information.
Generally speaking, the earlier chapters describe features of Emacs Lisp that have coun-
terparts in many programming languages, and later chapters describe features that are
peculiar to Emacs Lisp or relate specifically to editing.
This is edition 2.9 of the GNU Emacs Lisp Reference Manual, corresponding to Emacs
version 22.1.
1.1 Caveats
This manual has gone through numerous drafts. It is nearly complete but not flawless.
There are a few topics that are not covered, either because we consider them secondary
(such as most of the individual modes) or because they are yet to be written. Because we
are not able to deal with them completely, we have left out several parts intentionally. This
includes most information about usage on VMS.
The manual should be fully correct in what it does cover, and it is therefore open to
criticism on anything it says—from specific examples and descriptive text, to the ordering
of chapters and sections. If something is confusing, or you find that you have to look at
the sources or experiment to learn something not covered in the manual, then perhaps the
manual should be fixed. Please let us know.
As you use this manual, we ask that you mark pages with corrections so you can later
look them up and send them to us. If you think of a simple, real-life example for a function
or group of functions, please make an effort to write it up and send it in. Please reference
any comments to the chapter name, section name, and function name, as appropriate, since
page numbers and chapter and section numbers will change and we may have trouble finding
the text you are talking about. Also state the number of the edition you are criticizing.
Please mail comments and corrections to
[email protected]
We let mail to this list accumulate unread until someone decides to apply the corrections.
Months, and sometimes years, go by between updates. So please attach no significance to
the lack of a reply—your mail will be acted on in due time. If you want to contact the
Emacs maintainers more quickly, send mail to [email protected].
Chapter 1: Introduction 2
1.3 Conventions
This section explains the notational conventions that are used in this manual. You may
want to skip this section and refer back to it later.
In this manual, we write () when we wish to emphasize that it means the empty list,
and we write nil when we wish to emphasize that it means the truth value false. That is
a good convention to use in Lisp programs also.
(cons ’foo ()) ; Emphasize the empty list
(setq foo-flag nil) ; Emphasize the truth value false
In contexts where a truth value is expected, any non-nil value is considered to be true.
However, t is the preferred way to represent the truth value true. When you need to choose
a value which represents true, and there is no other basis for choosing, use t. The symbol
t always has the value t.
In Emacs Lisp, nil and t are special symbols that always evaluate to themselves. This is
so that you do not need to quote them to use them as constants in a program. An attempt
to change their values results in a setting-constant error. See Section 11.2 [Constant
Variables], page 135.
booleanp object [Function]
Return non-nil iff object is one of the two canonical boolean values: t or nil.
electric-future-map [Variable]
The value of this variable is a full keymap used by Electric Command Future mode.
The functions in this map allow you to edit commands you have not yet thought
about executing.
User option descriptions have the same format, but ‘Variable’ is replaced by ‘User Op-
tion’.
emacs-build-time [Variable]
The value of this variable indicates the time at which Emacs was built at the local
site. It is a list of three integers, like the value of current-time (see Section 39.5
[Time of Day], page 824).
emacs-build-time
⇒ (13623 62065 344633)
emacs-version [Variable]
The value of this variable is the version of Emacs being run. It is a string such as
"20.3.1". The last number in this string is not really part of the Emacs release
version number; it is incremented each time you build Emacs in any given directory.
A value with four numeric components, such as "20.3.9.1", indicates an unreleased
test version.
Chapter 1: Introduction 7
The following two variables have existed since Emacs version 19.23:
emacs-major-version [Variable]
The major version number of Emacs, as an integer. For Emacs version 20.3, the value
is 20.
emacs-minor-version [Variable]
The minor version number of Emacs, as an integer. For Emacs version 20.3, the value
is 3.
1.5 Acknowledgements
This manual was written by Robert Krawitz, Bil Lewis, Dan LaLiberte, Richard M. Stall-
man and Chris Welty, the volunteers of the GNU manual group, in an effort extending
over several years. Robert J. Chassell helped to review and edit the manual, with the sup-
port of the Defense Advanced Research Projects Agency, ARPA Order 6082, arranged by
Warren A. Hunt, Jr. of Computational Logic, Inc.
Corrections were supplied by Karl Berry, Jim Blandy, Bard Bloom, Stephane Boucher,
David Boyes, Alan Carroll, Richard Davis, Lawrence R. Dodd, Peter Doornbosch, David A.
Duff, Chris Eich, Beverly Erlebacher, David Eckelkamp, Ralf Fassel, Eirik Fuller, Stephen
Gildea, Bob Glickstein, Eric Hanchrow, George Hartzell, Nathan Hess, Masayuki Ida, Dan
Jacobson, Jak Kirman, Bob Knighten, Frederick M. Korz, Joe Lammens, Glenn M. Lewis,
K. Richard Magill, Brian Marick, Roland McGrath, Skip Montanaro, John Gardiner Myers,
Thomas A. Peterson, Francesco Potorti, Friedrich Pukelsheim, Arnold D. Robbins, Raul
Rockwell, Per Starbäck, Shinichirou Sugou, Kimmo Suominen, Edward Tharp, Bill Trost,
Rickard Westman, Jean White, Matthew Wilding, Carl Witty, Dale Worley, Rusty Wright,
and David D. Zuhn.
Chapter 2: Lisp Data Types 8
2.2 Comments
A comment is text that is written in a program only for the sake of humans that read the
program, and that has no effect on the meaning of the program. In Lisp, a semicolon (‘;’)
starts a comment if it is not within a string or character constant. The comment continues
to the end of line. The Lisp reader discards comments; they do not become part of the Lisp
objects which represent the program within the Lisp system.
The ‘#@count ’ construct, which skips the next count characters, is useful for program-
generated comments containing binary data. The Emacs Lisp byte compiler uses this in its
output files (see Chapter 16 [Byte Compilation], page 214). It isn’t meant for source files,
however.
See Section D.7 [Comment Tips], page 865, for conventions for formatting comments.
and ‘?\e’, respectively. (‘?\s’ followed by a dash has a different meaning—it applies the
“super” modifier to the following character.) Thus,
?\a ⇒ 7 ; control-g, C-g
?\b ⇒ 8 ; backspace, BS, C-h
?\t ⇒ 9 ; tab, TAB, C-i
?\n ⇒ 10 ; newline, C-j
?\v ⇒ 11 ; vertical tab, C-k
?\f ⇒ 12 ; formfeed character, C-l
?\r ⇒ 13 ; carriage return, RET, C-m
?\e ⇒ 27 ; escape character, ESC, C-[
?\s ⇒ 32 ; space character, SPC
?\\ ⇒ 92 ; backslash character, \
?\d ⇒ 127 ; delete character, DEL
These sequences which start with backslash are also known as escape sequences, because
backslash plays the role of an “escape character”; this terminology has nothing to do with
the character ESC. ‘\s’ is meant for use in character constants; in string constants, just
write the space.
A backslash is allowed, and harmless, preceding any character without a special escape
meaning; thus, ‘?\+’ is equivalent to ‘?+’. There is no reason to add a backslash before most
characters. However, you should add a backslash before any of the characters ‘()\|;’‘"#.,’
to avoid confusing the Emacs commands for editing Lisp code. You can also add a backslash
before whitespace characters such as space, tab, newline and formfeed. However, it is cleaner
to use one of the easily readable escape sequences, such as ‘\t’ or ‘\s’, instead of an actual
whitespace character such as a tab or a space. (If you do write backslash followed by a
space, you should write an extra space after the character constant to separate it from the
following text.)
Because cons cells are so central to Lisp, we also have a word for “an object which is not
a cons cell.” These objects are called atoms.
The read syntax and printed representation for lists are identical, and consist of a left
parenthesis, an arbitrary number of elements, and a right parenthesis. Here are examples
of lists:
(A 2 "A") ; A list of three elements.
() ; A list of no elements (the empty list).
nil ; A list of no elements (the empty list).
("A ()") ; A list of one element: the string "A ()".
(A ()) ; A list of two elements: A and the empty list.
(A nil) ; Equivalent to the previous.
((A B C)) ; A list of one element
; (which is a list of three elements).
Upon reading, each object inside the parentheses becomes an element of the list. That
is, a cons cell is made for each element. The car slot of the cons cell holds the element,
and its cdr slot refers to the next cons cell of the list, which holds the next element in the
list. The cdr slot of the last cons cell is set to hold nil.
The names car and cdr derive from the history of Lisp. The original Lisp implementa-
tion ran on an IBM 704 computer which divided words into two parts, called the “address”
part and the “decrement”; car was an instruction to extract the contents of the address
part of a register, and cdr an instruction to extract the contents of the decrement. By
contrast, “cons cells” are named for the function cons that creates them, which in turn was
named for its purpose, the construction of cells.
whose cdr is the object b. Dotted pair notation is more general than list syntax because
the cdr does not have to be a list. However, it is more cumbersome in cases where list
syntax would work. In dotted pair notation, the list ‘(1 2 3)’ is written as ‘(1 . (2 . (3 .
nil)))’. For nil-terminated lists, you can use either notation, but list notation is usually
clearer and more convenient. When printing a list, the dotted pair notation is only used if
the cdr of a cons cell is not a list.
Here’s an example using boxes to illustrate dotted pair notation. This example shows
the pair (rose . violet):
--- ---
| | |--> violet
--- ---
|
|
--> rose
You can combine dotted pair notation with list notation to represent conveniently a
chain of cons cells with a non-nil final cdr. You write a dot after the last element of the
list, followed by the cdr of the final cons cell. For example, (rose violet . buttercup)
is equivalent to (rose . (violet . buttercup)). The object looks like this:
--- --- --- ---
| | |--> | | |--> buttercup
--- --- --- ---
| |
| |
--> rose --> violet
The syntax (rose . violet . buttercup) is invalid because there is nothing that it
could mean. If anything, it would say to put buttercup in the cdr of a cons cell whose
cdr is already used for violet.
The list (rose violet) is equivalent to (rose . (violet)), and looks like this:
--- --- --- ---
| | |--> | | |--> nil
--- --- --- ---
| |
| |
--> rose --> violet
Similarly, the three-element list (rose violet buttercup) is equivalent to (rose .
(violet . (buttercup))).
one that is preceded by ‘\’—does not become part of the string; i.e., the Lisp reader ignores
an escaped newline while reading a string. An escaped space ‘\ ’ is likewise ignored.
"It is useful to include newlines
in documentation strings,
but the newline is \
ignored if escaped."
⇒ "It is useful to include newlines
in documentation strings,
but the newline is ignored if escaped."
Properly speaking, strings cannot hold meta characters; but when a string is to be used
as a key sequence, there is a special convention that provides a way to represent meta
versions of ASCII characters in a string. If you use the ‘\M-’ syntax to indicate a meta
character in a string constant, this sets the 27 bit of the character in the string. If the string
is used in define-key or lookup-key, this numeric code is translated into the equivalent
meta character. See Section 2.3.3 [Character Type], page 10.
Strings cannot hold characters that have the hyper, super, or alt modifiers.
The printed representation of a char-table is like a vector except that there is an extra
‘#^’ at the beginning.
See Section 6.6 [Char-Tables], page 93, for special functions to operate on char-tables.
Uses of char-tables include:
• Case tables (see Section 4.9 [Case Tables], page 60).
• Character category tables (see Section 35.9 [Categories], page 696).
• Display tables (see Section 38.21 [Display Tables], page 807).
• Syntax tables (see Chapter 35 [Syntax Tables], page 684).
Section 12.7 [Anonymous Functions], page 170). A named function in Lisp is just a symbol
with a valid function in its function cell (see Section 12.4 [Defining Functions], page 165).
Most of the time, functions are called when their names are written in Lisp expressions
in Lisp programs. However, you can construct or obtain a function object at run time
and then call it with the primitive functions funcall and apply. See Section 12.5 [Calling
Functions], page 167.
it appears as a function to be called. See Chapter 16 [Byte Compilation], page 214, for
information about the byte compiler.
The printed representation and read syntax for a byte-code function object is like that
for a vector, with an additional ‘#’ before the opening ‘[’.
The local keymap and variable list contain entries that individually override global bindings
or values. These are used to customize the behavior of programs in different buffers, without
actually changing the programs.
A buffer may be indirect, which means it shares the text of another buffer, but presents
it differently. See Section 27.11 [Indirect Buffers], page 494.
Buffers have no read syntax. They print in hash notation, showing the buffer name.
(current-buffer)
⇒ #<buffer objects.texi>
The object nil, in addition to its other meanings, may be used as a stream. It stands
for the value of the variable standard-input or standard-output. Also, the object t as
a stream specifies input using the minibuffer (see Chapter 20 [Minibuffers], page 278) or
output in the echo area (see Section 38.4 [The Echo Area], page 741).
Streams have no special printed representation or read syntax, and print as whatever
primitive type they are.
See Chapter 19 [Read and Print], page 268, for a description of functions related to
streams, including parsing and printing functions.
#1=(a #1#)
This makes a list whose second element is the list itself. Here’s how you can see that it
really works:
(prog1 nil
(setq x ’#1=(a #1#)))
(eq x (cadr x))
⇒ t
The Lisp printer can produce this syntax to record circular and shared structure in a
Lisp object, if you bind the variable print-circle to a non-nil value. See Section 19.6
[Output Variables], page 276.
arguments to see if their elements or contents are the same. So, if two objects are eq,
they are equal, but the converse is not always true.
(equal ’foo ’foo)
⇒ t
The test for equality is implemented recursively; for example, given two cons cells x and
y, (equal x y ) returns t if and only if both the expressions below return t:
(equal (car x ) (car y ))
(equal (cdr x ) (cdr y ))
Because of this recursive method, circular lists may therefore cause infinite recursion
(leading to an error).
Chapter 3: Numbers 32
3 Numbers
GNU Emacs supports two numeric data types: integers and floating point numbers. Integers
are whole numbers such as −3, 0, 7, 13, and 511. Their values are exact. Floating point
numbers are numbers with fractional parts, such as −4.5, 0.0, or 2.71828. They can also be
expressed in exponential notation: 1.5e2 equals 150; in this example, ‘e2’ stands for ten to
the second power, and that is multiplied by 1.5. Floating point values are not exact; they
have a fixed, limited amount of precision.
To test whether a floating point value is a NaN, compare it with itself using =. That
returns nil for a NaN, and t for any other floating point value.
The value -0.0 is distinguishable from ordinary zero in IEEE floating point, but Emacs
Lisp equal and = consider them equal values.
You can use logb to extract the binary exponent of a floating point number (or estimate
the logarithm of an integer):
There are four functions to convert floating point numbers to integers; they differ in
how they round. All accept an argument number and an optional argument divisor. Both
arguments may be integers or floating point numbers. divisor may also be nil. If divisor
is nil or omitted, these functions convert number to an integer, or return it unchanged if
it already is an integer. If divisor is non-nil, they divide number by divisor and convert
the result to an integer. An arith-error results if divisor is 0.
(truncate 1.2)
⇒ 1
(truncate 1.7)
⇒ 1
(truncate -1.2)
⇒ -1
(truncate -1.7)
⇒ -1
(round -1.7)
⇒ -2
1- number-or-marker [Function]
This function returns number-or-marker minus 1.
+ &rest numbers-or-markers [Function]
This function adds its arguments together. When given no arguments, + returns 0.
(+)
⇒ 0
(+ 1)
⇒ 1
(+ 1 2 3 4)
⇒ 10
⇒ -10
(-)
⇒ 0
(lsh 7 1)
⇒ 14
;; Decimal 7 becomes decimal 14.
00000111 ⇒ 00001110
As the examples illustrate, shifting the pattern of bits one place to the left produces
a number that is twice the value of the previous number.
Shifting a pattern of bits two places to the left produces results like this (with 8-bit
binary numbers):
(lsh 3 2)
⇒ 12
;; Decimal 3 becomes decimal 12.
00000011 ⇒ 00001100
Chapter 3: Numbers 42
On the other hand, shifting one place to the right looks like this:
(lsh 6 -1)
⇒ 3
;; Decimal 6 becomes decimal 3.
00000110 ⇒ 00000011
(lsh 5 -1)
⇒ 2
;; Decimal 5 becomes decimal 2.
00000101 ⇒ 00000010
As the example illustrates, shifting one place to the right divides the value of a positive
integer by two, rounding downward.
The function lsh, like all Emacs Lisp arithmetic functions, does not check for overflow,
so shifting left can discard significant bits and change the sign of the number. For
example, left shifting 268,435,455 produces −2 on a 29-bit machine:
(lsh 268435455 1) ; left shift
⇒ -2
In binary, in the 29-bit implementation, the argument looks like this:
;; Decimal 268,435,455
0 1111 1111 1111 1111 1111 1111 1111
which becomes the following when left shifted:
;; Decimal −2
1 1111 1111 1111 1111 1111 1111 1110
(logand)
⇒ -1 ; -1 = 1 1111 1111 1111 1111 1111 1111 1111
On some machines, any integer representable in Lisp may be the result of random.
On other machines, the result can never be larger than a certain maximum or less
than a certain (negative) minimum.
Chapter 4: Strings and Characters 47
[String Type], page 18, for information about the syntax of characters and strings. See
Chapter 33 [Non-ASCII Characters], page 640, for functions to convert between text repre-
sentations and to encode and decode character codes.
character position up to which the substring is copied. The character whose index is
3 is actually the fourth character in the string.
A negative number counts from the end of the string, so that −1 signifies the index
of the last character of the string. For example:
(substring "abcdefg" -3 -1)
⇒ "ef"
In this example, the index for ‘e’ is −3, the index for ‘f’ is −2, and the index for ‘g’
is −1. Therefore, ‘e’ and ‘f’ are included, and ‘g’ is excluded.
When nil is used for end, it stands for the length of the string. Thus,
(substring "abcdefg" -3 nil)
⇒ "efg"
Omitting the argument end is equivalent to specifying nil. It follows that (substring
string 0) returns a copy of all of string.
(substring "abcdefg" 0)
⇒ "abcdefg"
But we recommend copy-sequence for this purpose (see Section 6.1 [Sequence Func-
tions], page 87).
If the characters copied from string have text properties, the properties are copied
into the new string also. See Section 32.19 [Text Properties], page 615.
substring also accepts a vector for the first argument. For example:
(substring [a b (c) "d"] 1 3)
⇒ [b (c)]
A wrong-type-argument error is signaled if start is not an integer or if end is neither
an integer nor nil. An args-out-of-range error is signaled if start indicates a
character following end, or if either integer is out of range for string.
Contrast this function with buffer-substring (see Section 32.2 [Buffer Contents],
page 582), which returns a string containing a portion of the text in the current buffer.
The beginning of a string is at index 0, but the beginning of a buffer is at index 1.
Empty matches do count, except that split-string will not look for a final empty
match when it already reached the end of the string using a non-empty match or
when string is empty:
(split-string "aooob" "o*")
⇒ ("" "a" "" "b" "")
(split-string "ooaboo" "o*")
⇒ ("" "" "a" "b" "")
(split-string "" "")
⇒ ("")
However, when separators can match the empty string, omit-nulls is usually t, so
that the subtleties in the three previous examples are rarely relevant:
(split-string "Soup is good food" "o*" t)
⇒ ("S" "u" "p" " " "i" "s" " " "g" "d" " " "f" "d")
(split-string "Nice doggy!" "" t)
⇒ ("N" "i" "c" "e" " " "d" "o" "g" "g" "y" "!")
(split-string "" "" t)
⇒ nil
Somewhat odd, but predictable, behavior can occur for certain “non-greedy” values
of separators that can prefer empty matches over non-empty matches. Again, such
values rarely occur in practice:
(split-string "ooo" "o*" t)
⇒ nil
(split-string "ooo" "\\|o+" t)
⇒ ("o" "o" "o")
split-string-default-separators [Variable]
The default value of separators for split-string. Its usual value is
"[ \f\t\n\r\v]+".
greater, and this function returns nil. If the two strings match entirely, the value is
nil.
Pairs of characters are compared according to their character codes. Keep in mind
that lower case letters have higher numeric values in the ASCII character set than
their upper case counterparts; digits and many punctuation characters have a lower
numeric value than upper case letters. An ASCII character is less than any non-ASCII
character; a unibyte non-ASCII character is always less than any multibyte non-ASCII
character (see Section 33.1 [Text Representations], page 640).
(string< "abc" "abd")
⇒ t
(string< "abd" "abc")
⇒ nil
(string< "123" "abc")
⇒ t
When the strings have different lengths, and they match up to the length of string1,
then the result is t. If they match up to the length of string2, the result is nil. A
string of no characters is less than any other string.
(string< "" "abc")
⇒ t
(string< "ab" "abc")
⇒ t
(string< "abc" "")
⇒ nil
(string< "abc" "ab")
⇒ nil
(string< "" "")
⇒ nil
Symbols are also allowed as arguments, in which case their print names are used.
string-lessp string1 string2 [Function]
string-lessp is another name for string<.
compare-strings string1 start1 end1 string2 start2 end2 &optional [Function]
ignore-case
This function compares the specified part of string1 with the specified part of string2.
The specified part of string1 runs from index start1 up to index end1 (nil means the
end of the string). The specified part of string2 runs from index start2 up to index
end2 (nil means the end of the string).
The strings are both converted to multibyte for the comparison (see Section 33.1 [Text
Representations], page 640) so that a unibyte string and its conversion to multibyte
are always regarded as equal. If ignore-case is non-nil, then case is ignored, so that
upper case letters can be equal to lower case letters.
If the specified portions of the two strings match, the value is t. Otherwise, the value
is an integer which indicates how many leading characters agree, and which string
is less. Its absolute value is one plus the number of characters that agree at the
beginning of the two strings. The sign is negative if string1 (or its specified portion)
is less.
Chapter 4: Strings and Characters 54
(string-to-char "xyz")
⇒ 120
(string-to-char "")
⇒ 0
(string-to-char "\000")
⇒ 0
This function may be eliminated in the future if it does not seem useful enough to
retain.
Chapter 4: Strings and Characters 55
Here are some other functions that can convert to or from a string:
concat concat can convert a vector or a list into a string. See Section 4.3 [Creating
Strings], page 48.
vconcat vconcat can convert a string into a vector. See Section 6.5 [Vector Functions],
page 92.
append append can convert a string into a list. See Section 5.4 [Building Lists], page 67.
Chapter 4: Strings and Characters 56
In the following three examples, ‘%7s’ specifies a minimum width of 7. In the first case,
the string inserted in place of ‘%7s’ has only 3 letters, it needs 4 blank spaces as padding.
In the second case, the string "specification" is 13 letters wide but is not truncated. In
the third case, the padding is on the right.
(format "The word ‘%7s’ actually has %d letters in it."
"foo" (length "foo"))
⇒ "The word ‘ foo’ actually has 3 letters in it."
case. When the argument to downcase is a character, downcase returns the corre-
sponding lower case character. This value is an integer. If the original character is
lower case, or is not a letter, then the value equals the original character.
(downcase "The cat in the hat")
⇒ "the cat in the hat"
(downcase ?X)
⇒ 120
upcase string-or-char [Function]
This function converts a character or a string to upper case.
When the argument to upcase is a string, the function creates and returns a new
string in which each letter in the argument that is lower case is converted to upper
case.
When the argument to upcase is a character, upcase returns the corresponding upper
case character. This value is an integer. If the original character is upper case, or is
not a letter, then the value returned equals the original character.
(upcase "The cat in the hat")
⇒ "THE CAT IN THE HAT"
(upcase ?x)
⇒ 88
capitalize string-or-char [Function]
This function capitalizes strings or characters. If string-or-char is a string, the func-
tion creates and returns a new string, whose contents are a copy of string-or-char in
which each word has been capitalized. This means that the first character of each
word is converted to upper case, and the rest are converted to lower case.
The definition of a word is any sequence of consecutive characters that are assigned
to the word constituent syntax class in the current syntax table (see Section 35.2.1
[Syntax Class Table], page 685).
When the argument to capitalize is a character, capitalize has the same result
as upcase.
(capitalize "The cat in the hat")
⇒ "The Cat In The Hat"
(capitalize ?x)
⇒ 88
upcase-initials string-or-char [Function]
If string-or-char is a string, this function capitalizes the initials of the words in string-
or-char, without altering any letters other than the initials. It returns a new string
whose contents are a copy of string-or-char, in which each word has had its initial
letter converted to upper case.
Chapter 4: Strings and Characters 60
The definition of a word is any sequence of consecutive characters that are assigned
to the word constituent syntax class in the current syntax table (see Section 35.2.1
[Syntax Class Table], page 685).
When the argument to upcase-initials is a character, upcase-initials has the
same result as upcase.
(upcase-initials "The CAT in the hAt")
⇒ "The CAT In The HAt"
See Section 4.5 [Text Comparison], page 52, for functions that compare strings; some of
them ignore case differences, or can optionally ignore case differences.
equivalences; then Emacs fills in this slot from canonicalize. In a case table that is actually
in use, those components are non-nil. Do not try to specify equivalences without also
specifying canonicalize.
Here are the functions for working with case tables:
standard-case-table [Function]
This returns the standard case table.
current-case-table [Function]
This function returns the current buffer’s case table.
Some language environments may modify the case conversions of ASCII characters; for
example, in the Turkish language environment, the ASCII character ‘I’ is downcased into
a Turkish “dotless i”. This can interfere with code that requires ordinary ASCII case
conversion, such as implementations of ASCII-based network protocols. In that case, use
the with-case-table macro with the variable ascii-case-table, which stores the unmodified
case table for the ASCII character set.
ascii-case-table [Variable]
The case table for the ASCII character set. This should not be modified by any
language environment settings.
The following three functions are convenient subroutines for packages that define non-
ASCII character sets. They modify the specified case table case-table; they also modify the
standard syntax table. See Chapter 35 [Syntax Tables], page 684. Normally you would use
these functions to change the standard case table.
describe-buffer-case-table [Command]
This command displays a description of the contents of the current buffer’s case table.
Chapter 5: Lists 63
5 Lists
A list represents a sequence of zero or more elements (which may be any Lisp objects). The
important difference between lists and vectors is that two or more lists can share part of
their structure; in addition, you can insert or delete elements in a list without copying the
whole list.
⇒ a
x
⇒ (b c)
The most common way to compute the length of a list, when you are not worried that
it may be circular, is with length. See Section 6.1 [Sequence Functions], page 87.
Chapter 5: Lists 67
trees
⇒ (pine oak)
more-trees
⇒ (maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
⇒ t
You can see how append works by looking at a box diagram. The variable trees is set
to the list (pine oak) and then the variable more-trees is set to the list (maple birch
pine oak). However, the variable trees continues to refer to the original list:
more-trees trees
| |
| --- --- --- --- -> --- --- --- ---
--> | | |--> | | |--> | | |--> | | |--> nil
--- --- --- --- --- --- --- ---
| | | |
| | | |
--> maple -->birch --> pine --> oak
An empty sequence contributes nothing to the value returned by append. As a conse-
quence of this, a final nil argument forces a copy of the previous argument:
trees
⇒ (pine oak)
(setq wood (append trees nil))
⇒ (pine oak)
wood
⇒ (pine oak)
(eq wood trees)
⇒ nil
This once was the usual way to copy a list, before the function copy-sequence was invented.
See Chapter 6 [Sequences Arrays Vectors], page 87.
Here we show the use of vectors and strings as arguments to append:
(append [a b] "cd" nil)
⇒ (a b 99 100)
With the help of apply (see Section 12.5 [Calling Functions], page 167), we can append
all the lists in a list of lists:
(apply ’append ’((a b c) nil (x y z) nil))
⇒ (a b c x y z)
If no sequences are given, nil is returned:
(append)
⇒ nil
Here are some examples where the final argument is not a list:
(append ’(x y) ’z)
⇒ (x y . z)
(append ’(x y) [z])
⇒ (x y . [z])
Chapter 5: Lists 70
The second example shows that when the final argument is a sequence but not a list, the
sequence’s elements do not become elements of the resulting list. Instead, the sequence
becomes the final cdr, like any other non-list final argument.
(number-sequence 8)
⇒ (8)
(number-sequence 8 5)
⇒ nil
(number-sequence 5 8 -1)
⇒ nil
(number-sequence 1.5 6 2)
⇒ (1.5 3.5 5.5)
⇒ (c a b)
An equivalent expression for (add-to-list ’var value ) is this:
(or (member value var )
(setq var (cons value var )))
add-to-ordered-list symbol element &optional order [Function]
This function sets the variable symbol by inserting element into the old value, which
must be a list, at the position specified by order. If element is already a member of
the list, its position in the list is adjusted according to order. Membership is tested
using eq. This function returns the resulting list, whether updated or not.
The order is typically a number (integer or float), and the elements of the list are
sorted in non-decreasing numerical order.
order may also be omitted or nil. Then the numeric order of element stays unchanged
if it already has one; otherwise, element has no numeric order. Elements without a
numeric list order are placed at the end of the list, in no particular order.
Any other value for order removes the numeric order of element if it already has one;
otherwise, it is equivalent to nil.
The argument symbol is not implicitly quoted; add-to-ordered-list is an ordinary
function, like set and unlike setq. Quote the argument yourself if that is what you
want.
The ordering information is stored in a hash table on symbol’s list-order property.
Here’s a scenario showing how to use add-to-ordered-list:
(setq foo ’())
⇒ nil
When a cons cell is part of the shared structure of several lists, storing a new car into
the cons changes one element of each of these lists. Here is an example:
;; Create two lists that are partly shared.
(setq x1 ’(a b c))
⇒ (a b c)
(setq x2 (cons ’z (cdr x1)))
⇒ (z b c)
Here is a graphical depiction of the shared structure of the two lists in the variables x1
and x2, showing why replacing b changes them both:
--- --- --- --- --- ---
x1---> | | |----> | | |--> | | |--> nil
--- --- --- --- --- ---
| --> | |
| | | |
--> a | --> b --> c
|
--- --- |
x2--> | | |--
--- ---
|
|
--> z
Here is an alternative form of box diagram, showing the same relationship:
x1:
-------------- -------------- --------------
| car | cdr | | car | cdr | | car | cdr |
| a | o------->| b | o------->| c | nil |
| | | -->| | | | | |
-------------- | -------------- --------------
|
x2: |
-------------- |
| car | cdr | |
| z | o----
| | |
--------------
You can delete elements from the middle of a list by altering the cdrs of the cons cells
in the list. For example, here we delete the second element, b, from the list (a b c), by
changing the cdr of the first cons cell:
(setq x1 ’(a b c))
⇒ (a b c)
(setcdr x1 (cdr (cdr x1)))
⇒ (c)
x1
⇒ (a c)
Here is the result in box notation:
--------------------
| |
-------------- | -------------- | --------------
| car | cdr | | | car | cdr | -->| car | cdr |
| a | o----- | b | o-------->| c | nil |
| | | | | | | | |
-------------- -------------- --------------
The second cons cell, which previously held the element b, still exists and its car is still b,
but it no longer forms part of this list.
It is equally easy to insert a new element by changing cdrs:
(setq x1 ’(a b c))
⇒ (a b c)
(setcdr x1 (cons ’d (cdr x1)))
⇒ (d b c)
x1
⇒ (a d b c)
Here is this result in box notation:
-------------- ------------- -------------
| car | cdr | | car | cdr | | car | cdr |
| a | o | -->| b | o------->| c | nil |
| | | | | | | | | | |
--------- | -- | ------------- -------------
| |
----- --------
| |
| --------------- |
| | car | cdr | |
-->| d | o------
| | |
---------------
(symbol-function ’add-foo)
⇒ (lambda (x) (nconc (quote (foo)) x))
(symbol-function ’add-foo)
⇒ (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
x
⇒ (a b c)
(nreverse x)
⇒ (c b a)
;; The cons cell that was first is now last.
x
⇒ (a)
To avoid confusion, we usually store the result of nreverse back in the same variable
which held the original list:
(setq x (nreverse x))
Here is the nreverse of our favorite example, (a b c), presented graphically:
Original list head: Reversed list:
------------- ------------- ------------
| car | cdr | | car | cdr | | car | cdr |
| a | nil |<-- | b | o |<-- | c | o |
| | | | | | | | | | | | |
------------- | --------- | - | -------- | -
| | | |
------------- ------------
Warning: Note that the list in nums no longer contains 0; this is the same cons cell
that it was before, but it is no longer the first one in the list. Don’t assume a variable
that formerly held the argument now holds the entire sorted list! Instead, save the
result of sort and use that. Most often we store the result back into the variable that
held the original list:
(setq nums (sort nums ’<))
See Section 32.15 [Sorting], page 605, for more functions that perform sorting. See
documentation in Section 24.2 [Accessing Documentation], page 426, for a useful
example of sort.
When delq deletes elements from the front of the list, it does so simply by advancing
down the list and returning a sublist that starts after those elements:
(delq ’a ’(a b c)) ≡ (cdr ’(a b c))
When an element to be deleted appears in the middle of the list, removing it involves
changing the cdrs (see Section 5.6.2 [Setcdr], page 74).
(setq sample-list ’(a b c (4)))
⇒ (a b c (4))
(delq ’a sample-list)
⇒ (b c (4))
sample-list
⇒ (a b c (4))
Chapter 5: Lists 79
(delq ’c sample-list)
⇒ (a b (4))
sample-list
⇒ (a b (4))
Note that (delq ’c sample-list) modifies sample-list to splice out the third element,
but (delq ’a sample-list) does not splice anything—it just returns a shorter list. Don’t
assume that a variable which formerly held the argument list now has fewer elements, or
that it still holds the original list! Instead, save the result of delq and use that. Most often
we store the result back into the variable that held the original list:
(setq flowers (delq ’rose flowers))
In the following example, the (4) that delq attempts to match and the (4) in the
sample-list are not eq:
(delq ’(4) sample-list)
⇒ (a c (4))
The following three functions are like memq, delq and remq, but use equal rather than
eq to compare elements. See Section 2.7 [Equality Predicates], page 30.
member object list [Function]
The function member tests to see whether object is a member of list, comparing
members with object using equal. If object is a member, member returns a list
starting with its first occurrence in list. Otherwise, it returns nil.
Chapter 5: Lists 80
Common Lisp note: The functions member, delete and remove in GNU Emacs
Lisp are derived from Maclisp, not Common Lisp. The Common Lisp versions
do not use equal to compare elements.
Chapter 5: Lists 81
Note that property lists are similar to association lists in several respects. A property
list behaves like an association list in which each key can occur only once. See Section 8.4
[Property Lists], page 107, for a comparison of property lists and association lists.
The function assoc-string is much like assoc except that it ignores certain differences
between strings. See Section 4.5 [Text Comparison], page 52.
The newest element in the ring always has index 0. Higher indices correspond to older
elements. Indices are computed modulo the ring length. Index −1 corresponds to the oldest
element, −2 to the next-oldest, and so forth.
If you are careful not to exceed the ring size, you can use the ring as a first-in-first-out
queue. For example:
(let ((fifo (make-ring 5)))
(mapc (lambda (obj) (ring-insert fifo obj))
’(0 one "two"))
(list (ring-remove fifo) t
Chapter 5: Lists 86
(ring-remove fifo) t
(ring-remove fifo)))
⇒ (0 t one t "two")
Chapter 6: Sequences, Arrays, and Vectors 87
6.1 Sequences
In Emacs Lisp, a sequence is either a list or an array. The common property of all sequences
is that they are ordered collections of elements. This section describes functions that accept
any kind of sequence.
sequencep object [Function]
Returns t if object is a list, vector, string, bool-vector, or char-table, nil otherwise.
length sequence [Function]
This function returns the number of elements in sequence. If sequence is a dotted list,
a wrong-type-argument error is signaled. Circular lists may cause an infinite loop.
For a char-table, the value returned is always one more than the maximum Emacs
character code.
See [Definition of safe-length], page 66, for the related function safe-length.
Chapter 6: Sequences, Arrays, and Vectors 88
(eq x y)
⇒ nil
(equal x y)
⇒ t
(eq (elt x 1) (elt y 1))
⇒ t
6.2 Arrays
An array object has slots that hold a number of other Lisp objects, called the elements
of the array. Any element of an array may be accessed in constant time. In contrast, an
element of a list requires access time that is proportional to the position of the element in
the list.
Emacs defines four types of array, all one-dimensional: strings, vectors, bool-vectors and
char-tables. A vector is a general array; its elements can be any Lisp objects. A string is
a specialized array; its elements must be characters. Each type of array has its own read
syntax. See Section 2.3.8 [String Type], page 18, and Section 2.3.9 [Vector Type], page 20.
All four kinds of array share these characteristics:
• The first element of an array has index zero, the second element has index 1, and so on.
This is called zero-origin indexing. For example, an array of four elements has indices
0, 1, 2, and 3.
• The length of the array is fixed once you create it; you cannot change the length of an
existing array.
• For purposes of evaluation, the array is a constant—in other words, it evaluates to
itself.
• The elements of an array may be referenced or changed with the functions aref and
aset, respectively (see Section 6.3 [Array Functions], page 90).
Chapter 6: Sequences, Arrays, and Vectors 90
When you create an array, other than a char-table, you must specify its length. You can-
not specify the length of a char-table, because that is determined by the range of character
codes.
In principle, if you want an array of text characters, you could use either a string or a
vector. In practice, we always choose strings for such applications, for four reasons:
• They occupy one-fourth the space of a vector of the same elements.
• Strings are printed in a way that shows the contents more clearly as text.
• Strings can hold text properties. See Section 32.19 [Text Properties], page 615.
• Many of the specialized editing and I/O facilities of Emacs accept only strings. For
example, you cannot insert a vector of characters into a buffer the way you can insert
a string. See Chapter 4 [Strings and Characters], page 47.
By contrast, for an array of keyboard input characters (such as a key sequence), a vector
may be necessary, because many keyboard input characters are outside the range that will
fit in a string. See Section 21.7.1 [Key Sequence Input], page 330.
(setq x "asdfasfd")
⇒ "asdfasfd"
(aset x 3 ?Z)
⇒ 90
x
⇒ "asdZasfd"
If array is a string and object is not a character, a wrong-type-argument error results.
The function converts a unibyte string to multibyte if necessary to insert a character.
The general sequence functions copy-sequence and length are often useful for objects
known to be arrays. See Section 6.1 [Sequence Functions], page 87.
6.4 Vectors
Arrays in Lisp, like arrays in most languages, are blocks of memory whose elements can
be accessed in constant time. A vector is a general-purpose array of specified length;
its elements can be any Lisp objects. (By contrast, a string can hold only characters as
elements.) Vectors in Emacs are used for obarrays (vectors of symbols), and as part of
keymaps (vectors of commands). They are also used internally as part of the representation
of a byte-compiled function; if you print such a function, you will see a vector in it.
In Emacs Lisp, the indices of the elements of a vector start from zero and count up from
there.
Vectors are printed with square brackets surrounding the elements. Thus, a vector whose
elements are the symbols a, b and a is printed as [a b a]. You can write vectors in the
same way in Lisp input.
A vector, like a string or a number, is considered a constant for evaluation: the result
of evaluating it is the same vector. This does not evaluate or even examine the elements of
the vector. See Section 9.1.1 [Self-Evaluating Forms], page 111.
Here are examples illustrating these principles:
Chapter 6: Sequences, Arrays, and Vectors 92
In Emacs versions before 21, the vconcat function allowed integers as arguments, con-
verting them to strings of digits, but that feature has been eliminated. The proper
way to convert an integer to a decimal number in this way is with format (see Sec-
tion 4.7 [Formatting Strings], page 56) or number-to-string (see Section 4.6 [String
Conversion], page 54).
For other concatenation functions, see mapconcat in Section 12.6 [Mapping Func-
tions], page 168, concat in Section 4.3 [Creating Strings], page 48, and append in
Section 5.4 [Building Lists], page 67.
The append function also provides a way to convert a vector into a list with the same
elements:
(setq avector [1 two (quote (three)) "four" [five]])
⇒ [1 two (quote (three)) "four" [five]]
(append avector nil)
⇒ (1 two (quote (three)) "four" [five])
6.6 Char-Tables
A char-table is much like a vector, except that it is indexed by character codes. Any valid
character code, without modifiers, can be used as an index in a char-table. You can access
a char-table’s elements with aref and aset, as with any array. In addition, a char-table
can have extra slots to hold additional data not associated with particular character codes.
Char-tables are constants when evaluated.
Each char-table has a subtype which is a symbol. The subtype has two purposes: to
distinguish char-tables meant for different uses, and to control the number of extra slots.
For example, display tables are char-tables with display-table as the subtype, and syntax
tables are char-tables with syntax-table as the subtype. A valid subtype must have a
char-table-extra-slots property which is an integer between 0 and 10. This integer
specifies the number of extra slots in the char-table.
A char-table can have a parent, which is another char-table. If it does, then whenever
the char-table specifies nil for a particular character c, it inherits the value specified in
the parent. In other words, (aref char-table c ) returns the value from the parent of
char-table if char-table itself specifies nil.
A char-table can also have a default value. If so, then (aref char-table c ) returns
the default value whenever the char-table does not specify any other non-nil value.
make-char-table subtype &optional init [Function]
Return a newly created char-table, with subtype subtype. Each element is initialized
to init, which defaults to nil. You cannot alter the subtype of a char-table after the
char-table is created.
There is no argument to specify the length of the char-table, because all char-tables
have room for any valid character code as an index.
char-table-p object [Function]
This function returns t if object is a char-table, otherwise nil.
char-table-subtype char-table [Function]
This function returns the subtype symbol of char-table.
Chapter 6: Sequences, Arrays, and Vectors 94
generic-char
A generic character stands for a character set; specifying the generic
character as argument is equivalent to specifying the character set name.
See Section 33.7 [Splitting Characters], page 645, for a description of
generic characters.
6.7 Bool-vectors
A bool-vector is much like a vector, except that it stores only the values t and nil. If you
try to store any non-nil value into an element of the bool-vector, the effect is to store t
there. As with all arrays, bool-vector indices start from 0, and the length cannot be changed
once the bool-vector is created. Bool-vectors are constants when evaluated.
There are two special functions for working with bool-vectors; aside from that, you
manipulate them with same functions used for other kinds of arrays.
Here is an example of creating, examining, and updating a bool-vector. Note that the
printed form represents up to 8 boolean values as a single character.
(setq bv (make-bool-vector 5 t))
⇒ #&5"^_"
(aref bv 1)
⇒ t
Chapter 6: Sequences, Arrays, and Vectors 96
(aset bv 3 nil)
⇒ nil
bv
⇒ #&5"^W"
These results make sense because the binary codes for control- and control-W are 11111
and 10111, respectively.
Chapter 7: Hash Tables 97
7 Hash Tables
A hash table is a very fast kind of lookup table, somewhat like an alist (see Section 5.8
[Association Lists], page 81) in that it maps keys to corresponding values. It differs from
an alist in these ways:
• Lookup in a hash table is extremely fast for large tables—in fact, the time required
is essentially independent of how many elements are stored in the table. For smaller
tables (a few tens of elements) alists may still be faster because hash tables have a
more-or-less constant overhead.
• The correspondences in a hash table are in no particular order.
• There is no way to share structure between two hash tables, the way two alists can
share a common tail.
Emacs Lisp provides a general-purpose hash table data type, along with a series of
functions for operating on them. Hash tables have no read syntax, and print in hash
notation, like this:
(make-hash-table)
⇒ #<hash-table ’eql nil 0/65 0x83af980>
(The term “hash notation” refers to the initial ‘#’ character—see Section 2.1 [Printed Rep-
resentation], page 8—and has nothing to do with the term “hash table.”)
Obarrays are also a kind of hash table, but they are a different type of object and are
used only for recording interned symbols (see Section 8.3 [Creating Symbols], page 104).
:weakness weak
The weakness of a hash table specifies whether the presence of a key or
value in the hash table preserves it from garbage collection.
The value, weak, must be one of nil, key, value, key-or-value, key-
and-value, or t which is an alias for key-and-value. If weak is key then
the hash table does not prevent its keys from being collected as garbage
(if they are not referenced anywhere else); if a particular key does get
collected, the corresponding association is removed from the hash table.
If weak is value, then the hash table does not prevent values from being
collected as garbage (if they are not referenced anywhere else); if a par-
ticular value does get collected, the corresponding association is removed
from the hash table.
If weak is key-and-value or t, both the key and the value must be live in
order to preserve the association. Thus, the hash table does not protect
either keys or values from garbage collection; if either one is collected as
garbage, that removes the association.
If weak is key-or-value, either the key or the value can preserve the as-
sociation. Thus, associations are removed from the hash table when both
their key and value would be collected as garbage (if not for references
from weak hash tables).
The default for weak is nil, so that all keys and values referenced in the
hash table are preserved from garbage collection.
:size size
This specifies a hint for how many associations you plan to store in the
hash table. If you know the approximate number, you can make things
a little more efficient by specifying it this way. If you specify too small
a size, the hash table will grow automatically when necessary, but doing
that takes some extra time.
The default size is 65.
:rehash-size rehash-size
When you add an association to a hash table and the table is “full,” it
grows automatically. This value specifies how to make the hash table
larger, at that time.
If rehash-size is an integer, it should be positive, and the hash table grows
by adding that much to the nominal size. If rehash-size is a floating point
number, it had better be greater than 1, and the hash table grows by
multiplying the old size by that number.
The default value is 1.5.
:rehash-threshold threshold
This specifies the criterion for when the hash table is “full” (so it should
be made larger). The value, threshold, should be a positive floating point
number, no greater than 1. The hash table is “full” whenever the actual
number of entries exceeds this fraction of the nominal size. The default
for threshold is 0.8.
Chapter 7: Hash Tables 99
This example creates a hash table whose keys are strings that are compared case-
insensitively.
(defun case-fold-string= (a b)
(compare-strings a nil nil b nil nil t))
(defun case-fold-string-hash (a)
(sxhash (upcase a)))
(define-hash-table-test ’case-fold
’case-fold-string= ’case-fold-string-hash)
8 Symbols
A symbol is an object with a unique name. This chapter describes symbols, their com-
ponents, their property lists, and how they are created and interned. Separate chapters
describe the use of symbols as variables and as function names; see Chapter 11 [Variables],
page 135, and Chapter 12 [Functions], page 160. For the precise read syntax for symbols,
see Section 2.3.4 [Symbol Type], page 13.
You can test whether an arbitrary Lisp object is a symbol with symbolp:
symbolp object [Function]
This function returns t if object is a symbol, nil otherwise.
In normal usage, the function cell usually contains a function (see Chapter 12 [Functions],
page 160) or a macro (see Chapter 13 [Macros], page 176), as that is what the Lisp inter-
preter expects to see there (see Chapter 9 [Evaluation], page 110). Keyboard macros (see
Section 21.15 [Keyboard Macros], page 345), keymaps (see Chapter 22 [Keymaps], page 347)
and autoload objects (see Section 9.1.8 [Autoloading], page 115) are also sometimes stored
in the function cells of symbols.
The property list cell normally should hold a correctly formatted property list (see
Section 8.4 [Property Lists], page 107), as a number of functions expect to see a property
list there.
The function cell or the value cell may be void, which means that the cell does not
reference any object. (This is not the same thing as holding the symbol void, nor the same
as holding the symbol nil.) Examining a function or value cell that is void results in an
error, such as ‘Symbol’s value as variable is void’.
The four functions symbol-name, symbol-value, symbol-plist, and symbol-function
return the contents of the four cells of a symbol. Here as an example we show the contents
of the four cells of the symbol buffer-file-name:
(symbol-name ’buffer-file-name)
⇒ "buffer-file-name"
(symbol-value ’buffer-file-name)
⇒ "/gnu/elisp/symbols.texi"
(symbol-function ’buffer-file-name)
⇒ #<subr buffer-file-name>
(symbol-plist ’buffer-file-name)
⇒ (variable-documentation 29529)
Because this symbol is the variable which holds the name of the file being visited in the
current buffer, the value cell contents we see are the name of the source file of this chapter of
the Emacs Lisp Manual. The property list cell contains the list (variable-documentation
29529) which tells the documentation functions where to find the documentation string
for the variable buffer-file-name in the ‘DOC-version ’ file. (29529 is the offset from
the beginning of the ‘DOC-version ’ file to where that documentation string begins—see
Section 24.1 [Documentation Basics], page 425.) The function cell contains the function for
returning the name of the file. buffer-file-name names a primitive function, which has
no read syntax and prints in hash notation (see Section 2.3.15 [Primitive Function Type],
page 22). A symbol naming a function written in Lisp would have a lambda expression (or
a byte-code object) in this cell.
defvar and defconst are special forms that define a symbol as a global variable. They
are documented in detail in Section 11.5 [Defining Variables], page 139. For defining user
option variables that can be customized, use defcustom (see Chapter 14 [Customization],
page 185).
defun defines a symbol as a function, creating a lambda expression and storing it in the
function cell of the symbol. This lambda expression thus becomes the function definition of
the symbol. (The term “function definition,” meaning the contents of the function cell, is
derived from the idea that defun gives the symbol its definition as a function.) defsubst
and defalias are two other ways of defining a function. See Chapter 12 [Functions],
page 160.
defmacro defines a symbol as a macro. It creates a macro object and stores it in the
function cell of the symbol. Note that a given symbol can be a macro or a function, but
not both at once, because both macro and function definitions are kept in the function cell,
and that cell can hold only one Lisp object at any given time. See Chapter 13 [Macros],
page 176.
In Emacs Lisp, a definition is not required in order to use a symbol as a variable or
function. Thus, you can make a symbol a global variable with setq, whether you define
it first or not. The real purpose of definitions is to guide programmers and programming
tools. They inform programmers who read the code that certain symbols are intended to be
used as variables, or as functions. In addition, utilities such as ‘etags’ and ‘make-docfile’
recognize definitions, and add appropriate information to tag tables and the ‘DOC-version ’
file. See Section 24.2 [Accessing Documentation], page 426.
Interning usually happens automatically in the reader, but sometimes other programs
need to do it. For example, after the M-x command obtains the command name as a string
using the minibuffer, it then interns the string, to get the interned symbol with that name.
No obarray contains all symbols; in fact, some symbols are not in any obarray. They are
called uninterned symbols. An uninterned symbol has the same four cells as other symbols;
however, the only way to gain access to it is by finding it in some other object or as the
value of a variable.
Creating an uninterned symbol is useful in generating Lisp code, because an uninterned
symbol used as a variable in the code you generate cannot clash with any variables used in
other Lisp programs.
In Emacs Lisp, an obarray is actually a vector. Each element of the vector is a bucket;
its value is either an interned symbol whose name hashes to that bucket, or 0 if the bucket is
empty. Each interned symbol has an internal link (invisible to the user) to the next symbol
in the bucket. Because these links are invisible, there is no way to find all the symbols in an
obarray except using mapatoms (below). The order of symbols in a bucket is not significant.
In an empty obarray, every element is 0, so you can create an obarray with (make-vector
length 0). This is the only valid way to create an obarray. Prime numbers as lengths tend
to result in good hashing; lengths one less than a power of two are also good.
Do not try to put symbols in an obarray yourself. This does not work—only intern
can enter a symbol in an obarray properly.
Common Lisp note: In Common Lisp, a single symbol may be interned in
several obarrays.
Most of the functions below take a name and sometimes an obarray as arguments. A
wrong-type-argument error is signaled if the name is not a string, or if the obarray is not
a vector.
symbol-name symbol [Function]
This function returns the string that is symbol’s name. For example:
(symbol-name ’foo)
⇒ "foo"
Warning: Changing the string by substituting characters does change the name of
the symbol, but fails to update the obarray, so don’t do it!
make-symbol name [Function]
This function returns a newly-allocated, uninterned symbol whose name is name
(which must be a string). Its value and function definition are void, and its property
list is nil. In the example below, the value of sym is not eq to foo because it is a
distinct uninterned symbol whose name is also ‘foo’.
(setq sym (make-symbol "foo"))
⇒ foo
(eq sym ’foo)
⇒ nil
intern name &optional obarray [Function]
This function returns the interned symbol whose name is name. If there is no such
symbol in the obarray obarray, intern creates a new one, adds it to the obarray, and
returns it. If obarray is omitted, the value of the global variable obarray is used.
Chapter 8: Symbols 106
Common Lisp note: In Common Lisp, you can intern an existing symbol in an
obarray. In Emacs Lisp, you cannot do this, because the argument to intern
must be a string, not a symbol.
intern-soft name &optional obarray [Function]
This function returns the symbol in obarray whose name is name, or nil if obarray
has no symbol with that name. Therefore, you can use intern-soft to test whether
a symbol with a given name is already interned. If obarray is omitted, the value of
the global variable obarray is used.
The argument name may also be a symbol; in that case, the function returns name
if name is interned in the specified obarray, and otherwise nil.
(intern-soft "frazzle") ; No such symbol exists.
⇒ nil
(make-symbol "frazzle") ; Create an uninterned one.
⇒ frazzle
(intern-soft "frazzle") ; That one cannot be found.
⇒ nil
(setq sym (intern "frazzle")) ; Create an interned one.
⇒ frazzle
(intern-soft "frazzle") ; That one can be found!
⇒ frazzle
(eq sym ’frazzle) ; And it is the same one.
⇒ t
obarray [Variable]
This variable is the standard obarray for use by intern and read.
mapatoms function &optional obarray [Function]
This function calls function once with each symbol in the obarray obarray. Then it
returns nil. If obarray is omitted, it defaults to the value of obarray, the standard
obarray for ordinary symbols.
(setq count 0)
⇒ 0
(defun count-syms (s)
(setq count (1+ count)))
⇒ count-syms
(mapatoms ’count-syms)
⇒ nil
count
⇒ 1871
See documentation in Section 24.2 [Accessing Documentation], page 426, for another
example using mapatoms.
Chapter 8: Symbols 107
It accepts a malformed plist argument and always returns nil if property is not found
in the plist. For example,
(plist-get ’(foo 4 bad) ’bar)
⇒ nil
9 Evaluation
The evaluation of expressions in Emacs Lisp is performed by the Lisp interpreter—a program
that receives a Lisp object as input and computes its value as an expression. How it does
this depends on the data type of the object, according to rules described in this chapter.
The interpreter runs automatically to evaluate portions of your program, but can also be
called explicitly via the Lisp primitive function eval.
A Lisp object that is intended for evaluation is called an expression or a form. The
fact that expressions are data objects and not merely text is one of the fundamental differ-
ences between Lisp-like languages and typical programming languages. Any object can be
evaluated, but in practice only numbers, symbols, lists and strings are evaluated very often.
It is very common to read a Lisp expression and then evaluate the expression, but reading
and evaluation are separate activities, and either can be performed alone. Reading per se
does not evaluate anything; it converts the printed representation of a Lisp object to the
object itself. It is up to the caller of read whether this object is a form to be evaluated, or
serves some entirely different purpose. See Section 19.3 [Input Functions], page 271.
Do not confuse evaluation with command key interpretation. The editor command
loop translates keyboard input into a command (an interactively callable function) using
the active keymaps, and then uses call-interactively to invoke the command. The
execution of the command itself involves evaluation if the command is written in Lisp, but
that is not a part of command key interpretation itself. See Chapter 21 [Command Loop],
page 304.
Evaluation is a recursive process. That is, evaluation of a form may call eval to evaluate
parts of the form. For example, evaluation of a function call first evaluates each argument
of the function call, and then evaluates each form in the function body. Consider evaluation
of the form (car x): the subform x must first be evaluated recursively, so that its value can
be passed as an argument to the function car.
Evaluation of a function call ultimately calls the function specified in it. See Chapter 12
[Functions], page 160. The execution of the function may itself work by evaluating the
function definition; or the function may be a Lisp primitive implemented in C, or it may be
a byte-compiled function (see Chapter 16 [Byte Compilation], page 214).
The evaluation of forms takes place in a context called the environment, which consists of
the current values and bindings of all Lisp variables.1 Whenever a form refers to a variable
without creating a new binding for it, the value of the variable’s binding in the current
environment is used. See Chapter 11 [Variables], page 135.
Evaluation of a form may create new environments for recursive evaluation by binding
variables (see Section 11.3 [Local Variables], page 136). These environments are temporary
and vanish by the time evaluation of the form is complete. The form may also make changes
that persist; these changes are called side effects. An example of a form that produces side
effects is (setq foo 1).
The details of what evaluation means for each kind of form are described below (see
Section 9.1 [Forms], page 111).
1
This definition of “environment” is specifically not intended to include all the data that can affect the
result of a program.
Chapter 9: Evaluation 111
The symbols nil and t are treated specially, so that the value of nil is always nil, and
the value of t is always t; you cannot set or bind them to any other values. Thus, these two
symbols act like self-evaluating forms, even though eval treats them like any other symbol.
A symbol whose name starts with ‘:’ also self-evaluates in the same way; likewise, its value
ordinarily cannot be changed. See Section 11.2 [Constant Variables], page 135.
Executing the function itself evaluates its body; this does involve symbol function indirection
when calling erste.
The built-in function indirect-function provides an easy way to perform symbol func-
tion indirection explicitly.
Ordinary evaluation of a macro call finishes by evaluating the expansion. However, the
macro expansion is not necessarily evaluated right away, or at all, because other programs
also expand macro calls, and they may or may not evaluate the expansions.
Normally, the argument expressions are not evaluated as part of computing the macro
expansion, but instead appear as part of the expansion, so they are computed when the
expansion is evaluated.
For example, given a macro defined as follows:
(defmacro cadr (x)
(list ’car (list ’cdr x)))
an expression such as (cadr (assq ’handler list)) is a macro call, and its expansion is:
(car (cdr (assq ’handler list)))
Note that the argument (assq ’handler list) appears in the expansion.
See Chapter 13 [Macros], page 176, for a complete description of Emacs Lisp macros.
prog1
prog2
progn see Section 10.1 [Sequencing], page 119
quote see Section 9.2 [Quoting], page 115
save-current-buffer
see Section 27.2 [Current Buffer], page 481
save-excursion
see Section 30.3 [Excursions], page 568
save-restriction
see Section 30.4 [Narrowing], page 569
save-window-excursion
see Section 28.18 [Window Configurations], page 526
setq see Section 11.8 [Setting Variables], page 143
setq-default
see Section 11.10.2 [Creating Buffer-Local], page 149
track-mouse
see Section 29.13 [Mouse Tracking], page 547
unwind-protect
see Section 10.5 [Nonlocal Exits], page 125
while see Section 10.4 [Iteration], page 124
with-output-to-temp-buffer
see Section 38.8 [Temporary Displays], page 752
Common Lisp note: Here are some comparisons of special forms in GNU Emacs
Lisp and Common Lisp. setq, if, and catch are special forms in both Emacs
Lisp and Common Lisp. defun is a special form in Emacs Lisp, but a macro in
Common Lisp. save-excursion is a special form in Emacs Lisp, but doesn’t
exist in Common Lisp. throw is a special form in Common Lisp (because it
must be able to throw multiple values), but it is a function in Emacs Lisp (which
doesn’t have multiple values).
9.1.8 Autoloading
The autoload feature allows you to call a function or macro whose function definition has
not yet been loaded into Emacs. It specifies which file contains the definition. When an
autoload object appears as a symbol’s function definition, calling that symbol as a function
automatically loads the specified file; then it calls the real definition loaded from that file.
See Section 15.5 [Autoload], page 206.
9.2 Quoting
The special form quote returns its single argument, as written, without evaluating it. This
provides a way to include constant symbols and lists, which are not self-evaluating objects,
in a program. (It is not necessary to quote self-evaluating objects such as numbers, strings,
and vectors.)
Chapter 9: Evaluation 116
9.3 Eval
Most often, forms are evaluated automatically, by virtue of their occurrence in a program
being run. On rare occasions, you may need to write code that evaluates a form that is
computed at run time, such as after reading a form from text being edited or getting one
from a property list. On these occasions, use the eval function.
The functions and variables described in this section evaluate forms, specify limits to the
evaluation process, or record recently returned values. Loading a file also does evaluation
(see Chapter 15 [Loading], page 201).
It is generally cleaner and more flexible to store a function in a data structure, and call
it with funcall or apply, than to store an expression in the data structure and evaluate
it. Using functions provides the ability to pass information to them as arguments.
eval form [Function]
This is the basic function evaluating an expression. It evaluates form in the current
environment and returns the result. How the evaluation proceeds depends on the
type of the object (see Section 9.1 [Forms], page 111).
Since eval is a function, the argument expression that appears in a call to eval is
evaluated twice: once as preparation before eval is called, and again by the eval
function itself. Here is an example:
(setq foo ’bar)
⇒ bar
Chapter 9: Evaluation 117
max-lisp-eval-depth [Variable]
This variable defines the maximum depth allowed in calls to eval, apply, and funcall
before an error is signaled (with error message "Lisp nesting exceeds max-lisp-
eval-depth").
This limit, with the associated error when it is exceeded, is one way Emacs Lisp
avoids infinite recursion on an ill-defined function. If you increase the value of max-
lisp-eval-depth too much, such code can cause stack overflow instead.
Chapter 9: Evaluation 118
The depth limit counts internal uses of eval, apply, and funcall, such as for calling
the functions mentioned in Lisp expressions, and recursive evaluation of function call
arguments and function body forms, as well as explicit calls in Lisp code.
The default value of this variable is 300. If you set it to a value less than 100, Lisp
will reset it to 100 if the given value is reached. Entry to the Lisp debugger increases
the value, if there is little room left, to make sure the debugger itself has room to
execute.
max-specpdl-size provides another limit on nesting. See [Local Variables], page 137.
values [Variable]
The value of this variable is a list of the values returned by all the expressions that were
read, evaluated, and printed from buffers (including the minibuffer) by the standard
Emacs commands which do this. (Note that this does not include evaluation in
‘*ielm*’ buffers, nor evaluation using C-j in lisp-interaction-mode.) The elements
are ordered most recent first.
(setq x 1)
⇒ 1
(list ’A (1+ 2) auto-save-default)
⇒ (A 3 t)
values
⇒ ((A 3 t) 1 ...)
This variable is useful for referring back to values of forms recently evaluated. It is
generally a bad idea to print the value of values itself, since this may be very long.
Instead, examine particular elements, like this:
;; Refer to the most recent evaluation result.
(nth 0 values)
⇒ (A 3 t)
;; That put a new element on,
;; so all elements move back one.
(nth 1 values)
⇒ (A 3 t)
;; This gets the element that was next-to-most-recent
;; before this example.
(nth 3 values)
⇒ 1
Chapter 10: Control Structures 119
10 Control Structures
A Lisp program consists of expressions or forms (see Section 9.1 [Forms], page 111). We
control the order of execution of these forms by enclosing them in control structures. Control
structures are special forms which control when, whether, or how many times to execute
the forms they contain.
The simplest order of execution is sequential execution: first form a, then form b, and
so on. This is what happens when you write several forms in succession in the body of a
function, or at top level in a file of Lisp code—the forms are executed in the order written.
We call this textual order. For example, if a function body consists of two forms a and b,
evaluation of the function evaluates first a and then b. The result of evaluating b becomes
the value of the function.
Explicit control structures make possible an order of execution other than sequential.
Emacs Lisp provides several kinds of control structure, including other varieties of se-
quencing, conditionals, iteration, and (controlled) jumps—all discussed below. The built-in
control structures are special forms since their subforms are not necessarily evaluated or not
evaluated sequentially. You can use macros to define your own control structure constructs
(see Chapter 13 [Macros], page 176).
10.1 Sequencing
Evaluating forms in the order they appear is the most common way control passes from one
form to another. In some contexts, such as in a function body, this happens automatically.
Elsewhere you must use a control structure construct to do this: progn, the simplest control
construct of Lisp.
A progn special form looks like this:
(progn a b c ...)
and it says to execute the forms a, b, c, and so on, in that order. These forms are called
the body of the progn form. The value of the last form in the body becomes the value of
the entire progn. (progn) returns nil.
In the early days of Lisp, progn was the only way to execute two or more forms in
succession and use the value of the last of them. But programmers found they often needed
to use a progn in the body of a function, where (at that time) only one form was allowed.
So the body of a function was made into an “implicit progn”: several forms are allowed
just as in the body of an actual progn. Many other control structures likewise contain an
implicit progn. As a result, progn is not used as much as it was many years ago. It is
needed now most often inside an unwind-protect, and, or, or in the then-part of an if.
Two other control constructs likewise evaluate a series of forms but return a different
value:
prog1 form1 forms. . . [Special Form]
This special form evaluates form1 and all of the forms, in textual order, returning the
result of form1.
(prog1 (print "The first form")
(print "The second form")
(print "The third form"))
a "The first form"
a "The second form"
a "The third form"
⇒ "The first form"
Here is a way to remove the first element from a list in the variable x, then return
the value of that former element:
(prog1 (car x) (setq x (cdr x)))
prog2 form1 form2 forms. . . [Special Form]
This special form evaluates form1, form2, and all of the following forms, in textual
order, returning the result of form2.
(prog2 (print "The first form")
(print "The second form")
(print "The third form"))
a "The first form"
a "The second form"
a "The third form"
⇒ "The second form"
10.2 Conditionals
Conditional control structures choose among alternatives. Emacs Lisp has four conditional
forms: if, which is much the same as in other languages; when and unless, which are
variants of if; and cond, which is a generalized case statement.
if condition then-form else-forms. . . [Special Form]
if chooses between the then-form and the else-forms based on the value of condition.
If the evaluated condition is non-nil, then-form is evaluated and the result returned.
Otherwise, the else-forms are evaluated in textual order, and the value of the last one
is returned. (The else part of if is an example of an implicit progn. See Section 10.1
[Sequencing], page 119.)
Chapter 10: Control Structures 121
If condition has the value nil, and no else-forms are given, if returns nil.
if is a special form because the branch that is not selected is never evaluated—it
is ignored. Thus, in the example below, true is not printed because print is never
called.
(if nil
(print ’true)
’very-false)
⇒ very-false
(cond ((numberp x) x)
((stringp x) x)
((bufferp x)
(setq temporary-hack x) ; multiple body-forms
(buffer-name x)) ; in one clause
((symbolp x) (symbol-value x)))
Often we want to execute the last clause whenever none of the previous clauses was
successful. To do this, we use t as the condition of the last clause, like this: (t
body-forms ). The form t evaluates to t, which is never nil, so this clause never
fails, provided the cond gets to it at all.
For example,
(setq a 5)
(cond ((eq a ’hack) ’foo)
(t "default"))
⇒ "default"
This cond expression returns foo if the value of a is hack, and returns the string
"default" otherwise.
Any conditional construct can be expressed with cond or with if. Therefore, the choice
between them is a matter of style. For example:
(if a b c )
≡
(cond (a b ) (t c ))
10.4 Iteration
Iteration means executing part of a program repetitively. For example, you might want to
repeat some computation once for each element of a list, or once for each integer from 0 to
n. You can do this in Emacs Lisp with the special form while:
The dolist and dotimes macros provide convenient ways to write two common kinds
of loops.
(defun foo-inner ()
...
(if x
(throw ’foo t))
...)
The throw form, if executed, transfers control straight back to the corresponding catch,
which returns immediately. The code following the throw is not executed. The second
argument of throw is used as the return value of the catch.
The function throw finds the matching catch based on the first argument: it searches for
a catch whose first argument is eq to the one specified in the throw. If there is more than
one applicable catch, the innermost one takes precedence. Thus, in the above example, the
throw specifies foo, and the catch in foo-outer specifies the same symbol, so that catch
is the applicable one (assuming there is no other matching catch in between).
Executing throw exits all Lisp constructs up to the matching catch, including function
calls. When binding constructs such as let or function calls are exited in this way, the
bindings are unbound, just as they are when these constructs exit normally (see Section 11.3
[Local Variables], page 136). Likewise, throw restores the buffer and position saved by
save-excursion (see Section 30.3 [Excursions], page 568), and the narrowing status saved
by save-restriction and the window selection saved by save-window-excursion (see
Section 28.18 [Window Configurations], page 526). It also runs any cleanups established
with the unwind-protect special form when it exits that form (see Section 10.5.4 [Cleanups],
page 133).
Chapter 10: Control Structures 126
The throw need not appear lexically within the catch that it jumps to. It can equally
well be called from another function called within the catch. As long as the throw takes
place chronologically after entry to the catch, and chronologically before exit from it, it
has access to that catch. This is why throw can be used in commands such as exit-
recursive-edit that throw back to the editor command loop (see Section 21.12 [Recursive
Editing], page 342).
Common Lisp note: Most other versions of Lisp, including Common Lisp, have
several ways of transferring control nonsequentially: return, return-from, and
go, for example. Emacs Lisp has only throw.
catch tag body. . . [Special Form]
catch establishes a return point for the throw function. The return point is distin-
guished from other such return points by tag, which may be any Lisp object except
nil. The argument tag is evaluated normally before the return point is established.
With the return point in effect, catch evaluates the forms of the body in textual
order. If the forms execute normally (without error or nonlocal exit) the value of the
last body form is returned from the catch.
If a throw is executed during the execution of body, specifying the same value tag,
the catch form exits immediately; the value it returns is whatever was specified as
the second argument of throw.
throw tag value [Function]
The purpose of throw is to return from a return point previously established with
catch. The argument tag is used to choose among the various existing return points;
it must be eq to the value specified in the catch. If multiple return points match tag,
the innermost one is used.
The argument value is used as the value to return from that catch.
If no return point is in effect with tag tag, then a no-catch error is signaled with
data (tag value ).
Here are two tricky examples, slightly different, showing two return points at once. First,
two return points with the same tag, hack:
(catch ’hack
(print (catch2 ’hack))
’no)
a yes
⇒ no
Since both return points have tags that match the throw, it goes to the inner one, the one
established in catch2. Therefore, catch2 returns normally with value yes, and this value
is printed. Finally the second body form in the outer catch, which is ’no, is evaluated and
returned from the outer catch.
(catch ’hack
(print (catch2 ’quux))
’no)
⇒ yes
We still have two return points, but this time only the outer one has the tag hack; the inner
one has the tag quux instead. Therefore, throw makes the outer catch return the value
yes. The function print is never called, and the body-form ’no is never evaluated.
10.5.3 Errors
When Emacs Lisp attempts to evaluate a form that, for some reason, cannot be evaluated,
it signals an error.
When an error is signaled, Emacs’s default reaction is to print an error message and
terminate execution of the current command. This is the right thing to do in most cases,
such as if you type C-f at the end of the buffer.
In complicated programs, simple termination may not be what you want. For example,
the program may have made temporary changes in data structures, or created temporary
buffers that should be deleted before the program is finished. In such cases, you would
use unwind-protect to establish cleanup expressions to be evaluated in case of error. (See
Section 10.5.4 [Cleanups], page 133.) Occasionally, you may wish the program to continue
execution despite an error in a subroutine. In these cases, you would use condition-case
to establish error handlers to recover control in case of error.
Resist the temptation to use error handling to transfer control from one part of the
program to another; use catch and throw instead. See Section 10.5.1 [Catch and Throw],
page 125.
Chapter 10: Control Structures 128
predicate that describes the type that was expected, and the object that failed to fit
that type.
Both error-symbol and data are available to any error handlers that handle the error:
condition-case binds a local variable to a list of the form (error-symbol . data )
(see Section 10.5.3.3 [Handling Errors], page 129).
The function signal never returns (though in older Emacs versions it could sometimes
return).
(signal ’wrong-number-of-arguments ’(x y))
error Wrong number of arguments: x, y
Common Lisp note: Emacs Lisp has nothing like the Common Lisp concept of
continuable errors.
command-error-function [Variable]
This variable, if non-nil, specifies a function to use to handle errors that return
control to the Emacs command loop. The function should take three arguments:
data, a list of the same form that condition-case would bind to its variable; context,
a string describing the situation in which the error occurred, or (more often) nil; and
caller, the Lisp function which called the primitive that signaled the error.
An error that has no explicit handler may call the Lisp debugger. The debugger is
enabled if the variable debug-on-error (see Section 18.1.1 [Error Debugging], page 237) is
non-nil. Unlike error handlers, the debugger runs in the environment of the error, so that
you can examine values of variables precisely as they were at the time of the error.
(condition-case nil
(delete-file filename)
(error nil))
This deletes the file named filename, catching any error and returning nil if an error occurs.
The second argument of condition-case is called the protected form. (In the example
above, the protected form is a call to delete-file.) The error handlers go into effect when
this form begins execution and are deactivated when this form returns. They remain in
effect for all the intervening time. In particular, they are in effect during the execution
of functions called by this form, in their subroutines, and so on. This is a good thing,
since, strictly speaking, errors can be signaled only by Lisp primitives (including signal
and error) called by the protected form, not by the protected form itself.
The arguments after the protected form are handlers. Each handler lists one or more
condition names (which are symbols) to specify which errors it will handle. The error
symbol specified when an error is signaled also defines a list of condition names. A handler
applies to an error if they have any condition names in common. In the example above,
there is one handler, and it specifies one condition name, error, which covers all errors.
The search for an applicable handler checks all the established handlers starting with the
most recently established one. Thus, if two nested condition-case forms offer to handle
the same error, the inner of the two gets to handle it.
If an error is handled by some condition-case form, this ordinarily prevents the de-
bugger from being run, even if debug-on-error says this error should invoke the debugger.
See Section 18.1.1 [Error Debugging], page 237. If you want to be able to debug errors that
are caught by a condition-case, set the variable debug-on-signal to a non-nil value.
When an error is handled, control returns to the handler. Before this happens, Emacs
unbinds all variable bindings made by binding constructs that are being exited and executes
the cleanups of all unwind-protect forms that are exited. Once control arrives at the
handler, the body of the handler is executed.
After execution of the handler body, execution returns from the condition-case form.
Because the protected form is exited completely before execution of the handler, the handler
cannot resume execution at the point of the error, nor can it examine variable bindings that
were made within the protected form. All it can do is clean up and proceed.
The condition-case construct is often used to trap errors that are predictable, such as
failure to open a file in a call to insert-file-contents. It is also used to trap errors that
are totally unpredictable, such as when the program evaluates an expression read from the
user.
Error signaling and handling have some resemblance to throw and catch (see Sec-
tion 10.5.1 [Catch and Throw], page 125), but they are entirely separate facilities. An
error cannot be caught by a catch, and a throw cannot be handled by an error handler
(though using throw when there is no suitable catch signals an error that can be handled).
The condition-case form makes a difference when an error occurs during protected-
form.
Each of the handlers is a list of the form (conditions body ...). Here conditions is
an error condition name to be handled, or a list of condition names; body is one or
more Lisp expressions to be executed when this handler handles an error. Here are
examples of handlers:
(error nil)
((arith-error file-error)
(message
"Either division by zero or failure to open a file"))
Each error that occurs has an error symbol that describes what kind of error it
is. The error-conditions property of this symbol is a list of condition names (see
Section 10.5.3.4 [Error Symbols], page 132). Emacs searches all the active condition-
case forms for a handler that specifies one or more of these condition names; the
innermost matching condition-case handles the error. Within this condition-
case, the first applicable handler handles the error.
After executing the body of the handler, the condition-case returns normally, using
the value of the last form in the handler body as the overall value.
The argument var is a variable. condition-case does not bind this variable when
executing the protected-form, only when it handles an error. At that time, it binds
var locally to an error description, which is a list giving the particulars of the error.
The error description has the form (error-symbol . data ). The handler can refer
to this list to decide what to do. For example, if the error is for failure opening a file,
the file name is the second element of data—the third element of the error description.
If var is nil, that means no variable is bound. Then the error symbol and associated
data are not available to the handler.
Here is an example of using condition-case to handle the error that results from
dividing by zero. The handler displays the error message (but without a beep), then returns
a very large number.
(defun safe-divide (dividend divisor)
(condition-case err
;; Protected form.
(/ dividend divisor)
;; The handler.
(arith-error ; Condition.
;; Display the usual message for this error.
(message "%s" (error-message-string err))
1000000)))
⇒ safe-divide
Chapter 10: Control Structures 132
(safe-divide 5 0)
a Arithmetic error: (arith-error)
⇒ 1000000
The handler specifies condition name arith-error so that it will handle only division-by-
zero errors. Other kinds of errors will not be handled, at least not by this condition-case.
Thus,
(safe-divide nil 3)
error Wrong type argument: number-or-marker-p, nil
Here is a condition-case that catches all kinds of errors, including those signaled with
error:
(setq baz 34)
⇒ 34
(condition-case err
(if (eq baz 35)
t
;; This is a call to the function error.
(error "Rats! The variable %s was %s, not 35" ’baz baz))
;; This is the handler; it is not a form.
(error (princ (format "The error was: %s" err))
2))
a The error was: (error "Rats! The variable baz was 34, not 35")
⇒ 2
(put ’new-error
’error-conditions
’(error my-own-errors new-error))
⇒ (error my-own-errors new-error)
(put ’new-error ’error-message "A new error")
⇒ "A new error"
This error has three condition names: new-error, the narrowest classification; my-own-
errors, which we imagine is a wider classification; and error, which is the widest of all.
The error string should start with a capital letter but it should not end with a period.
This is for consistency with the rest of Emacs.
Naturally, Emacs will never signal new-error on its own; only an explicit call to signal
(see [Definition of signal], page 128) in your code can do this:
(signal ’new-error ’(x y))
error A new error: x, y
This error can be handled through any of the three condition names. This example
handles new-error and any other errors in the class my-own-errors:
(condition-case foo
(bar nil t)
(my-own-errors nil))
The significant way that errors are classified is by their condition names—the names
used to match errors with handlers. An error symbol serves only as a convenient way to
specify the intended error message and list of condition names. It would be cumbersome to
give signal a list of condition names rather than one error symbol.
By contrast, using only error symbols without condition names would seriously decrease
the power of condition-case. Condition names make it possible to categorize errors at
various levels of generality when you write an error handler. Using error symbols alone
would eliminate all but the narrowest level of classification.
See Appendix F [Standard Errors], page 891, for a list of all the standard error symbols
and their conditions.
For example, here we make an invisible buffer for temporary use, and make sure to kill
it before finishing:
(save-excursion
(let ((buffer (get-buffer-create " *temp*")))
(set-buffer buffer)
(unwind-protect
body-form
(kill-buffer buffer))))
You might think that we could just as well write (kill-buffer (current-buffer)) and
dispense with the variable buffer. However, the way shown above is safer, if body-form
happens to get an error after switching to a different buffer! (Alternatively, you could write
another save-excursion around body-form, to ensure that the temporary buffer becomes
current again in time to kill it.)
Emacs includes a standard macro called with-temp-buffer which expands into more or
less the code shown above (see [Current Buffer], page 483). Several of the macros defined
in this manual use unwind-protect in this way.
Here is an actual example derived from an FTP package. It creates a process (see
Chapter 37 [Processes], page 705) to try to establish a connection to a remote machine.
As the function ftp-login is highly susceptible to numerous problems that the writer of
the function cannot anticipate, it is protected with a form that guarantees deletion of the
process in the event of failure. Otherwise, Emacs might fill up with useless subprocesses.
(let ((win nil))
(unwind-protect
(progn
(setq process (ftp-setup-buffer host file))
(if (setq win (ftp-login process host user password))
(message "Logged in")
(error "Ftp login failed")))
(or win (and process (delete-process process)))))
This example has a small bug: if the user types C-g to quit, and the quit happens
immediately after the function ftp-setup-buffer returns but before the variable process
is set, the process will not be killed. There is no easy way to fix this bug, but at least it is
very unlikely.
Chapter 11: Variables 135
11 Variables
A variable is a name used in a program to stand for a value. Nearly all programming
languages have variables of some sort. In the text of a Lisp program, variables are written
using the syntax for symbols.
In Lisp, unlike most programming languages, programs are represented primarily as Lisp
objects and only secondarily as text. The Lisp objects used for variables are symbols: the
symbol name is the variable name, and the variable’s value is stored in the value cell of the
symbol. The use of a symbol as a variable is independent of its use as a function name. See
Section 8.1 [Symbol Components], page 102.
The Lisp objects that constitute a Lisp program determine the textual form of the
program—it is simply the read syntax for those Lisp objects. This is why, for example,
a variable in a textual Lisp program is written using the read syntax for the symbol that
represents the variable.
nil ≡ ’nil
⇒ nil
(setq nil 500)
error Attempt to set constant symbol: nil
keywordp object [Function]
function returns t if object is a symbol whose name starts with ‘:’, interned in the
standard obarray, and returns nil otherwise.
All of the value-forms in bindings are evaluated in the order they appear and before
binding any of the symbols to them. Here is an example of this: z is bound to the
old value of y, which is 2, not the new value of y, which is 1.
(setq y 2)
⇒ 2
(let ((y 1)
(z y))
(list y z))
⇒ (1 2)
Here is a complete list of the other facilities that create local bindings:
• Function calls (see Chapter 12 [Functions], page 160).
• Macro calls (see Chapter 13 [Macros], page 176).
• condition-case (see Section 10.5.3 [Errors], page 127).
Variables can also have buffer-local bindings (see Section 11.10 [Buffer-Local Variables],
page 147) and frame-local bindings (see Section 11.11 [Frame-Local Variables], page 153); a
few variables have terminal-local bindings (see Section 29.2 [Multiple Displays], page 530).
These kinds of bindings work somewhat like ordinary local bindings, but they are localized
depending on “where” you are in Emacs, rather than localized in time.
max-specpdl-size [Variable]
This variable defines the limit on the total number of local variable bindings and
unwind-protect cleanups (see Section 10.5.4 [Cleaning Up from Nonlocal Exits],
page 133) that are allowed before signaling an error (with data "Variable binding
depth exceeds max-specpdl-size").
This limit, with the associated error when it is exceeded, is one way that Lisp avoids
infinite recursion on an ill-defined function. max-lisp-eval-depth provides another
limit on depth of nesting. See [Eval], page 117.
The default value is 1000. Entry to the Lisp debugger increases the value, if there is
little room left, to make sure the debugger itself has room to execute.
Chapter 11: Variables 138
A variable that has been made void with makunbound is indistinguishable from one that
has never received a value and has always been void.
You can use the function boundp to test whether a variable is currently void.
Chapter 11: Variables 139
‘...-forms’
The value is a list of forms (expressions).
‘...-predicate’
The value is a predicate—a function of one argument that returns non-nil for
“good” arguments and nil for “bad” arguments.
‘...-flag’
The value is significant only as to whether it is nil or not.
‘...-program’
The value is a program name.
‘...-command’
The value is a whole shell command.
‘...-switches’
The value specifies options for a command.
When you define a variable, always consider whether you should mark it as “risky”; see
Section 11.13 [File Local Variables], page 155.
When defining and initializing a variable that holds a complicated value (such as a
keymap with bindings in it), it’s best to put the entire computation of the value into the
defvar, like this:
(defvar my-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-a" ’my-command)
...
map)
docstring )
This method has several benefits. First, if the user quits while loading the file, the variable
is either still uninitialized or initialized properly, never in-between. If it is still uninitialized,
reloading the file will initialize it properly. Second, reloading the file once the variable is
initialized will not alter it; that is important if the user has run hooks to alter part of
the contents (such as, to rebind keys). Third, evaluating the defvar form with C-M-x will
reinitialize the map completely.
Putting so much code in the defvar form has one disadvantage: it puts the documen-
tation string far away from the line which names the variable. Here’s a safe way to avoid
that:
(defvar my-mode-map nil
docstring )
(unless my-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-a" ’my-command)
...
(setq my-mode-map map)))
This has all the same advantages as putting the initialization inside the defvar, except that
you must type C-M-x twice, once on each form, if you do want to reinitialize the variable.
But be careful not to write the code like this:
Chapter 11: Variables 143
(symbol-value ’abracadabra)
⇒ 5
A void-variable error is signaled if the current binding of symbol is void.
11.9.1 Scope
Emacs Lisp uses indefinite scope for local variable bindings. This means that any function
anywhere in the program text might access a given binding of a variable. Consider the
following function definitions:
(defun binder (x) ; x is bound in binder.
(foo 5)) ; foo is some other function.
11.9.2 Extent
Extent refers to the time during program execution that a variable name is valid. In Emacs
Lisp, a variable is valid only while the form that bound it is executing. This is called
dynamic extent. “Local” or “automatic” variables in most languages, including C and
Pascal, have dynamic extent.
One alternative to dynamic extent is indefinite extent. This means that a variable
binding can live on past the exit from the form that made the binding. Common Lisp and
Scheme, for example, support this, but Emacs Lisp does not.
To illustrate this, the function below, make-add, returns a function that purports to add
n to its own argument m. This would work in Common Lisp, but it does not do the job in
Emacs Lisp, because after the call to make-add exits, the variable n is no longer bound to
the actual argument 2.
(defun make-add (n)
(function (lambda (m) (+ n m)))) ; Return a function.
⇒ make-add
(fset ’add2 (make-add 2)) ; Define function add2
; with (make-add 2).
⇒ (lambda (m) (+ n m))
(add2 4) ; Try to add 2 to 4.
error Symbol’s value as variable is void: n
Some Lisp dialects have “closures,” objects that are like functions but record additional
variable bindings. Emacs Lisp does not have closures.
variables created there. We can pop those bindings from the stack at exit from the binding
construct.
We can find the value of a variable by searching the stack from top to bottom for a
binding for that variable; the value from that binding is the value of the variable. To set
the variable, we search for the current binding, then store the new value into that binding.
As you can see, a function’s bindings remain in effect as long as it continues execution,
even during its calls to other functions. That is why we say the extent of the binding is
dynamic. And any other function can refer to the bindings, if it uses the same variables
while the bindings are in effect. That is why we say the scope is indefinite.
The actual implementation of variable scoping in GNU Emacs Lisp uses a technique
called shallow binding. Each variable has a standard place in which its current value is
always found—the value cell of the symbol.
In shallow binding, setting the variable works by storing a value in the value cell. Cre-
ating a new binding works by pushing the old value (belonging to a previous binding) onto
a stack, and storing the new local value in the value cell. Eliminating a binding works by
popping the old value off the stack, into the value cell.
We use shallow binding because it has the same results as deep binding, but runs faster,
since there is never a need to search for a binding.
only in one frame. Having different values for a variable in different buffers and/or frames
is an important customization method.
This section describes buffer-local bindings; for frame-local bindings, see the following
section, Section 11.11 [Frame-Local Variables], page 153. (A few variables have bindings
that are local to each terminal; see Section 29.2 [Multiple Displays], page 530.)
more. And if you exit the let while still in the other buffer, you won’t see the unbinding
occur (though it will occur properly). Here is an example to illustrate:
(setq foo ’g)
(set-buffer "a")
(make-local-variable ’foo)
(setq foo ’a)
(let ((foo ’temp))
;; foo ⇒ ’temp ; let binding in buffer ‘a’
(set-buffer "b")
;; foo ⇒ ’g ; the global value since foo is not local in ‘b’
body ...)
foo ⇒ ’g ; exiting restored the local value in buffer ‘a’,
; but we don’t see that in buffer ‘b’
(set-buffer "a") ; verify the local value was restored
foo ⇒ ’a
Note that references to foo in body access the buffer-local binding of buffer ‘b’.
When a file specifies local variable values, these become buffer-local values when you
visit the file. See section “File Variables” in The GNU Emacs Manual.
exit from the let. This is because let does not distinguish between different kinds
of bindings; it knows only which variable the binding was made for.
If the variable is terminal-local, this function signals an error. Such variables cannot
have buffer-local bindings as well. See Section 29.2 [Multiple Displays], page 530.
Warning: do not use make-local-variable for a hook variable. The hook variables
are automatically made buffer-local as needed if you use the local argument to add-
hook or remove-hook.
make-variable-buffer-local variable [Command]
This function marks variable (a symbol) automatically buffer-local, so that any sub-
sequent attempt to set it will make it local to the current buffer at the time.
A peculiar wrinkle of this feature is that binding the variable (with let or other
binding constructs) does not create a buffer-local binding for it. Only setting the
variable (with set or setq), while the variable does not have a let-style binding that
was made in the current buffer, does so.
If variable does not have a default value, then calling this command will give it a
default value of nil. If variable already has a default value, that value remains
unchanged. Subsequently calling makunbound on variable will result in a void buffer-
local value and leave the default value unaffected.
The value returned is variable.
Warning: Don’t assume that you should use make-variable-buffer-local for user-
option variables, simply because users might want to customize them differently in
different buffers. Users can make any variable local, when they wish to. It is better
to leave the choice to them.
The time to use make-variable-buffer-local is when it is crucial that no two
buffers ever share the same binding. For example, when a variable is used for internal
purposes in a Lisp program which depends on having separate values in separate
buffers, then using make-variable-buffer-local can be the best solution.
local-variable-p variable &optional buffer [Function]
This returns t if variable is buffer-local in buffer buffer (which defaults to the current
buffer); otherwise, nil.
local-variable-if-set-p variable &optional buffer [Function]
This returns t if variable will become buffer-local in buffer buffer (which defaults to
the current buffer) if it is set there.
buffer-local-value variable buffer [Function]
This function returns the buffer-local binding of variable (a symbol) in buffer buffer.
If variable does not have a buffer-local binding in buffer buffer, it returns the default
value (see Section 11.10.3 [Default Value], page 152) of variable instead.
buffer-local-variables &optional buffer [Function]
This function returns a list describing the buffer-local variables in buffer buffer. (If
buffer is omitted, the current buffer is used.) It returns an association list (see
Section 5.8 [Association Lists], page 81) in which each element contains one buffer-
local variable and its value. However, when a variable’s buffer-local binding in buffer
is void, then the variable appears directly in the resulting list.
Chapter 11: Variables 151
(make-local-variable ’foobar)
(makunbound ’foobar)
(make-local-variable ’bind-me)
(setq bind-me 69)
(setq lcl (buffer-local-variables))
;; First, built-in variables local in all buffers:
⇒ ((mark-active . nil)
(buffer-undo-list . nil)
(mode-name . "Fundamental")
...
;; Next, non-built-in buffer-local variables.
;; This one is buffer-local and void:
foobar
;; This one is buffer-local and nonvoid:
(bind-me . 69))
Note that storing new values into the cdrs of cons cells in this list does not change
the buffer-local values of the variables.
kill-all-local-variables [Function]
This function eliminates all the buffer-local variable bindings of the current buffer
except for variables marked as “permanent.” As a result, the buffer will see the
default values of most variables.
This function also resets certain other information pertaining to the buffer: it sets
the local keymap to nil, the syntax table to the value of (standard-syntax-table),
the case table to (standard-case-table), and the abbrev table to the value of
fundamental-mode-abbrev-table.
The very first thing this function does is run the normal hook change-major-mode-
hook (see below).
Every major mode command begins by calling this function, which has the effect of
switching to Fundamental mode and erasing most of the effects of the previous major
mode. To ensure that this does its job, the variables that major modes set should
not be marked permanent.
kill-all-local-variables returns nil.
Chapter 11: Variables 152
change-major-mode-hook [Variable]
The function kill-all-local-variables runs this normal hook before it does any-
thing else. This gives major modes a way to arrange for something special to be done
if the user switches to a different major mode. It is also useful for buffer-specific
minor modes that should be forgotten if the user changes the major mode.
For best results, make this variable buffer-local, so that it will disappear after doing its
job and will not interfere with the subsequent major mode. See Section 23.1 [Hooks],
page 382.
A buffer-local variable is permanent if the variable name (a symbol) has a permanent-
local property that is non-nil. Permanent locals are appropriate for data pertaining to
where the file came from or how to save it, rather than with how to edit the contents.
If variable does not have a default value, then calling this command will give it a
default value of nil. If variable already has a default value, that value remains
unchanged.
If the variable is terminal-local, this function signals an error, because such vari-
ables cannot have frame-local bindings as well. See Section 29.2 [Multiple Displays],
page 530. A few variables that are implemented specially in Emacs can be buffer-local,
but can never be frame-local.
This command returns variable.
Buffer-local bindings take precedence over frame-local bindings. Thus, consider a vari-
able foo: if the current buffer has a buffer-local binding for foo, that binding is active;
otherwise, if the selected frame has a frame-local binding for foo, that binding is active;
otherwise, the default binding of foo is active.
Here is an example. First we prepare a few bindings for foo:
(setq f1 (selected-frame))
(make-variable-frame-local ’foo)
(select-frame f2)
(set-buffer (get-buffer-create "b1"))
foo
⇒ (b 1)
Otherwise, the frame gets a chance to provide the binding; when frame f2 is selected, its
frame-local binding is in effect:
(select-frame f2)
(set-buffer (get-buffer "*scratch*"))
foo
⇒ (f 2)
When neither the current buffer nor the selected frame provides a binding, the default
binding is used:
Chapter 11: Variables 155
(select-frame f1)
(set-buffer (get-buffer "*scratch*"))
foo
⇒ nil
When the active binding of a variable is a frame-local binding, setting the variable changes
that binding. You can observe the result with frame-parameters:
(select-frame f2)
(set-buffer (get-buffer "*scratch*"))
(setq foo ’nobody)
(assq ’foo (frame-parameters f2))
⇒ (foo . nobody)
has its effect here. However, this function does not look for the ‘mode:’ local variable
in the ‘-*-’ line. set-auto-mode does that, also taking enable-local-variables
into account (see Section 23.2.3 [Auto Major Mode], page 388).
If the optional argument mode-only is non-nil, then all this function does is return
t if the ‘-*-’ line or the local variables list specifies a mode and nil otherwise. It
does not set the mode nor any other file local variable.
If a file local variable could specify a function that would be called later, or an expression
that would be executed later, simply visiting a file could take over your Emacs. Emacs takes
several measures to prevent this.
You can specify safe values for a variable with a safe-local-variable property.
The property has to be a function of one argument; any value is safe if the function
returns non-nil given that value. Many commonly encountered file variables standardly
have safe-local-variable properties, including fill-column, fill-prefix, and
indent-tabs-mode. For boolean-valued variables that are safe, use booleanp as the
property value. Lambda expressions should be quoted so that describe-variable can
display the predicate.
Some variables are considered risky. A variable whose name ends in any of ‘-command’,
‘-frame-alist’, ‘-function’, ‘-functions’, ‘-hook’, ‘-hooks’, ‘-form’, ‘-forms’,
‘-map’, ‘-map-alist’, ‘-mode-alist’, ‘-program’, or ‘-predicate’ is considered risky.
The variables ‘font-lock-keywords’, ‘font-lock-keywords’ followed by a digit, and
‘font-lock-syntactic-keywords’ are also considered risky. Finally, any variable whose
name has a non-nil risky-local-variable property is considered risky.
ignored-local-variables [Variable]
This variable holds a list of variables that should not be given local values by files.
Any value specified for one of these variables is completely ignored.
Chapter 11: Variables 157
The ‘Eval:’ “variable” is also a potential loophole, so Emacs normally asks for confir-
mation before handling it.
enable-local-eval [User Option]
This variable controls processing of ‘Eval:’ in ‘-*-’ lines or local variables lists in files
being visited. A value of t means process them unconditionally; nil means ignore
them; anything else means ask the user what to do for each file. The default value is
maybe.
safe-local-eval-forms [User Option]
This variable holds a list of expressions that are safe to evaluate when found in the
‘Eval:’ “variable” in a file local variables list.
If the expression is a function call and the function has a safe-local-eval-function
property, the property value determines whether the expression is safe to evaluate. The
property value can be a predicate to call to test the expression, a list of such predicates (it’s
safe if any predicate succeeds), or t (always safe provided the arguments are constant).
Text properties are also potential loopholes, since their values could include functions to
call. So Emacs discards all text properties from string values specified for file local variables.
You can make two variables synonyms and declare one obsolete at the same time using
the macro define-obsolete-variable-alias.
define-obsolete-variable-alias obsolete-name current-name [Macro]
&optional when docstring
This macro marks the variable obsolete-name as obsolete and also makes it an alias
for the variable current-name. It is equivalent to the following:
(defvaralias obsolete-name current-name docstring )
(make-obsolete-variable obsolete-name current-name when )
indirect-variable variable [Function]
This function returns the variable at the end of the chain of aliases of variable. If
variable is not a symbol, or if variable is not defined as an alias, the function returns
variable.
This function signals a cyclic-variable-indirection error if there is a loop in the
chain of symbols.
(defvaralias ’foo ’bar)
(indirect-variable ’foo)
⇒ bar
(indirect-variable ’bar)
⇒ bar
(setq bar 2)
bar
⇒ 2
foo
⇒ 2
(setq foo 0)
bar
⇒ 0
foo
⇒ 0
Variables of type DEFVAR_INT can only take on integer values. Attempting to assign
them any other value will result in an error:
(setq window-min-height 5.0)
error Wrong type argument: integerp, 5.0
Chapter 12: Functions 160
12 Functions
A Lisp program is composed mainly of Lisp functions. This chapter explains what functions
are, how they accept arguments, and how to define them.
mand; such symbols can be invoked with M-x. The symbol is a function as well
if the definition is a function. See Section 21.3 [Interactive Call], page 310.
keystroke command
A keystroke command is a command that is bound to a key sequence (typically
one to three keystrokes). The distinction is made here merely to avoid confusion
with the meaning of “command” in non-Emacs editors; for Lisp programs, the
distinction is normally unimportant.
byte-code function
A byte-code function is a function that has been compiled by the byte compiler.
See Section 2.3.16 [Byte-Code Type], page 22.
functionp object [Function]
This function returns t if object is any kind of function, or a special form, or, recur-
sively, a symbol whose function definition is a function or special form. (This does
not include macros.)
Unlike functionp, the next three functions do not treat a symbol as its function defini-
tion.
subrp object [Function]
This function returns t if object is a built-in function (i.e., a Lisp primitive).
(subrp ’message) ; message is a symbol,
⇒ nil ; not a subr object.
(subrp (symbol-function ’message))
⇒ t
byte-code-function-p object [Function]
This function returns t if object is a byte-code function. For example:
(byte-code-function-p (symbol-function ’next-line))
⇒ t
subr-arity subr [Function]
This function provides information about the argument list of a primitive, subr. The
returned value is a pair (min . max ). min is the minimum number of args. max is
the maximum number or the symbol many, for a function with &rest arguments, or
the symbol unevalled if subr is a special form.
defun stores this lambda expression in the function cell of name. It returns the value
name, but usually we ignore this value.
As described previously, argument-list is a list of argument names and may include the
keywords &optional and &rest (see Section 12.2 [Lambda Expressions], page 161).
Also, the first two of the body-forms may be a documentation string and an interactive
declaration.
There is no conflict if the same symbol name is also used as a variable, since the
symbol’s value cell is independent of the function cell. See Section 8.1 [Symbol Com-
ponents], page 102.
Here are some examples:
(defun foo () 5)
⇒ foo
(foo)
⇒ 5
(defun capitalize-backwards ()
"Upcase the last letter of a word."
(interactive)
(backward-word 1)
(forward-word 1)
(backward-char 1)
(capitalize-word 1))
⇒ capitalize-backwards
Be careful not to redefine existing functions unintentionally. defun redefines even
primitive functions such as car without any hesitation or notification. Redefining a
function already defined is often done deliberately, and there is no way to distinguish
deliberate redefinition from unintentional redefinition.
is because defalias records which file defined the function, just like defun (see
Section 15.9 [Unloading], page 211).
By contrast, in programs that manipulate function definitions for other purposes, it
is better to use fset, which does not keep such records. See Section 12.8 [Function
Cells], page 171.
You cannot create a new primitive function with defun or defalias, but you can use
them to change the function definition of any symbol, even one such as car or x-popup-
menu whose normal definition is a primitive. However, this is risky: for instance, it is next
to impossible to redefine car without breaking Lisp completely. Redefining an obscure
function such as x-popup-menu is less dangerous, but it still may not work as you expect. If
there are calls to the primitive from C code, they call the primitive’s C definition directly,
so changing the symbol’s definition will have no effect on them.
See also defsubst, which defines a function like defun and tells the Lisp compiler to
open-code it. See Section 12.10 [Inline Functions], page 173.
See [describe-symbols example], page 427, for a realistic example using function and
an anonymous function.
If you have never given a symbol any function definition, we say that that symbol’s
function cell is void. In other words, the function cell does not have any Lisp object in it.
If you try to call such a symbol as a function, it signals a void-function error.
Note that void is not the same as nil or the symbol void. The symbols nil and void
are Lisp objects, and can be stored into a function cell just as any other object can be (and
they can be valid functions if you define them in turn with defun). A void function cell
contains no object whatsoever.
Chapter 12: Functions 172
You can test the voidness of a symbol’s function definition with fboundp. After you have
given a symbol a function definition, you can make it void once more using fmakunbound.
(symbol-function ’xfirst)
⇒ car
(symbol-function (symbol-function ’xfirst))
⇒ #<subr car>
Making a function inline makes explicit calls run faster. But it also has disadvantages.
For one thing, it reduces flexibility; if you change the definition of the function, calls already
inlined still use the old definition until you recompile them.
Another disadvantage is that making a large function inline can increase the size of
compiled code both in files and in memory. Since the speed advantage of inline functions
is greatest for small functions, you generally should not make large functions inline.
Also, inline functions do not behave well with respect to debugging, tracing, and advising
(see Chapter 17 [Advising Functions], page 226). Since ease of debugging and the flexibility
of redefining functions are important features of Emacs, you should not make a function
inline, even if it’s small, unless its speed is really crucial, and you’ve timed the code to
verify that using defun actually has performance problems.
It’s possible to define a macro to expand into the same code that an inline function
would execute. (See Chapter 13 [Macros], page 176.) But the macro would be limited to
direct use in expressions—a macro cannot be called with apply, mapcar and so on. Also,
it takes some work to convert an ordinary function into a macro. To convert it into an
inline function is very easy; simply replace defun with defsubst. Since each argument of
an inline function is evaluated exactly once, you needn’t worry about how many times the
body uses the arguments, as you do for macros. (See Section 13.6.2 [Argument Evaluation],
page 180.)
Inline functions can be used and open-coded later on in the same file, following the
definition, just like macros.
Being quick and simple, unsafep does a very light analysis and rejects many Lisp ex-
pressions that are actually safe. There are no known cases where unsafep returns nil for
an unsafe expression. However, a “safe” Lisp expression can return a string with a display
property, containing an associated Lisp expression to be executed after the string is inserted
into a buffer. This associated expression can be a virus. In order to be safe, you must delete
properties from all strings calculated by user code before inserting them into buffers.
13 Macros
Macros enable you to define new control constructs and other language features. A macro
is defined much like a function, but instead of telling how to compute a value, it tells how
to compute another Lisp expression which will in turn compute the value. We call this
expression the expansion of the macro.
Macros can do this because they operate on the unevaluated expressions for the ar-
guments, not on the argument values as functions do. They can therefore construct an
expansion containing these argument expressions or parts of them.
If you are using a macro to do something an ordinary function could do, just for the sake
of speed, consider using an inline function instead. See Section 12.10 [Inline Functions],
page 173.
In order for compilation of macro calls to work, the macros must already be defined in
Lisp when the calls to them are compiled. The compiler has a special feature to help you
do this: if a file being compiled contains a defmacro form, the macro is defined temporarily
for the rest of the compilation of that file. To make this feature work, you must put the
defmacro in the same file where it is used, and before its first use.
Byte-compiling a file executes any require calls at top-level in the file. This is in case the
file needs the required packages for proper compilation. One way to ensure that necessary
macro definitions are available during compilation is to require the files that define them
(see Section 15.7 [Named Features], page 209). To avoid loading the macro definition files
when someone runs the compiled program, write eval-when-compile around the require
calls (see Section 16.5 [Eval During Compile], page 219).
The body of the macro definition can include a declare form, which can specify how
TAB should indent macro calls, and how to step through them for Edebug.
A declare form only has its special effect in the body of a defmacro form if it imme-
diately follows the documentation string, if present, or the argument list otherwise.
(Strictly speaking, several declare forms can follow the documentation string or ar-
gument list, but since a declare form can have several specs, they can always be
combined into a single form.) When used at other places in a defmacro form, or
outside a defmacro form, declare just returns nil without evaluating any specs.
No macro absolutely needs a declare form, because that form has no effect on how
the macro expands, on what the macro means in the program. It only affects secondary
features: indentation and Edebug.
13.5 Backquote
Macros often need to construct large list structures from a mixture of constants and non-
constant parts. To make this easier, use the ‘‘’ syntax (usually called backquote).
Backquote allows you to quote a list, but selectively evaluate elements of that list. In the
simplest case, it is identical to the special form quote (see Section 9.2 [Quoting], page 115).
For example, these two forms yield identical results:
‘(a list of (+ 2 3) elements)
⇒ (a list of (+ 2 3) elements)
’(a list of (+ 2 3) elements)
⇒ (a list of (+ 2 3) elements)
The special marker ‘,’ inside of the argument to backquote indicates a value that isn’t
constant. Backquote evaluates the argument of ‘,’ and puts the value in the list structure:
(list ’a ’list ’of (+ 2 3) ’elements)
⇒ (a list of 5 elements)
‘(a list of ,(+ 2 3) elements)
⇒ (a list of 5 elements)
Substitution with ‘,’ is allowed at deeper levels of the list structure also. For example:
(defmacro t-becomes-nil (variable)
‘(if (eq ,variable t)
(setq ,variable nil)))
(t-becomes-nil foo)
≡ (if (eq foo t) (setq foo nil))
You can also splice an evaluated value into the resulting list, using the special marker
‘,@’. The elements of the spliced list become elements at the same level as the other elements
of the resulting list. The equivalent code without using ‘‘’ is often unreadable. Here are
some examples:
(setq some-list ’(2 3))
⇒ (2 3)
(cons 1 (append some-list ’(4) some-list))
⇒ (1 2 3 4 2 3)
‘(1 ,@some-list 4 ,@some-list)
⇒ (1 2 3 4 2 3)
Chapter 13: Macros 180
(for i from 1 to 3 do
(setq square (* i i))
(princ (format "\n%d %d" i square)))
7→
(let ((i 1))
(while (<= i 3)
(setq square (* i i))
(princ (format "\n%d %d" i square))
(inc i)))
a1 1
a2 4
a3 9
⇒ nil
The arguments from, to, and do in this macro are “syntactic sugar”; they are entirely
ignored. The idea is that you will write noise words (such as from, to, and do) in those
positions in the macro call.
Here’s an equivalent definition simplified through use of backquote:
(defmacro for (var from init to final do &rest body)
"Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
‘(let ((,var ,init))
(while (<= ,var ,final)
,@body
(inc ,var))))
Both forms of this definition (with backquote and without) suffer from the defect that
final is evaluated on every iteration. If final is a constant, this is not a problem. If it is a
more complex form, say (long-complex-calculation x), this can slow down the execution
significantly. If final has side effects, executing it more than once is probably incorrect.
A well-designed macro definition takes steps to avoid this problem by producing an
expansion that evaluates the argument expressions exactly once unless repeated evaluation
is part of the intended purpose of the macro. Here is a correct expansion for the for macro:
(let ((i 1)
(max 3))
(while (<= i max)
(setq square (* i i))
(princ (format "%d %d" i square))
(inc i)))
Here is a macro definition that creates this expansion:
(defmacro for (var from init to final do &rest body)
"Execute a simple for loop: (for i from 1 to 10 do (print i))."
‘(let ((,var ,init)
(max ,final))
(while (<= ,var max)
,@body
(inc ,var))))
Chapter 13: Macros 182
Unfortunately, this fix introduces another problem, described in the following section.
The references to max inside the body of the for, which are supposed to refer to the user’s
binding of max, really access the binding made by for.
The way to correct this is to use an uninterned symbol instead of max (see Section 8.3
[Creating Symbols], page 104). The uninterned symbol can be bound and referred to just
like any other symbol, but since it is created by for, we know that it cannot already appear
in the user’s program. Since it is not interned, there is no way the user can put it into the
program later. It will never appear anywhere except where put by for. Here is a definition
of for that works this way:
(defmacro for (var from init to final do &rest body)
"Execute a simple for loop: (for i from 1 to 10 do (print i))."
(let ((tempvar (make-symbol "max")))
‘(let ((,var ,init)
(,tempvar ,final))
(while (<= ,var ,tempvar)
,@body
(inc ,var)))))
This creates an uninterned symbol named max and puts it in the expansion instead of the
usual interned symbol max that appears in expressions ordinarily.
(emacs-commentary-link library )
Link to the commentary section of a library; library is a string
which specifies the library name.
(emacs-library-link library )
Link to an Emacs Lisp library file; library is a string which specifies
the library name.
(file-link file )
Link to a file; file is a string which specifies the name of the file to
visit with find-file when the user invokes this link.
(function-link function )
Link to the documentation of a function; function is a string
which specifies the name of the function to describe with
describe-function when the user invokes this link.
(variable-link variable )
Link to the documentation of a variable; variable is a string
which specifies the name of the variable to describe with
describe-variable when the user invokes this link.
(custom-group-link group )
Link to another customization group. Invoking it creates a new
customization buffer for group.
You can specify the text to use in the customization buffer by adding :tag
name after the first element of the link-data; for example, (info-link :tag
"foo" "(emacs)Top") makes a link to the Emacs manual which appears in the
buffer as ‘foo’.
An item can have more than one external link; however, most items have none
at all.
:load file
Load file file (a string) before displaying this customization item. Loading is
done with load-library, and only if the file is not already loaded.
:require feature
Execute (require ’feature ) when your saved customizations set the value of
this item. feature should be a symbol.
The most common reason to use :require is when a variable enables a feature
such as a minor mode, and just setting the variable won’t have any effect unless
the code which implements the mode is loaded.
:version version
This keyword specifies that the item was first introduced in Emacs version
version, or that its default value was changed in that version. The value version
must be a string.
:package-version ’(package . version )
This keyword specifies that the item was first introduced in package version
version, or that its meaning or default value was changed in that version. The
value of package is a symbol and version is a string.
Chapter 14: Writing Customization Definitions 187
customize-package-emacs-version-alist [Variable]
This alist provides a mapping for the versions of Emacs that are associated with
versions of a package listed in the :package-version keyword. Its elements look like
this:
(package (pversion . eversion )...)
For each package, which is a symbol, there are one or more elements that contain a
package version pversion with an associated Emacs version eversion. These versions
are strings. For example, the MH-E package updates this alist with the following:
(add-to-list ’customize-package-emacs-version-alist
’(MH-E ("6.0" . "22.1") ("6.1" . "22.1") ("7.0" . "22.1")
("7.1" . "22.1") ("7.2" . "22.1") ("7.3" . "22.1")
("7.4" . "22.1") ("8.0" . "22.1")))
The value of package needs to be unique and it needs to match the package value
appearing in the :package-version keyword. Since the user might see the value in
a error message, a good choice is the official name of the package, such as MH-E or
Gnus.
that symbol. Useful widgets are custom-variable for a variable, custom-face for a
face, and custom-group for a group.
When you introduce a new group into Emacs, use the :version keyword in the
defgroup; then you need not use it for the individual members of the group.
In addition to the common keywords (see Section 14.1 [Common Keywords],
page 185), you can also use this keyword in defgroup:
:prefix prefix
If the name of an item in the group starts with prefix, then the tag for
that item is constructed (by default) by omitting prefix.
One group can have any number of prefixes.
The prefix-discarding feature is currently turned off, which means that :prefix currently
has no effect. We did this because we found that discarding the specified prefixes often led
to confusing names for options. This happened because the people who wrote the defgroup
definitions for various groups added :prefix keywords whenever they make logical sense—
that is, whenever the variables in the library have a common prefix.
In order to obtain good results with :prefix, it would be necessary to check the specific
effects of discarding a particular prefix, given the specific items in a group and their names
and documentation. If the resulting text is not clear, then :prefix should not be used in
that case.
It should be possible to recheck all the customization groups, delete the :prefix spec-
ifications which give unclear results, and then turn this feature back on, if someone would
like to do the work.
If you specify the :set keyword, to make the variable take other special actions when
set through the customization buffer, the variable’s documentation string should tell
the user specifically how to do the same job in hand-written Lisp code.
When you evaluate a defcustom form with C-M-x in Emacs Lisp mode (eval-defun),
a special feature of eval-defun arranges to set the variable unconditionally, without
testing whether its value is void. (The same feature applies to defvar.) See Sec-
tion 11.5 [Defining Variables], page 139.
:type type
Use type as the data type for this option. It specifies which values are legitimate,
and how to display the value. See Section 14.4 [Customization Types], page 191,
for more information.
:options value-list
Specify the list of reasonable values for use in this option. The user is not
restricted to using only these values, but they are offered as convenient alter-
natives.
This is meaningful only for certain types, currently including hook, plist and
alist. See the definition of the individual types for a description of how to use
:options.
:set setfunction
Specify setfunction as the way to change the value of this option. The function
setfunction should take two arguments, a symbol (the option name) and the
new value, and should do whatever is necessary to update the value properly for
this option (which may not mean simply setting the option as a Lisp variable).
The default for setfunction is set-default.
:get getfunction
Specify getfunction as the way to extract the value of this option. The function
getfunction should take one argument, a symbol, and should return whatever
customize should use as the “current value” for that symbol (which need not
be the symbol’s Lisp value). The default is default-value.
You have to really understand the workings of Custom to use :get correctly. It
is meant for values that are treated in Custom as variables but are not actually
stored in Lisp variables. It is almost surely a mistake to specify getfunction
for a value that really is stored in a Lisp variable.
:initialize function
function should be a function used to initialize the variable when the defcustom
is evaluated. It should take two arguments, the option name (a symbol) and
the value. Here are some predefined functions meant for use in this way:
custom-initialize-set
Use the variable’s :set function to initialize the variable, but do
not reinitialize it if it is already non-void.
Chapter 14: Writing Customization Definitions 190
custom-initialize-default
Like custom-initialize-set, but use the function set-default
to set the variable, instead of the variable’s :set function. This
is the usual choice for a variable whose :set function enables or
disables a minor mode; with this choice, defining the variable will
not call the minor mode function, but customizing the variable will
do so.
custom-initialize-reset
Always use the :set function to initialize the variable. If the vari-
able is already non-void, reset it by calling the :set function using
the current value (returned by the :get method). This is the de-
fault :initialize function.
custom-initialize-changed
Use the :set function to initialize the variable, if it is already set
or has been customized; otherwise, just use set-default.
custom-initialize-safe-set
custom-initialize-safe-default
These functions behave like custom-initialize-set (custom-
initialize-default, respectively), but catch errors. If an error
occurs during initialization, they set the variable to nil using
set-default, and throw no error.
These two functions are only meant for options defined in pre-
loaded files, where some variables or functions used to compute
the option’s value may not yet be defined. The option normally
gets updated in ‘startup.el’, ignoring the previously computed
value. Because of this typical usage, the value which these two
functions compute normally only matters when, after startup, one
unsets the option’s value and then reevaluates the defcustom. By
that time, the necessary variables and functions will be defined, so
there will not be an error.
:set-after variables
When setting variables according to saved customizations, make sure to set the
variables variables before this one; in other words, delay setting this variable
until after those others have been handled. Use :set-after if setting this
variable won’t work properly unless those other variables already have their
intended values.
The :require keyword is useful for an option that turns on the operation of a certain
feature. Assuming that the package is coded to check the value of the option, you still need
to arrange for the package to be loaded. You can do that with :require. See Section 14.1
[Common Keywords], page 185. Here is an example, from the library ‘saveplace.el’:
(defcustom save-place nil
"Non-nil means automatically save place in each file..."
:type ’boolean
:require ’saveplace
Chapter 14: Writing Customization Definitions 191
:group ’save-place)
If a customization item has a type such as hook or alist, which supports :options,
you can add additional values to the list from outside the defcustom declaration by call-
ing custom-add-frequent-value. For example, if you define a function my-lisp-mode-
initialization intended to be called from emacs-lisp-mode-hook, you might want to
add that to the list of reasonable values for emacs-lisp-mode-hook, but not by editing its
definition. You can do it thus:
(custom-add-frequent-value ’emacs-lisp-mode-hook
’my-lisp-mode-initialization)
custom-add-frequent-value symbol value [Function]
For the customization option symbol, add value to the list of reasonable values.
The precise effect of adding a value depends on the customization type of symbol.
Internally, defcustom uses the symbol property standard-value to record the expres-
sion for the standard value, and saved-value to record the value saved by the user with the
customization buffer. Both properties are actually lists whose car is an expression which
evaluates to the value.
integer The value must be an integer, and is represented textually in the customization
buffer.
number The value must be a number (floating point or integer), and is represented
textually in the customization buffer.
float The value must be a floating point number, and is represented textually in the
customization buffer.
string The value must be a string, and the customization buffer shows just the con-
tents, with no delimiting ‘"’ characters and no quoting with ‘\’.
regexp Like string except that the string must be a valid regular expression.
character
The value must be a character code. A character code is actually an integer,
but this type shows the value by inserting the character in the buffer, rather
than by showing the number.
file The value must be a file name, and you can do completion with M-TAB.
(file :must-match t)
The value must be a file name for an existing file, and you can do completion
with M-TAB.
directory
The value must be a directory name, and you can do completion with M-TAB.
hook The value must be a list of functions (or a single function, but that is obso-
lete usage). This customization type is used for hook variables. You can use
the :options keyword in a hook variable’s defcustom to specify a list of func-
tions recommended for use in the hook; see Section 14.3 [Variable Definitions],
page 188.
alist The value must be a list of cons-cells, the car of each cell representing a key,
and the cdr of the same cell representing an associated value. The user can
add and delete key/value pairs, and edit both the key and the value of each
pair.
You can specify the key and value types like this:
(alist :key-type key-type :value-type value-type )
where key-type and value-type are customization type specifications. The de-
fault key type is sexp, and the default value type is sexp.
The user can add any key matching the specified key type, but you can give
some keys a preferential treatment by specifying them with the :options (see
Section 14.3 [Variable Definitions], page 188). The specified keys will always be
shown in the customize buffer (together with a suitable value), with a checkbox
to include or exclude or disable the key/value pair from the alist. The user will
not be able to edit the keys specified by the :options keyword argument.
The argument to the :options keywords should be a list of specifications for
reasonable keys in the alist. Ordinarily, they are simply atoms, which stand for
themselves as. For example:
Chapter 14: Writing Customization Definitions 193
plist The plist custom type is similar to the alist (see above), except that the
information is stored as a property list, i.e. a list of this form:
Chapter 14: Writing Customization Definitions 194
(const value )
The value must be value—nothing else is allowed.
The main use of const is inside of choice. For example, (choice integer
(const nil)) allows either an integer or nil.
:tag is often used with const, inside of choice. For example,
(choice (const :tag "Yes" t)
(const :tag "No" nil)
(const :tag "Ask" foo))
describes a variable for which t means yes, nil means no, and foo means “ask.”
Chapter 14: Writing Customization Definitions 196
(other value )
This alternative can match any Lisp value, but if the user chooses this alterna-
tive, that selects the value value.
The main use of other is as the last element of choice. For example,
(choice (const :tag "Yes" t)
(const :tag "No" nil)
(other :tag "Ask" foo))
describes a variable for which t means yes, nil means no, and anything else
means “ask.” If the user chooses ‘Ask’ from the menu of alternatives, that
specifies the value foo; but any other value (not t, nil or foo) displays as
‘Ask’, just like foo.
(function-item function )
Like const, but used for values which are functions. This displays the docu-
mentation string as well as the function name. The documentation string is
either the one you specify with :doc, or function’s own documentation string.
(variable-item variable )
Like const, but used for values which are variable names. This displays the
documentation string as well as the variable name. The documentation string
is either the one you specify with :doc, or variable’s own documentation string.
(set types ...)
The value must be a list, and each element of the list must match one of the
types specified.
This appears in the customization buffer as a checklist, so that each of types
may have either one corresponding element or none. It is not possible to specify
two different elements that match the same one of types. For example, (set
integer symbol) allows one integer and/or one symbol in the list; it does
not allow multiple integers or multiple symbols. As a result, it is rare to use
nonspecific types such as integer in a set.
Most often, the types in a set are const types, as shown here:
(set (const :bold) (const :italic))
Sometimes they describe possible elements in an alist:
(set (cons :tag "Height" (const height) integer)
(cons :tag "Width" (const width) integer))
That lets the user specify a height value optionally and a width value optionally.
(repeat element-type )
The value must be a list and each element of the list must fit the type element-
type. This appears in the customization buffer as a list of elements, with ‘[INS]’
and ‘[DEL]’ buttons for adding more elements or removing elements.
(restricted-sexp :match-alternatives criteria )
This is the most general composite type construct. The value may be any Lisp
object that satisfies one of criteria. criteria should be a list, and each element
should be one of these possibilities:
Chapter 14: Writing Customization Definitions 197
(list file
(choice (const t)
(list :inline t string string)))
If the user chooses the first alternative in the choice, then the overall list has two elements
and the second element is t. If the user chooses the second alternative, then the overall list
has three elements and the second and third must be strings.
:button-face face
Use the face face (a face name or a list of face names) for button text displayed
with ‘%[...%]’.
:button-prefix prefix
:button-suffix suffix
These specify the text to display before and after a button. Each can be:
nil No text is inserted.
a string The string is inserted literally.
a symbol The symbol’s value is used.
:tag tag Use tag (a string) as the tag for the value (or part of the value) that corresponds
to this type.
:doc doc Use doc as the documentation string for this value (or part of the value) that
corresponds to this type. In order for this to work, you must specify a value
for :format, and use ‘%d’ or ‘%h’ in that value.
The usual reason to specify a documentation string for a type is to provide
more information about the meanings of alternatives inside a :choice type or
the parts of some other composite type.
:help-echo motion-doc
When you move to this item with widget-forward or widget-backward, it
will display the string motion-doc in the echo area. In addition, motion-doc is
used as the mouse help-echo string and may actually be a function or form
evaluated to yield a help string. If it is a function, it is called with one argument,
the widget.
:match function
Specify how to decide whether a value matches the type. The corresponding
value, function, should be a function that accepts two arguments, a widget and
a value; it should return non-nil if the value is acceptable.
:tag "Node"
:type ’(choice (string :tag "Leaf" :value "")
(cons :tag "Interior"
:value ("" . "")
binary-tree-of-string
binary-tree-of-string)))
15 Loading
Loading a file of Lisp code means bringing its contents into the Lisp environment in the
form of Lisp objects. Emacs finds and opens the file, reads the text, evaluates each form,
and then closes the file.
The load functions evaluate all the expressions in a file just as the eval-buffer function
evaluates all the expressions in a buffer. The difference is that the load functions read and
evaluate the text in the file as found on disk, not the text in an Emacs buffer.
The loaded file must contain Lisp expressions, either as source code or as byte-compiled
code. Each form in the file is called a top-level form. There is no special format for the
forms in a loadable file; any form in a file may equally well be typed directly into a buffer
and evaluated there. (Indeed, most code is tested this way.) Most often, the forms are
function definitions and variable definitions.
A file containing Lisp code is often called a library. Thus, the “Rmail library” is a file
containing code for Rmail mode. Similarly, a “Lisp library directory” is a directory of files
containing Lisp code.
If the optional argument must-suffix is non-nil, then load insists that the file name
used must end in either ‘.el’ or ‘.elc’ (possibly extended with a compression suffix),
unless it contains an explicit directory name.
If filename is a relative file name, such as ‘foo’ or ‘baz/foo.bar’, load searches for
the file using the variable load-path. It appends filename to each of the directories
listed in load-path, and loads the first file it finds whose name matches. The current
default directory is tried only if it is specified in load-path, where nil stands for
the default directory. load tries all three possible suffixes in the first directory in
load-path, then all three suffixes in the second directory, and so on. See Section 15.3
[Library Search], page 203.
If you get a warning that ‘foo.elc’ is older than ‘foo.el’, it means you should
consider recompiling ‘foo.el’. See Chapter 16 [Byte Compilation], page 214.
When loading a source file (not compiled), load performs character set translation
just as Emacs would do when visiting the file. See Section 33.10 [Coding Systems],
page 648.
Messages like ‘Loading foo...’ and ‘Loading foo...done’ appear in the echo area
during loading unless nomessage is non-nil.
Any unhandled errors while loading a file terminate loading. If the load was done for
the sake of autoload, any function definitions made during the loading are undone.
If load can’t find the file to load, then normally it signals the error file-error (with
‘Cannot open load file filename ’). But if missing-ok is non-nil, then load just
returns nil.
You can use the variable load-read-function to specify a function for load to use
instead of read for reading expressions. See below.
load returns t if the file loads successfully.
load-in-progress [Variable]
This variable is non-nil if Emacs is in the process of loading a file, and it is nil
otherwise.
load-read-function [Variable]
This variable specifies an alternate expression-reading function for load and eval-
region to use instead of read. The function should accept one argument, just as
read does.
Normally, the variable’s value is nil, which means those functions should use read.
Chapter 15: Loading 203
Instead of using this variable, it is cleaner to use another, newer feature: to pass the
function as the read-function argument to eval-region. See [Eval], page 117.
For information about how load is used in building Emacs, see Section E.1 [Building
Emacs], page 870.
load-suffixes [Variable]
This is a list of suffixes indicating (compiled or source) Emacs Lisp files. It should
not include the empty string. load uses these suffixes in order when it appends
Lisp suffixes to the specified file name. The standard value is (".elc" ".el") which
produces the behavior described in the previous section.
load-file-rep-suffixes [Variable]
This is a list of suffixes that indicate representations of the same file. This list should
normally start with the empty string. When load searches for a file it appends the
suffixes in this list, in order, to the file name, before searching for another file.
Enabling Auto Compression mode appends the suffixes in jka-compr-load-suffixes
to this list and disabling Auto Compression mode removes them again. The standard
value of load-file-rep-suffixes if Auto Compression mode is disabled is ("").
Given that the standard value of jka-compr-load-suffixes is (".gz"), the stan-
dard value of load-file-rep-suffixes if Auto Compression mode is enabled is (""
".gz").
get-load-suffixes [Function]
This function returns the list of all suffixes that load should try, in order, when
its must-suffix argument is non-nil. This takes both load-suffixes and load-
file-rep-suffixes into account. If load-suffixes, jka-compr-load-suffixes
and load-file-rep-suffixes all have their standard values, this function returns
(".elc" ".elc.gz" ".el" ".el.gz") if Auto Compression mode is enabled and
(".elc" ".el") if Auto Compression mode is disabled.
To summarize, load normally first tries the suffixes in the value of (get-load-suffixes)
and then those in load-file-rep-suffixes. If nosuffix is non-nil, it skips the former
group, and if must-suffix is non-nil, it skips the latter group.
Not all subdirectories are included, though. Subdirectories whose names do not start
with a letter or digit are excluded. Subdirectories named ‘RCS’ or ‘CVS’ are excluded.
Also, a subdirectory which contains a file named ‘.nosearch’ is excluded. You can use
these methods to prevent certain subdirectories of the ‘site-lisp’ directories from being
searched.
If you run Emacs from the directory where it was built—that is, an executable that has
not been formally installed—then load-path normally contains two additional directories.
These are the lisp and site-lisp subdirectories of the main build directory. (Both are
represented as absolute file names.)
15.5 Autoload
The autoload facility allows you to make a function or macro known in Lisp, but put off
loading the file that defines it. The first call to the function automatically reads the proper
file to install the real definition and other associated code, then runs the real definition as
if it had been loaded all along.
There are two ways to set up an autoloaded function: by calling autoload, and by
writing a special “magic” comment in the source before the real definition. autoload is
the low-level primitive for autoloading; any Lisp program can call autoload at any time.
Magic comments are the most convenient way to make a function autoload, for packages
installed along with Emacs. These comments do nothing on their own, but they serve as a
guide for the command update-file-autoloads, which constructs calls to autoload and
arranges to execute them when Emacs is built.
(symbol-function ’run-prolog)
⇒ (autoload "prolog" 169681 t nil)
In this case, "prolog" is the name of the file to load, 169681 refers to the documen-
tation string in the ‘emacs/etc/DOC-version ’ file (see Section 24.1 [Documentation
Basics], page 425), t means the function is interactive, and nil that it is not a macro
or a keymap.
The autoloaded file usually contains other definitions and may require or provide one
or more features. If the file is not completely loaded (due to an error in the evaluation of
its contents), any function definitions or provide calls that occurred during the load are
undone. This is to ensure that the next attempt to call any function autoloading from this
file will try again to load the file. If not for this, then some of the functions in the file might
be defined by the aborted load, but fail to work properly for the lack of certain subroutines
not loaded successfully because they come later in the file.
If the autoloaded file fails to define the desired Lisp function or macro, then an error is
signaled with data "Autoloading failed to define function function-name ".
A magic autoload comment (often called an autoload cookie) consists of
‘;;;###autoload’, on a line by itself, just before the real definition of the function
in its autoloadable source file. The command M-x update-file-autoloads writes a
corresponding autoload call into ‘loaddefs.el’. Building Emacs loads ‘loaddefs.el’
and thus calls autoload. M-x update-directory-autoloads is even more powerful; it
updates autoloads for all files in the current directory.
The same magic comment can copy any kind of form into ‘loaddefs.el’. If the form
following the magic comment is not a function-defining form or a defcustom form, it is
copied verbatim. “Function-defining forms” include define-skeleton, define-derived-
mode, define-generic-mode and define-minor-mode as well as defun and defmacro.
To save space, a defcustom form is converted to a defvar in ‘loaddefs.el’, with some
additional information if it uses :require.
You can also use a magic comment to execute a form at build time without executing
it when the file itself is loaded. To do this, write the form on the same line as the magic
comment. Since it is in a comment, it does nothing when you load the source file; but M-x
update-file-autoloads copies it to ‘loaddefs.el’, where it is executed while building
Emacs.
The following example shows how doctor is prepared for autoloading with a magic
comment:
;;;###autoload
(defun doctor ()
"Switch to *doctor* buffer and start giving psychotherapy."
(interactive)
(switch-to-buffer "*doctor*")
(doctor-mode))
Here’s what that produces in ‘loaddefs.el’:
(autoload (quote doctor) "doctor" "\
Switch to *doctor* buffer and start giving psychotherapy.
\(fn)" t nil)
Chapter 15: Loading 208
The backslash and newline immediately following the double-quote are a convention used
only in the preloaded uncompiled Lisp files such as ‘loaddefs.el’; they tell make-docfile
to put the documentation string in the ‘etc/DOC’ file. See Section E.1 [Building Emacs],
page 870. See also the commentary in ‘lib-src/make-docfile.c’. ‘(fn)’ in the usage
part of the documentation string is replaced with the function’s name when the various
help functions (see Section 24.5 [Help Functions], page 431) display it.
If you write a function definition with an unusual macro that is not one of the known
and recognized function definition methods, use of an ordinary magic autoload comment
would copy the whole definition into loaddefs.el. That is not desirable. You can put the
desired autoload call into loaddefs.el instead by writing this:
;;;###autoload (autoload ’foo "myfile")
(mydefunmacro foo
...)
(unless foo-was-loaded
execute-first-time-only
(setq foo-was-loaded t))
If the library uses provide to provide a named feature, you can use featurep earlier in the
file to test whether the provide call has been executed before.
Chapter 15: Loading 209
15.7 Features
provide and require are an alternative to autoload for loading files automatically. They
work in terms of named features. Autoloading is triggered by calling a specific function,
but a feature is loaded the first time another program asks for it by name.
A feature name is a symbol that stands for a collection of functions, variables, etc. The
file that defines them should provide the feature. Another program that uses them may
ensure they are defined by requiring the feature. This loads the file of definitions if it hasn’t
been loaded already.
To require the presence of a feature, call require with the feature name as argument.
require looks in the global variable features to see whether the desired feature has been
provided already. If not, it loads the feature from the appropriate file. This file should call
provide at the top level to add the feature to features; if it fails to do so, require signals
an error.
For example, in ‘emacs/lisp/prolog.el’, the definition for run-prolog includes the
following code:
(defun run-prolog ()
"Run an inferior Prolog process, with I/O via buffer *prolog*."
(interactive)
(require ’comint)
(switch-to-buffer (make-comint "prolog" prolog-program-name))
(inferior-prolog-mode))
The expression (require ’comint) loads the file ‘comint.el’ if it has not yet been loaded.
This ensures that make-comint is defined. Features are normally named after the files that
provide them, so that require need not be given the file name.
The ‘comint.el’ file contains the following top-level expression:
(provide ’comint)
This adds comint to the global features list, so that (require ’comint) will henceforth
know that nothing needs to be done.
When require is used at top level in a file, it takes effect when you byte-compile that
file (see Chapter 16 [Byte Compilation], page 214) as well as when you load it. This is in
case the required package contains macros that the byte compiler must know about. It also
avoids byte-compiler warnings for functions and variables defined in the file loaded with
require.
Although top-level calls to require are evaluated during byte compilation, provide
calls are not. Therefore, you can ensure that a file of definitions is loaded before it is byte-
compiled by including a provide followed by a require for the same feature, as in the
following example.
(provide ’my-feature) ; Ignored by byte compiler,
; evaluated by load.
(require ’my-feature) ; Evaluated by byte compiler.
The compiler ignores the provide, then processes the require by loading the file in ques-
tion. Loading the file does execute the provide call, so the subsequent require call does
nothing when the file is loaded.
Chapter 15: Loading 210
(provide ’foo)
⇒ foo
features
⇒ (foo bar bish)
When a file is loaded to satisfy an autoload, and it stops due to an error in the
evaluation of its contents, any function definitions or provide calls that occurred
during the load are undone. See Section 15.5 [Autoload], page 206.
require feature &optional filename noerror [Function]
This function checks whether feature is present in the current Emacs session (using
(featurep feature ); see below). The argument feature must be a symbol.
If the feature is not present, then require loads filename with load. If filename is
not supplied, then the name of the symbol feature is used as the base file name to
load. However, in this case, require insists on finding feature with an added ‘.el’
or ‘.elc’ suffix (possibly extended with a compression suffix); a file whose name is
just feature won’t be used. (The variable load-suffixes specifies the exact required
Lisp suffixes.)
If noerror is non-nil, that suppresses errors from actual loading of the file. In that
case, require returns nil if loading the file fails. Normally, require returns feature.
If loading the file succeeds but does not provide feature, require signals an error,
‘Required feature feature was not provided’.
featurep feature &optional subfeature [Function]
This function returns t if feature has been provided in the current Emacs session
(i.e., if feature is a member of features.) If subfeature is non-nil, then the function
returns t only if that subfeature is provided as well (i.e. if subfeature is a member of
the subfeature property of the feature symbol.)
features [Variable]
The value of this variable is a list of symbols that are the features loaded in the
current Emacs session. Each symbol was put in this list with a call to provide. The
order of the elements in the features list is not significant.
Chapter 15: Loading 211
load-history [Variable]
This variable’s value is an alist connecting library file names with the names of func-
tions and variables they define, the features they provide, and the features they re-
quire.
Each element is a list and describes one library. The car of the list is the absolute
file name of the library, as a string. The rest of the list elements have these forms:
var The symbol var was defined as a variable.
(defun . fun )
The function fun was defined.
(t . fun ) The function fun was previously an autoload before this library redefined
it as a function. The following element is always (defun . fun ), which
represents defining fun as a function.
(autoload . fun )
The function fun was defined as an autoload.
(require . feature )
The feature feature was required.
(provide . feature )
The feature feature was provided.
The value of load-history may have one element whose car is nil. This element
describes definitions made with eval-buffer on a buffer that is not visiting a file.
The command eval-region updates load-history, but does so by adding the symbols
defined to the element for the file being visited, rather than replacing that element. See
Section 9.3 [Eval], page 116.
15.9 Unloading
You can discard the functions and variables loaded by a library to reclaim memory for other
Lisp objects. To do this, use the function unload-feature:
defmacro, defconst, defvar, and defcustom. It then restores any autoloads for-
merly associated with those symbols. (Loading saves these in the autoload property
of the symbol.)
Before restoring the previous definitions, unload-feature runs remove-hook to re-
move functions in the library from certain hooks. These hooks include variables whose
names end in ‘hook’ or ‘-hooks’, plus those listed in unload-feature-special-
hooks. This is to prevent Emacs from ceasing to function because important hooks
refer to functions that are no longer defined.
If these measures are not sufficient to prevent malfunction, a library can define an
explicit unload hook. If feature -unload-hook is defined, it is run as a normal hook
before restoring the previous definitions, instead of the usual hook-removing actions.
The unload hook ought to undo all the global state changes made by the library
that might cease to work once the library is unloaded. unload-feature can cause
problems with libraries that fail to do this, so it should be used with caution.
Ordinarily, unload-feature refuses to unload a library on which other loaded libraries
depend. (A library a depends on library b if a contains a require for b.) If the
optional argument force is non-nil, dependencies are ignored and you can unload
any library.
The unload-feature function is written in Lisp; its actions are based on the variable
load-history.
unload-feature-special-hooks [Variable]
This variable holds a list of hooks to be scanned before unloading a library, to remove
functions defined in the library.
An error in form does not undo the load, but does prevent execution of the rest of
form.
In general, well-designed Lisp programs should not use this feature. The clean and
modular ways to interact with a Lisp library are (1) examine and set the library’s variables
(those which are meant for outside use), and (2) call the library’s functions. If you wish to
do (1), you can do it immediately—there is no need to wait for when the library is loaded.
To do (2), you must load the library (preferably with require).
But it is OK to use eval-after-load in your personal customizations if you don’t feel
they must meet the design standards for programs meant for wider use.
after-load-alist [Variable]
This variable, an alist built by eval-after-load, holds the expressions to evaluate
when particular libraries are loaded. Each element looks like this:
(regexp-or-feature forms ...)
The key regexp-or-feature is either a regular expression or a symbol, and the value
is a list of forms. The forms are evaluated when the key matches the absolute true
name of the file being loaded or the symbol being provided.
Chapter 16: Byte Compilation 214
16 Byte Compilation
Emacs Lisp has a compiler that translates functions written in Lisp into a special represen-
tation called byte-code that can be executed more efficiently. The compiler replaces Lisp
function definitions with byte-code. When a byte-code function is called, its definition is
evaluated by the byte-code interpreter.
Because the byte-compiled code is evaluated by the byte-code interpreter, instead of
being executed directly by the machine’s hardware (as true compiled code is), byte-code
is completely transportable from machine to machine without recompilation. It is not,
however, as fast as true compiled code.
Compiling a Lisp file with the Emacs byte compiler always reads the file as multibyte
text, even if Emacs was started with ‘--unibyte’, unless the file specifies otherwise. This is
so that compilation gives results compatible with running the same file without compilation.
See Section 15.4 [Loading Non-ASCII], page 205.
In general, any version of Emacs can run byte-compiled code produced by recent earlier
versions of Emacs, but the reverse is not true.
If you do not want a Lisp file to be compiled, ever, put a file-local variable binding for
no-byte-compile into it, like this:
;; -*-no-byte-compile: t; -*-
See Section 18.5 [Compilation Errors], page 267, for how to investigate errors occurring
in byte compilation.
(silly-loop 100000)
⇒ ("Fri Mar 18 17:25:57 1994"
"Fri Mar 18 17:26:28 1994") ; 31 seconds
(byte-compile ’silly-loop)
⇒ [Compiled code not shown]
(silly-loop 100000)
⇒ ("Fri Mar 18 17:26:52 1994"
"Fri Mar 18 17:26:58 1994") ; 6 seconds
Chapter 16: Byte Compilation 215
In this example, the interpreted code required 31 seconds to run, whereas the byte-
compiled code required 6 seconds. These results are representative, but actual results will
vary greatly.
(byte-compile ’factorial)
⇒
#[(integer)
"^H\301U\203^H^@\301\207\302^H\303^HS!\"\207"
[integer 1 * factorial]
4 "Compute factorial of INTEGER."]
Chapter 16: Byte Compilation 216
The result is a byte-code function object. The string it contains is the actual byte-
code; each character in it is an instruction or an operand of an instruction. The vector
contains all the constants, variable names and function names used by the function,
except for certain primitives that are coded as special instructions.
If the argument to byte-compile is a lambda expression, it returns the corresponding
compiled code, but does not store it anywhere.
compile-defun &optional arg [Command]
This command reads the defun containing point, compiles it, and evaluates the result.
If you use this on a defun that is actually a function definition, the effect is to install
a compiled version of that function.
compile-defun normally displays the result of evaluation in the echo area, but if arg
is non-nil, it inserts the result in the current buffer after the form it compiled.
byte-compile-file filename &optional load [Command]
This function compiles a file of Lisp code named filename into a file of byte-code. The
output file’s name is made by changing the ‘.el’ suffix into ‘.elc’; if filename does
not end in ‘.el’, it adds ‘.elc’ to the end of filename.
Compilation works by reading the input file one form at a time. If it is a definition
of a function or macro, the compiled function or macro definition is written out.
Other forms are batched together, then each batch is compiled, and written so that
its compiled code will be executed when the file is read. All comments are discarded
when the input file is read.
This command returns t if there were no errors and nil otherwise. When called
interactively, it prompts for the file name.
If load is non-nil, this command loads the compiled file after compiling it. Interac-
tively, load is the prefix argument.
% ls -l push*
-rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el
(byte-compile-file "~/emacs/push.el")
⇒ t
% ls -l push*
-rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el
-rw-rw-rw- 1 lewis 638 Oct 8 20:25 push.elc
byte-recompile-directory directory &optional flag force [Command]
This command recompiles every ‘.el’ file in directory (or its subdirectories) that
needs recompilation. A file needs recompilation if a ‘.elc’ file exists but is older than
the ‘.el’ file.
When a ‘.el’ file has no corresponding ‘.elc’ file, flag says what to do. If it is nil,
this command ignores these files. If flag is 0, it compiles them. If it is neither nil nor
0, it asks the user whether to compile each such file, and asks about each subdirectory
as well.
Interactively, byte-recompile-directory prompts for directory and flag is the prefix
argument.
Chapter 16: Byte Compilation 217
If force is non-nil, this command recompiles every ‘.el’ file that has a ‘.elc’ file.
The returned value is unpredictable.
batch-byte-compile &optional noforce [Function]
This function runs byte-compile-file on files specified on the command line. This
function must be used only in a batch execution of Emacs, as it kills Emacs on
completion. An error in one file does not prevent processing of subsequent files, but
no output file will be generated for it, and the Emacs process will terminate with a
nonzero status code.
If noforce is non-nil, this function does not recompile files that have an up-to-date
‘.elc’ file.
% emacs -batch -f batch-byte-compile *.el
byte-code code-string data-vector max-stack [Function]
This function actually interprets byte-code. A byte-compiled function is actually
defined with a body that calls byte-code. Don’t call this function yourself—only the
byte compiler knows how to generate valid calls to this function.
In Emacs version 18, byte-code was always executed by way of a call to the function
byte-code. Nowadays, byte-code is usually executed as part of a byte-code function
object, and only rarely through an explicit call to byte-code.
byte-compile-dynamic-docstrings [Variable]
If this is non-nil, the byte compiler generates compiled files that are set up for
dynamic loading of documentation strings.
The dynamic documentation string feature writes compiled files that use a special Lisp
reader construct, ‘#@count ’. This construct skips the next count characters. It also uses
the ‘#$’ construct, which stands for “the name of this file, as a string.” It is usually best
not to use these constructs in Lisp source files, since they are not designed to be clear to
humans reading the file.
byte-compile-dynamic [Variable]
If this is non-nil, the byte compiler generates compiled files that are set up for
dynamic function loading.
docstring The documentation string (if any); otherwise, nil. The value may be a number
or a list, in case the documentation string is stored in a file. Use the function
documentation to get the real documentation string (see Section 24.2 [Access-
ing Documentation], page 426).
interactive
The interactive spec (if any). This can be a string or a Lisp expression. It is
nil for a function that isn’t interactive.
Here’s an example of a byte-code function object, in printed representation. It is the
definition of the command backward-sexp.
#[(&optional arg)
"^H\204^F^@\301^P\302^H[!\207"
[arg 1 forward-sexp]
2
254435
"p"]
The primitive way to create a byte-code object is with make-byte-code:
make-byte-code &rest elements [Function]
This function constructs and returns a byte-code function object with elements as its
elements.
You should not try to come up with the elements for a byte-code function yourself,
because if they are inconsistent, Emacs may crash when you call the function. Always leave
it to the byte compiler to create these objects; it makes the elements consistent (we hope).
You can access the elements of a byte-code object using aref; you can also use vconcat
to create a vector with the same elements.
Here are two examples of using the disassemble function. We have added explanatory
comments to help you relate the byte-code to the Lisp source; these do not appear in the
output of disassemble. These examples show unoptimized byte-code. Nowadays byte-code
is usually optimized, but we did not want to rewrite these examples, since they still serve
their purpose.
(factorial 4)
⇒ 24
(disassemble ’factorial)
a byte-code for factorial:
doc: Compute factorial of an integer.
args: (integer)
(disassemble ’silly-loop)
a byte-code for silly-loop:
doc: Return time before and after N iterations of a loop.
args: (n)
⇒ nil
Chapter 17: Advising Emacs Lisp Functions 226
When this piece of advice runs, it creates an additional line, in the situation where that
is appropriate, but does not move point to that line. This is the correct way to write the
advice, because the normal definition will run afterward and will move back to the newly
inserted line.
Defining the advice doesn’t immediately change the function previous-line. That
happens when you activate the advice, like this:
(ad-activate ’previous-line)
This is what actually begins to use the advice that has been defined so far for the function
previous-line. Henceforth, whenever that function is run, whether invoked by the user
with C-p or M-x, or called from Lisp, it runs the advice first, and its regular definition
second.
This example illustrates before-advice, which is one class of advice: it runs before the
function’s base definition. There are two other advice classes: after-advice, which runs after
the base definition, and around-advice, which lets you specify an expression to wrap around
the invocation of the base definition.
ad-return-value [Variable]
While advice is executing, after the function’s original definition has been executed,
this variable holds its return value, which will ultimately be returned to the caller
after finishing all the advice. After-advice and around-advice can arrange to return
some other value by storing it in this variable.
The argument name is the name of the advice, a non-nil symbol. The advice name
uniquely identifies one piece of advice, within all the pieces of advice in a particular class
for a particular function. The name allows you to refer to the piece of advice—to redefine
it, or to enable or disable it.
Chapter 17: Advising Emacs Lisp Functions 228
The optional position specifies where, in the current list of advice of the specified class,
this new advice should be placed. It should be either first, last or a number that specifies
a zero-based position (first is equivalent to 0). If no position is specified, the default is
first. Position values outside the range of existing positions in this class are mapped to
the beginning or the end of the range, whichever is closer. The position value is ignored
when redefining an existing piece of advice.
The optional arglist can be used to define the argument list for the sake of advice.
This becomes the argument list of the combined definition that is generated in order to
run the advice (see Section 17.10 [Combined Definition], page 235). Therefore, the advice
expressions can use the argument variables in this list to access argument values.
The argument list used in advice need not be the same as the argument list used in
the original function, but must be compatible with it, so that it can handle the ways the
function is actually called. If two pieces of advice for a function both specify an argument
list, they must specify the same argument list.
See Section 17.8 [Argument Access in Advice], page 233, for more information about
argument lists and advice, and a more flexible way for advice to access the arguments.
The remaining elements, flags, are symbols that specify further information about how
to use this piece of advice. Here are the valid symbols and their meanings:
activate Activate the advice for function now. Changes in a function’s advice always
take effect the next time you activate advice for the function; this flag says to
do so, for function, immediately after defining this piece of advice.
This flag has no immediate effect if function itself is not defined yet (a situation
known as forward advice), because it is impossible to activate an undefined
function’s advice. However, defining function will automatically activate its
advice.
protect Protect this piece of advice against non-local exits and errors in preceding code
and advice. Protecting advice places it as a cleanup in an unwind-protect
form, so that it will execute even if the previous code gets an error or uses
throw. See Section 10.5.4 [Cleanups], page 133.
compile Compile the combined definition that is used to run the advice. This flag is
ignored unless activate is also specified. See Section 17.10 [Combined Defini-
tion], page 235.
disable Initially disable this piece of advice, so that it will not be used unless subse-
quently explicitly enabled. See Section 17.6 [Enabling Advice], page 232.
preactivate
Activate advice for function when this defadvice is compiled or macroex-
panded. This generates a compiled advised definition according to the cur-
rent advice state, which will be used during activation if appropriate. See
Section 17.7 [Preactivation], page 232.
This is useful only if this defadvice is byte-compiled.
The optional documentation-string serves to document this piece of advice. When advice
is active for function, the documentation for function (as returned by documentation)
Chapter 17: Advising Emacs Lisp Functions 229
combines the documentation strings of all the advice for function with the documentation
string of its original function definition.
The optional interactive-form form can be supplied to change the interactive behavior
of the original function. If more than one piece of advice has an interactive-form, then the
first one (the one with the smallest position) found among all the advice takes precedence.
The possibly empty list of body-forms specifies the body of the advice. The body of an
advice can access or change the arguments, the return value, the binding environment, and
perform any other kind of side effect.
Warning: When you advise a macro, keep in mind that macros are expanded when a
program is compiled, not when a compiled program is run. All subroutines used by the
advice need to be available when the byte compiler expands the macro.
ad-unadvise-all [Command]
This command deletes all pieces of advice from all functions.
17.3 Around-Advice
Around-advice lets you “wrap” a Lisp expression “around” the original function definition.
You specify where the original function definition should go by means of the special symbol
ad-do-it. Where this symbol occurs inside the around-advice body, it is replaced with a
progn containing the forms of the surrounded code. Here is an example:
(defadvice foo (around foo-around)
"Ignore case in ‘foo’."
(let ((case-fold-search t))
ad-do-it))
Its effect is to make sure that case is ignored in searches when the original definition of foo
is run.
ad-do-it [Variable]
This is not really a variable, rather a place-holder that looks like a variable. You use
it in around-advice to specify the place to run the function’s original definition and
other “earlier” around-advice.
If the around-advice does not use ad-do-it, then it does not run the original function
definition. This provides a way to override the original definition completely. (It also
overrides lower-positioned pieces of around-advice).
If the around-advice uses ad-do-it more than once, the original definition is run at each
place. In this way, around-advice can execute the original definition (and lower-positioned
pieces of around-advice) several times. Another way to do that is by using ad-do-it inside
of a loop.
Chapter 17: Advising Emacs Lisp Functions 230
Activating advice does nothing if function’s advice is already active. But if there is new
advice, added since the previous time you activated advice for function, it activates the new
advice.
ad-deactivate-all [Command]
This command deactivates the advice for all functions.
ad-start-advice [Command]
Turn on automatic advice activation when a function is defined or redefined. This is
the default mode.
ad-stop-advice [Command]
Turn off automatic advice activation when a function is defined or redefined.
If the advised definition was constructed during “preactivation” (see Section 17.7 [Pre-
activation], page 232), then that definition must already be compiled, because it was
constructed during byte-compilation of the file that contained the defadvice with the
preactivate flag.
You can also disable many pieces of advice at once, for various functions, using a regular
expression. As always, the changes take real effect only when you next reactivate advice for
the functions in question.
17.7 Preactivation
Constructing a combined definition to execute advice is moderately expensive. When a
library advises many functions, this can make loading the library slow. In that case, you
can use preactivation to construct suitable combined definitions in advance.
To use preactivation, specify the preactivate flag when you define the advice with
defadvice. This defadvice call creates a combined definition which embodies this piece
of advice (whether enabled or not) plus any other currently enabled advice for the same
Chapter 17: Advising Emacs Lisp Functions 233
function, and the function’s own definition. If the defadvice is compiled, that compiles
the combined definition also.
When the function’s advice is subsequently activated, if the enabled advice for the func-
tion matches what was used to make this combined definition, then the existing combined
definition is used, thus avoiding the need to construct one. Thus, preactivation never causes
wrong results—but it may fail to do any good, if the enabled advice at the time of activation
doesn’t match what was used for preactivation.
Here are some symptoms that can indicate that a preactivation did not work properly,
because of a mismatch.
• Activation of the advised function takes longer than usual.
• The byte-compiler gets loaded while an advised function gets activated.
• byte-compile is included in the value of features even though you did not ever
explicitly use the byte-compiler.
Compiled preactivated advice works properly even if the function itself is not defined
until later; however, the function needs to be defined when you compile the preactivated
advice.
There is no elegant way to find out why preactivated advice is not being used. What you
can do is to trace the function ad-cache-id-verification-code (with the function trace-
function-background) before the advised function’s advice is activated. After activation,
check the value returned by ad-cache-id-verification-code for that function: verified
means that the preactivated advice was used, while other values give some information about
why they were considered inappropriate.
Warning: There is one known case that can make preactivation fail, in that a precon-
structed combined definition is used even though it fails to match the current state of advice.
This can happen when two packages define different pieces of advice with the same name,
in the same class, for the same function. But you should avoid that anyway.
For example,
(ad-define-subr-args ’fset ’(sym newdef))
specifies the argument list for the function fset.
whose form depends on the type of the original function. The variable ad-return-value is
set to whatever this returns. The variable is visible to all pieces of advice, which can access
and modify it before it is actually returned from the advised function.
The semantic structure of advised functions that contain protected pieces of advice is the
same. The only difference is that unwind-protect forms ensure that the protected advice
gets executed even if some previous piece of advice had an error or a non-local exit. If any
around-advice is protected, then the whole around-advice onion is protected as a result.
Chapter 18: Debugging Lisp Programs 237
When this variable is non-nil, Emacs does not create an error handler around process
filter functions and sentinels. Therefore, errors in these functions also invoke the
debugger. See Chapter 37 [Processes], page 705.
To debug an error that happens during loading of the init file, use the option
‘--debug-init’. This binds debug-on-error to t while loading the init file, and bypasses
the condition-case which normally catches errors in the init file.
If your init file sets debug-on-error, the effect may not last past the end of loading the
init file. (This is an undesirable byproduct of the code that implements the ‘--debug-init’
command line option.) The best way to make the init file set debug-on-error permanently
is with after-init-hook, like this:
(add-hook ’after-init-hook
(lambda () (setq debug-on-error t)))
Chapter 18: Debugging Lisp Programs 239
(debug-on-entry ’fact)
⇒ fact
(fact 3)
(symbol-function ’fact)
⇒ (lambda (n)
(debug (quote debug))
(if (zerop n) 1 (* n (fact (1- n)))))
it is wise to go back to the backtrace buffer and exit the debugger (with the q command)
when you are finished with it. Exiting the debugger gets out of the recursive edit and kills
the backtrace buffer.
The backtrace buffer shows you the functions that are executing and their argument
values. It also allows you to specify a stack frame by moving point to the line describing
that frame. (A stack frame is the place where the Lisp interpreter records information
about a particular invocation of a function.) The frame whose line point is on is considered
the current frame. Some of the debugger commands operate on the current frame. If a line
starts with a star, that means that exiting that frame will call the debugger again. This is
useful for examining the return value of a function.
If a function name is underlined, that means the debugger knows where its source code
is located. You can click Mouse-2 on that name, or move to it and type RET, to visit the
source code.
The debugger itself must be run byte-compiled, since it makes assumptions about how
many stack frames are used for the debugger itself. These assumptions are false if the
debugger is running interpreted.
d Continue execution, but enter the debugger the next time any Lisp function is
called. This allows you to step through the subexpressions of an expression,
seeing what values the subexpressions compute, and what else they do.
The stack frame made for the function call which enters the debugger in this
way will be flagged automatically so that the debugger will be called again when
the frame is exited. You can use the u command to cancel this flag.
b Flag the current frame so that the debugger will be entered when the frame
is exited. Frames flagged in this way are marked with stars in the backtrace
buffer.
Chapter 18: Debugging Lisp Programs 242
u Don’t enter the debugger when the current frame is exited. This cancels a b
command on that frame. The visible effect is to remove the star from the line
in the backtrace buffer.
j Flag the current frame like b. Then continue execution like c, but temporarily
disable break-on-entry for all functions that are set up to do so by debug-on-
entry.
e Read a Lisp expression in the minibuffer, evaluate it, and print the value in the
echo area. The debugger alters certain important variables, and the current
buffer, as part of its operation; e temporarily restores their values from outside
the debugger, so you can examine and change them. This makes the debugger
more transparent. By contrast, M-: does nothing special in the debugger; it
shows you the variable values within the debugger.
R Like e, but also save the result of evaluation in the buffer ‘*Debugger-record*’.
q Terminate the program being debugged; return to top-level Emacs command
execution.
If the debugger was entered due to a C-g but you really want to quit, and not
debug, use the q command.
r Return a value from the debugger. The value is computed by reading an ex-
pression with the minibuffer and evaluating it.
The r command is useful when the debugger was invoked due to exit from a
Lisp call frame (as requested with b or by entering the frame with d); then the
value specified in the r command is used as the value of that frame. It is also
useful if you call debug and use its return value. Otherwise, r has the same
effect as c, and the specified return value does not matter.
You can’t use r when the debugger was entered due to an error.
l Display a list of functions that will invoke the debugger when called. This
is a list of functions that are set to break on entry by means of debug-on-
entry. Warning: if you redefine such a function and thus cancel the effect of
debug-on-entry, it may erroneously show up in this list.
However, certain values for first argument to debug have a special significance. (Nor-
mally, these values are used only by the internals of Emacs, and not by programmers
calling debug.) Here is a table of these special values:
lambda A first argument of lambda means debug was called because of entry to a
function when debug-on-next-call was non-nil. The debugger displays
‘Debugger entered--entering a function:’ as a line of text at the top
of the buffer.
debug debug as first argument means debug was called because of entry to a
function that was set to debug on entry. The debugger displays the string
‘Debugger entered--entering a function:’, just as in the lambda case.
It also marks the stack frame for that function so that it will invoke the
debugger when exited.
t When the first argument is t, this indicates a call to debug due to eval-
uation of a function call form when debug-on-next-call is non-nil.
The debugger displays ‘Debugger entered--beginning evaluation of
function call form:’ as the top line in the buffer.
exit When the first argument is exit, it indicates the exit of a stack frame
previously marked to invoke the debugger on exit. The second argument
given to debug in this case is the value being returned from the frame.
The debugger displays ‘Debugger entered--returning value:’ in the
top line of the buffer, followed by the value being returned.
error When the first argument is error, the debugger indicates that it is being
entered because an error or quit was signaled and not handled, by dis-
playing ‘Debugger entered--Lisp error:’ followed by the error signaled
and any arguments to signal. For example,
(let ((debug-on-error t))
(/ 1 0))
debugger [Variable]
The value of this variable is the function to call to invoke the debugger. Its value
must be a function of any number of arguments, or, more typically, the name of a
function. This function should invoke some kind of debugger. The default value of
the variable is debug.
The first argument that Lisp hands to the function indicates why it was called. The
convention for arguments is detailed in the description of debug (see Section 18.1.7
[Invoking the Debugger], page 242).
backtrace [Command]
This function prints a trace of Lisp function calls currently active. This is the function
used by debug to fill up the ‘*Backtrace*’ buffer. It is written in C, since it must
have access to the stack to determine which function calls are active. The return
value is always nil.
In the following example, a Lisp expression calls backtrace explicitly. This prints
the backtrace to the stream standard-output, which, in this case, is the buffer
‘backtrace-output’.
Each line of the backtrace represents one function call. The line shows the values of
the function’s arguments if they are all known; if they are still being computed, the
line says so. The arguments of special forms are elided.
(with-output-to-temp-buffer "backtrace-output"
(let ((var 1))
(save-excursion
(setq var (eval ’(progn
(1+ var)
(list ’testing (backtrace))))))))
⇒ (testing nil)
debug-on-next-call [Variable]
If this variable is non-nil, it says to call the debugger before the next eval, apply
or funcall. Entering the debugger sets debug-on-next-call to nil.
The d command in the debugger works by setting this variable.
backtrace-debug level flag [Function]
This function sets the debug-on-exit flag of the stack frame level levels down the stack,
giving it the value flag. If flag is non-nil, this will cause the debugger to be entered
Chapter 18: Debugging Lisp Programs 245
when that frame later exits. Even a nonlocal exit through that frame will enter the
debugger.
This function is used only by the debugger.
command-debug-status [Variable]
This variable records the debugging status of the current interactive command. Each
time a command is called interactively, this variable is bound to nil. The debugger
can set this variable to leave information for future debugger invocations during the
same command invocation.
The advantage of using this variable rather than an ordinary global variable is that
the data will never carry over to a subsequent command invocation.
18.2 Edebug
Edebug is a source-level debugger for Emacs Lisp programs with which you can:
• Step through evaluation, stopping before and after each expression.
• Set conditional or unconditional breakpoints.
• Stop when a specified condition is true (the global break event).
• Trace slow or fast, stopping briefly at each stop point, or at each breakpoint.
• Display expression results and evaluate expressions as if outside of Edebug.
• Automatically re-evaluate a list of expressions and display their results each time Ede-
bug updates the display.
• Output trace info on function enter and exit.
• Stop when an error occurs.
• Display a backtrace, omitting Edebug’s own frames.
• Specify argument evaluation for macros and defining forms.
• Obtain rudimentary coverage testing and frequency counts.
The first three sections below should tell you enough about Edebug to enable you to use
it.
Chapter 18: Debugging Lisp Programs 246
Normally, you specify the Edebug execution mode by typing a command to continue the
program in a certain mode. Here is a table of these commands; all except for S resume
execution of the program, at least for a certain distance.
S Stop: don’t execute any more of the program, but wait for more Edebug com-
mands (edebug-stop).
SPC Step: stop at the next stop point encountered (edebug-step-mode).
n Next: stop at the next stop point encountered after an expression
(edebug-next-mode). Also see edebug-forward-sexp in Section 18.2.4
[Jumping], page 249.
t Trace: pause (normally one second) at each Edebug stop point (edebug-trace-
mode).
T Rapid trace: update the display at each stop point, but don’t actually pause
(edebug-Trace-fast-mode).
g Go: run until the next breakpoint (edebug-go-mode). See Section 18.2.6.1
[Breakpoints], page 250.
c Continue: pause one second at each breakpoint, and then continue (edebug-
continue-mode).
C Rapid continue: move point to each breakpoint, but don’t pause (edebug-
Continue-fast-mode).
G Go non-stop: ignore breakpoints (edebug-Go-nonstop-mode). You can still
stop the program by typing S, or any editing command.
In general, the execution modes earlier in the above list run the program more slowly or
stop sooner than the modes later in the list.
While executing or tracing, you can interrupt the execution by typing any Edebug com-
mand. Edebug stops the program at the next stop point and then executes the command
you typed. For example, typing t during execution switches to trace mode at the next stop
point. You can use S to stop execution without doing anything else.
If your function happens to read input, a character you type intending to interrupt
execution may be read by the function instead. You can avoid such unintended results by
paying attention to when your program wants input.
Keyboard macros containing the commands in this section do not completely work:
exiting from Edebug, to resume the program, loses track of the keyboard macro. This
is not easy to fix. Also, defining or executing a keyboard macro outside of Edebug does
not affect commands inside Edebug. This is usually an advantage. See also the edebug-
continue-kbd-macro option (see Section 18.2.16 [Edebug Options], page 263).
When you enter a new Edebug level, the initial execution mode comes from the value of
the variable edebug-initial-mode. (See Section 18.2.16 [Edebug Options], page 263.) By
default, this specifies step mode. Note that you may reenter the same Edebug level several
times if, for example, an instrumented function is called several times from one command.
edebug-sit-for-seconds [User Option]
This option specifies how many seconds to wait between execution steps in trace
mode. The default is 1 second.
Chapter 18: Debugging Lisp Programs 249
18.2.4 Jumping
The commands described in this section execute until they reach a specified location. All
except i make a temporary breakpoint to establish the place to stop, then switch to go mode.
Any other breakpoint reached before the intended stop point will also stop execution. See
Section 18.2.6.1 [Breakpoints], page 250, for the details on breakpoints.
These commands may fail to work as expected in case of nonlocal exit, as that can bypass
the temporary breakpoint where you expected the program to stop.
h Proceed to the stop point near where point is (edebug-goto-here).
f Run the program for one expression (edebug-forward-sexp).
o Run the program until the end of the containing sexp.
i Step into the function or macro called by the form after point.
The h command proceeds to the stop point at or after the current location of point,
using a temporary breakpoint.
The f command runs the program forward over one expression. More precisely, it sets
a temporary breakpoint at the position that C-M-f would reach, then executes in go mode
so that the program will stop at breakpoints.
With a prefix argument n, the temporary breakpoint is placed n sexps beyond point. If
the containing list ends before n more elements, then the place to stop is after the containing
expression.
You must check that the position C-M-f finds is a place that the program will really get
to. In cond, for example, this may not be true.
For flexibility, the f command does forward-sexp starting at point, rather than at the
stop point. If you want to execute one expression from the current stop point, first type w,
to move point there, and then type f.
The o command continues “out of” an expression. It places a temporary breakpoint at
the end of the sexp containing point. If the containing sexp is a function definition itself, o
continues until just before the last sexp in the definition. If that is where you are now, it
returns from the function and then stops. In other words, this command does not exit the
currently executing function unless you are positioned after the last sexp.
The i command steps into the function or macro called by the list form after point, and
stops at its first stop point. Note that the form need not be the one about to be evaluated.
But if the form is a function call about to be evaluated, remember to use this command
before any of the arguments are evaluated, since otherwise it will be too late.
The i command instruments the function or macro it’s supposed to step into, if it isn’t
instrumented already. This is convenient, but keep in mind that the function or macro
remains instrumented unless you explicitly arrange to deinstrument it.
q Return to the top level editor command loop (top-level). This exits all re-
cursive editing levels, including all levels of Edebug activity. However, instru-
mented code protected with unwind-protect or condition-case forms may
resume debugging.
Q Like q, but don’t stop even for protected code (top-level-nonstop).
r Redisplay the most recently known expression result in the echo area (edebug-
previous-result).
d Display a backtrace, excluding Edebug’s own functions for clarity (edebug-
backtrace).
You cannot use debugger commands in the backtrace buffer in Edebug as you
would in the standard debugger.
The backtrace buffer is killed automatically when you continue execution.
You can invoke commands from Edebug that activate Edebug again recursively. When-
ever Edebug is active, you can quit to the top level with q or abort one recursive edit level
with C-]. You can display a backtrace of all the pending evaluations with d.
18.2.6 Breaks
Edebug’s step mode stops execution when the next stop point is reached. There are three
other ways to stop Edebug execution once it has started: breakpoints, the global break
condition, and source breakpoints.
A conditional breakpoint tests a condition each time the program gets there. Any errors
that occur as a result of evaluating the condition are ignored, as if the result were nil. To
set a conditional breakpoint, use x, and specify the condition expression in the minibuffer.
Setting a conditional breakpoint at a stop point that has a previously established conditional
breakpoint puts the previous condition expression in the minibuffer so you can edit it.
You can make a conditional or unconditional breakpoint temporary by using a prefix
argument with the command to set the breakpoint. When a temporary breakpoint stops
the program, it is automatically unset.
Edebug always stops or pauses at a breakpoint, except when the Edebug mode is Go-
nonstop. In that mode, it ignores breakpoints entirely.
To find out where your breakpoints are, use the B command, which moves point to the
next breakpoint following point, within the same function, or to the first breakpoint if there
are no following breakpoints. This command does not continue execution—it just moves
point in the buffer.
18.2.9 Evaluation
While within Edebug, you can evaluate expressions “as if” Edebug were not running. Ede-
bug tries to be invisible to the expression’s evaluation and printing. Evaluation of expres-
sions that cause side effects will work as expected, except for changes to data that Edebug
explicitly saves and restores. See Section 18.2.14 [The Outside Context], page 257, for
details on this process.
e exp RET Evaluate expression exp in the context outside of Edebug (edebug-eval-
expression). That is, Edebug tries to minimize its interference with the
evaluation.
M-: exp RET
Evaluate expression exp in the context of Edebug itself.
C-x C-e Evaluate the expression before point, in the context outside of Edebug (edebug-
eval-last-sexp).
Edebug supports evaluation of expressions containing references to lexically bound sym-
bols created by the following constructs in ‘cl.el’ (version 2.03 or later): lexical-let,
macrolet, and symbol-macrolet.
The command C-c C-u (edebug-update-eval-list) rebuilds the evaluation list, scan-
ning the buffer and using the first expression of each group. (The idea is that the second
expression of the group is the value previously computed and displayed.)
Each entry to Edebug redisplays the evaluation list by inserting each expression in the
buffer, followed by its current value. It also inserts comment lines so that each expression
becomes its own group. Thus, if you type C-c C-u again without changing the buffer text,
the evaluation list is effectively unchanged.
If an error occurs during an evaluation from the evaluation list, the error message is
displayed in a string as if it were the result. Therefore, expressions that use variables not
currently valid do not interrupt your debugging.
Here is an example of what the evaluation list window looks like after several expressions
have been added to it:
(current-buffer)
#<buffer *scratch*>
;---------------------------------------------------------------
(selected-window)
#<window 16 on *scratch*>
;---------------------------------------------------------------
(point)
196
;---------------------------------------------------------------
bad-var
"Symbol’s value as variable is void: bad-var"
;---------------------------------------------------------------
(recursion-depth)
0
;---------------------------------------------------------------
this-command
eval-last-sexp
;---------------------------------------------------------------
To delete a group, move point into it and type C-c C-d, or simply delete the text for
the group and update the evaluation list with C-c C-u. To add a new expression to the
evaluation list, insert the expression at a suitable place, insert a new comment line, then
type C-c C-u. You need not insert dashes in the comment line—its contents don’t matter.
After selecting ‘*edebug*’, you can return to the source code buffer with C-c C-w. The
‘*edebug*’ buffer is killed when you continue execution, and recreated next time it is needed.
edebug-display-freq-count [Command]
This command displays the frequency count data for each line of the current definition.
The frequency counts appear as comment lines after each line of code, and you can
undo all insertions with one undo command. The counts appear under the ‘(’ before
an expression or the ‘)’ after an expression, or on the last character of a variable.
To simplify the display, a count is not shown if it is equal to the count of an earlier
expression on the same line.
The character ‘=’ following the count for an expression says that the expression has
returned the same value each time it was evaluated. In other words, it is not yet
“covered” for coverage testing purposes.
To clear the frequency count and coverage data for a definition, simply reinstrument
it with eval-defun.
For example, after evaluating (fac 5) with a source breakpoint, and setting edebug-
test-coverage to t, when the breakpoint is reached, the frequency data looks like this:
(defun fac (n)
(if (= n 0) (edebug))
;#6 1 = =5
(if (< 0 n)
;#5 =
(* n (fac (1- n)))
;# 5 0
1))
;# 0
The comment lines show that fac was called 6 times. The first if statement returned
5 times with the same result each time; the same is true of the condition on the second if.
The recursive call of fac did not return at all.
Chapter 18: Debugging Lisp Programs 257
The Edebug specification says which parts of a call to the macro are forms to be evalu-
ated. For simple macros, the specification often looks very similar to the formal argument
list of the macro definition, but specifications are much more general than macro arguments.
See Section 13.4 [Defining Macros], page 178, for more explanation of the declare form.
You can also define an edebug specification for a macro separately from the macro defini-
tion with def-edebug-spec. Adding debug declarations is preferred, and more convenient,
for macro definitions in Lisp, but def-edebug-spec makes it possible to define Edebug
specifications for special forms implemented in C.
Here is a table of the possibilities for specification and how each directs processing of
arguments.
t All arguments are instrumented for evaluation.
0 None of the arguments is instrumented.
a symbol The symbol must have an Edebug specification which is used instead. This
indirection is repeated until another kind of specification is found. This allows
you to inherit the specification from another macro.
a list The elements of the list describe the types of the arguments of a calling form.
The possible elements of a specification list are described in the following sec-
tions.
If a macro has no Edebug specification, neither through a debug declaration nor through
a def-edebug-spec call, the variable edebug-eval-macro-args comes into play. If it is
nil, the default, none of the arguments is instrumented for evaluation. If it is non-nil, all
arguments are instrumented.
Here’s a table of the possible elements of a specification list, with their meanings (see
Section 18.2.15.4 [Specification Examples], page 263, for the referenced examples):
sexp A single unevaluated Lisp object, which is not instrumented.
form A single evaluated expression, which is instrumented.
place A place to store a value, as in the Common Lisp setf construct.
body Short for &rest form. See &rest below.
function-form
A function form: either a quoted function symbol, a quoted lambda expression,
or a form (that should evaluate to a function symbol or lambda expression).
This is useful when an argument that’s a lambda expression might be quoted
with quote rather than function, since it instruments the body of the lambda
expression either way.
lambda-expr
A lambda expression with no quoting.
&optional
All following elements in the specification list are optional; as soon as one does
not match, Edebug stops matching at this level.
To make just a few elements optional followed by non-optional elements, use
[&optional specs ...]. To specify that several elements must all match or
none, use &optional [specs ...]. See the defun example.
&rest All following elements in the specification list are repeated zero or more times.
In the last repetition, however, it is not a problem if the expression runs out
before matching all of the elements of the specification list.
To repeat only a few elements, use [&rest specs ...]. To specify several ele-
ments that must all match on every repetition, use &rest [specs ...].
&or Each of the following elements in the specification list is an alternative. One of
the alternatives must match, or the &or specification fails.
Each list element following &or is a single alternative. To group two or more
list elements as a single alternative, enclose them in [...].
¬ Each of the following elements is matched as alternatives as if by using &or, but
if any of them match, the specification fails. If none of them match, nothing is
matched, but the ¬ specification succeeds.
&define Indicates that the specification is for a defining form. The defining form itself
is not instrumented (that is, Edebug does not stop before and after the defining
form), but forms inside it typically will be instrumented. The &define keyword
should be the first element in a list specification.
nil This is successful when there are no more arguments to match at the current ar-
gument list level; otherwise it fails. See sublist specifications and the backquote
example.
gate No argument is matched but backtracking through the gate is disabled while
matching the remainder of the specifications at this level. This is primarily
Chapter 18: Debugging Lisp Programs 261
used to generate more specific syntax error messages. See Section 18.2.15.3
[Backtracking], page 262, for more details. Also see the let example.
other-symbol
Any other symbol in a specification list may be a predicate or an indirect
specification.
If the symbol has an Edebug specification, this indirect specification should
be either a list specification that is used in place of the symbol, or a function
that is called to process the arguments. The specification may be defined with
def-edebug-spec just as for macros. See the defun example.
Otherwise, the symbol should be a predicate. The predicate is called with the
argument and the specification fails if the predicate returns nil. In either case,
that argument is not instrumented.
Some suitable predicates include symbolp, integerp, stringp, vectorp, and
atom.
[elements ...]
A vector of elements groups the elements into a single group specification. Its
meaning has nothing to do with vectors.
"string " The argument should be a symbol named string. This specification is equivalent
to the quoted symbol, ’symbol , where the name of symbol is the string, but
the string form is preferred.
(vector elements ...)
The argument should be a vector whose elements must match the elements in
the specification. See the backquote example.
(elements ...)
Any other list is a sublist specification and the argument must be a list whose
elements match the specification elements.
A sublist specification may be a dotted list and the corresponding list argu-
ment may then be a dotted list. Alternatively, the last cdr of a dotted list
specification may be another sublist specification (via a grouping or an indi-
rect specification, e.g., (spec . [(more specs...)])) whose elements match
the non-dotted list arguments. This is useful in recursive specifications such as
in the backquote example. Also see the description of a nil specification above
for terminating such recursion.
Note that a sublist specification written as (specs . nil) is equivalent to
(specs), and (specs . (sublist-elements...)) is equivalent to (specs
sublist-elements...).
Here is a list of additional specifications that may appear only after &define. See the
defun example.
name The argument, a symbol, is the name of the defining form.
A defining form is not required to have a name field; and it may have multiple
name fields.
Chapter 18: Debugging Lisp Programs 262
:name This construct does not actually match an argument. The element following
:name should be a symbol; it is used as an additional name component for the
definition. You can use this to add a unique, static component to the name of
the definition. It may be used more than once.
arg The argument, a symbol, is the name of an argument of the defining form.
However, lambda-list keywords (symbols starting with ‘&’) are not allowed.
lambda-list
This matches a lambda list—the argument list of a lambda expression.
def-body The argument is the body of code in a definition. This is like body, described
above, but a definition body must be instrumented with a different Edebug call
that looks up information associated with the definition. Use def-body for the
highest level list of forms within the definition.
def-form The argument is a single, highest-level form in a definition. This is like def-
body, except use this to match a single form rather than a list of forms. As a
special case, def-form also means that tracing information is not output when
the form is executed. See the interactive example.
(def-edebug-spec lambda-list
(([&rest arg]
[&optional ["&optional" arg &rest arg]]
&optional ["&rest" arg]
)))
(def-edebug-spec interactive
(&optional &or stringp def-form)) ; Notice: def-form
The specification for backquote below illustrates how to match dotted lists and use nil
to terminate recursion. It also illustrates how components of a vector may be matched.
(The actual specification defined by Edebug does not support dotted lists because doing so
causes very deep recursion that could fail.)
(def-edebug-spec ‘ (backquote-form)) ; Alias just for clarity.
(def-edebug-spec backquote-form
(&or ([&or "," ",@"] &or ("quote" backquote-form) form)
(backquote-form . [&or nil backquote-form])
(vector &rest backquote-form)
sexp))
Now you can go to the beginning of the defun and type C-M-q. Usually all the lines from
a certain point to the end of the function will shift to the right. There is probably a missing
close parenthesis, or a superfluous open parenthesis, near that point. (However, don’t
assume this is true; study the code to make sure.) Once you have found the discrepancy,
undo the C-M-q with C-_, since the old indentation is probably appropriate to the intended
parentheses.
After you think you have fixed the problem, use C-M-q again. If the old indentation
actually fit the intended nesting of parentheses, and you have put back those parentheses,
C-M-q should not change anything.
Edebug also has a coverage testing feature (see Section 18.2.13 [Coverage Testing],
page 256). These features partly duplicate each other, and it would be cleaner to com-
bine them.
string The input characters are taken from string, starting at the first character in the
string and using as many characters as required.
function The input characters are generated by function, which must support two kinds
of calls:
• When it is called with no arguments, it should return the next character.
• When it is called with one argument (always a character), function should
save the argument and arrange to return it on the next call. This is called
unreading the character; it happens when the Lisp reader reads one char-
acter too many and wants to “put it back where it came from.” In this
case, it makes no difference what value function returns.
t t used as a stream means that the input is read from the minibuffer. In fact,
the minibuffer is invoked once and the text given by the user is made into a
string that is then used as the input stream. If Emacs is running in batch mode,
standard input is used instead of the minibuffer. For example,
(message "%s" (read t))
will read a Lisp expression from standard input and print the result to standard
output.
nil nil supplied as an input stream means to use the value of standard-input
instead; that value is the default input stream, and must be a non-nil input
stream.
symbol A symbol as input stream is equivalent to the symbol’s function definition (if
any).
Here is an example of reading from a stream that is a buffer, showing where point is
located before and after:
---------- Buffer: foo ----------
This? is the contents of foo.
---------- Buffer: foo ----------
useless-list
⇒ (40 41)
Note that the open and close parentheses remain in the list. The Lisp reader encountered
the open parenthesis, decided that it ended the input, and unread it. Another attempt to
read from the stream at this point would read ‘()’ and return nil.
get-file-char [Function]
This function is used internally as an input stream to read from the input file opened
by the function load. Don’t use this function yourself.
Chapter 19: Reading and Printing Lisp Objects 271
standard-input [Variable]
This variable holds the default input stream—the stream that read uses when the
stream argument is nil. The default is t, meaning use the minibuffer.
marker The output characters are inserted into the buffer that marker points into, at
the marker position. The marker position advances as characters are inserted.
The value of point in the buffer has no effect on printing when the stream is a
marker, and this kind of printing does not move point (except that if the marker
points at or before the position of point, point advances with the surrounding
text, as usual).
function The output characters are passed to function, which is responsible for storing
them away. It is called with a single character as argument, as many times as
there are characters to be output, and is responsible for storing the characters
wherever you want to put them.
t The output characters are displayed in the echo area.
nil nil specified as an output stream means to use the value of standard-output
instead; that value is the default output stream, and must not be nil.
symbol A symbol as output stream is equivalent to the symbol’s function definition (if
any).
Many of the valid output streams are also valid as input streams. The difference between
input and output streams is therefore more a matter of how you use a Lisp object, than of
different types of object.
Here is an example of a buffer used as an output stream. Point is initially located as
shown immediately before the ‘h’ in ‘the’. At the end, point is located directly before that
same ‘h’.
---------- Buffer: foo ----------
This is t?he contents of foo.
---------- Buffer: foo ----------
m
⇒ #<marker at 34 in foo>
The following example shows output to the echo area:
(print "Echo Area output" t)
⇒ "Echo Area output"
---------- Echo Area ----------
"Echo Area output"
---------- Echo Area ----------
Finally, we show the use of a function as an output stream. The function eat-output
takes each character that it is given and conses it onto the front of the list last-output
(see Section 5.4 [Building Lists], page 67). At the end, the list contains all the characters
output, but in reverse order.
(setq last-output nil)
⇒ nil
last-output
⇒ (10 34 116 117 112 116 117 111 32 101 104
116 32 115 105 32 115 105 104 84 34 10)
Now we can put the output in the proper order by reversing the list:
(concat (nreverse last-output))
⇒ "
\"This is the output\"
"
Calling concat converts the list to a string so you can see its contents more clearly.
Some of the Emacs printing functions add quoting characters to the output when nec-
essary so that it can be read properly. The quoting characters used are ‘"’ and ‘\’; they
distinguish strings from symbols, and prevent punctuation characters in strings and sym-
bols from being taken as delimiters when reading. See Section 2.1 [Printed Representation],
page 8, for full details. You specify quoting or no quoting by the choice of printing function.
If the text is to be read back into Lisp, then you should print with quoting characters
to avoid ambiguity. Likewise, if the purpose is to describe a Lisp object clearly for a Lisp
programmer. However, if the purpose of the output is to look nice for humans, then it is
usually better to print without quoting.
Lisp objects can refer to themselves. Printing a self-referential object in the normal way
would require an infinite amount of text, and the attempt could cause infinite recursion.
Emacs detects such recursion and prints ‘#level ’ instead of recursively printing an object
already being printed. For example, here ‘#0’ indicates a recursive reference to the object
at level 0 of the current print operation:
(setq foo (list nil))
⇒ (nil)
(setcar foo foo)
⇒ (#0)
In the functions below, stream stands for an output stream. (See the previous section
for a description of output streams.) If stream is nil or omitted, it defaults to the value of
standard-output.
print-quoted [Variable]
If this is non-nil, that means to print quoted forms using abbreviated reader syntax.
(quote foo) prints as ’foo, (function foo) as #’foo, and backquoted forms print
using modern backquote syntax.
print-escape-newlines [Variable]
If this variable is non-nil, then newline characters in strings are printed as ‘\n’ and
formfeeds are printed as ‘\f’. Normally these characters are printed as actual newlines
and formfeeds.
This variable affects the print functions prin1 and print that print with quoting. It
does not affect princ. Here is an example using prin1:
(prin1 "a\nb")
a "a
a b"
⇒ "a
b"
print-escape-nonascii [Variable]
If this variable is non-nil, then unibyte non-ASCII characters in strings are uncondi-
tionally printed as backslash sequences by the print functions prin1 and print that
print with quoting.
Those functions also use backslash sequences for unibyte non-ASCII characters, re-
gardless of the value of this variable, when the output stream is a multibyte buffer or
a marker pointing into one.
print-escape-multibyte [Variable]
If this variable is non-nil, then multibyte non-ASCII characters in strings are un-
conditionally printed as backslash sequences by the print functions prin1 and print
that print with quoting.
Those functions also use backslash sequences for multibyte non-ASCII characters,
regardless of the value of this variable, when the output stream is a unibyte buffer or
a marker pointing into one.
Chapter 19: Reading and Printing Lisp Objects 277
print-length [Variable]
The value of this variable is the maximum number of elements to print in any list,
vector or bool-vector. If an object being printed has more than this many elements,
it is abbreviated with an ellipsis.
If the value is nil (the default), then there is no limit.
(setq print-length 2)
⇒ 2
(print ’(1 2 3 4 5))
a (1 2 ...)
⇒ (1 2 ...)
print-level [Variable]
The value of this variable is the maximum depth of nesting of parentheses and brackets
when printed. Any list or vector at a depth exceeding this limit is abbreviated with
an ellipsis. A value of nil (which is the default) means no limit.
eval-expression-print-length [User Option]
eval-expression-print-level [User Option]
These are the values for print-length and print-level used by eval-expression,
and thus, indirectly, by many interactive evaluation commands (see section “Evalu-
ating Emacs-Lisp Expressions” in The GNU Emacs Manual).
These variables are used for detecting and reporting circular and shared structure:
print-circle [Variable]
If non-nil, this variable enables detection of circular and shared structure in printing.
print-gensym [Variable]
If non-nil, this variable enables detection of uninterned symbols (see Section 8.3
[Creating Symbols], page 104) in printing. When this is enabled, uninterned symbols
print with the prefix ‘#:’, which tells the Lisp reader to produce an uninterned symbol.
print-continuous-numbering [Variable]
If non-nil, that means number continuously across print calls. This affects the num-
bers printed for ‘#n =’ labels and ‘#m #’ references.
Don’t set this variable with setq; you should only bind it temporarily to t with let.
When you do that, you should also bind print-number-table to nil.
print-number-table [Variable]
This variable holds a vector used internally by printing to implement the print-
circle feature. You should not use it except to bind it to nil when you bind
print-continuous-numbering.
float-output-format [Variable]
This variable specifies how to print floating point numbers. Its default value is nil,
meaning use the shortest output that represents the number without losing informa-
tion.
To control output format more precisely, you can put a string in this variable. The
string should hold a ‘%’-specification to be used in the C function sprintf. For further
restrictions on what you can use, see the variable’s documentation string.
Chapter 20: Minibuffers 278
20 Minibuffers
A minibuffer is a special buffer that Emacs commands use to read arguments more compli-
cated than the single numeric prefix argument. These arguments include file names, buffer
names, and command names (as in M-x). The minibuffer is displayed on the bottom line of
the frame, in the same place as the echo area (see Section 38.4 [The Echo Area], page 741),
but only while it is in use for reading an argument.
for the non-completion minibuffer local maps. See Section 20.6.3 [Completion Commands],
page 289, for the minibuffer local maps for completion.
When Emacs is running in batch mode, any request to read from the minibuffer actually
reads a line from the standard input descriptor that was supplied when Emacs was started.
minibuffer-allow-text-properties [Variable]
If this variable is nil, then read-from-minibuffer strips all text properties from the
minibuffer input before returning it. This variable also affects read-string. How-
ever, read-no-blanks-input (see below), as well as read-minibuffer and related
functions (see Section 20.3 [Reading Lisp Objects With the Minibuffer], page 281),
and all functions that do minibuffer input with completion, discard text properties
unconditionally, regardless of the value of this variable.
minibuffer-local-map [Variable]
This is the default local keymap for reading from the minibuffer. By default, it makes
the following bindings:
C-j exit-minibuffer
RET exit-minibuffer
C-g abort-recursive-edit
M-n
DOWN next-history-element
Chapter 20: Minibuffers 281
M-p
UP previous-history-element
M-s next-matching-history-element
M-r previous-matching-history-element
minibuffer-local-ns-map [Variable]
This built-in variable is the keymap used as the minibuffer local keymap in the func-
tion read-no-blanks-input. By default, it makes the following bindings, in addition
to those of minibuffer-local-map:
SPC exit-minibuffer
TAB exit-minibuffer
? self-insert-and-exit
history-add-new-input [Variable]
If the value of this variable is nil, standard functions that read from the minibuffer
don’t add new elements to the history list. This lets Lisp programs explicitly manage
input history by using add-to-history. By default, history-add-new-input is set
to a non-nil value.
history-length [Variable]
The value of this variable specifies the maximum length for all history lists that don’t
specify their own maximum lengths. If the value is t, that means there no maximum
(don’t delete old elements). The value of history-length property of the history list
variable’s symbol, if set, overrides this variable for that particular history list.
Chapter 20: Minibuffers 284
history-delete-duplicates [Variable]
If the value of this variable is t, that means when adding a new history element, all
previous identical elements are deleted.
minibuffer-history [Variable]
The default history list for minibuffer history input.
query-replace-history [Variable]
A history list for arguments to query-replace (and similar arguments to other com-
mands).
file-name-history [Variable]
A history list for file-name arguments.
buffer-name-history [Variable]
A history list for buffer-name arguments.
regexp-history [Variable]
A history list for regular expression arguments.
extended-command-history [Variable]
A history list for arguments that are names of extended commands.
shell-command-history [Variable]
A history list for arguments that are shell commands.
read-expression-history [Variable]
A history list for arguments that are Lisp expressions to evaluate.
the beginning of the string, 1 means after the first character, etc. In read-minibuffer, and
the other non-completion minibuffer input functions that support this argument, 1 means
the beginning of the string 2 means after the first character, etc.
Use of a cons cell as the value for initial arguments is deprecated in user code.
20.6 Completion
Completion is a feature that fills in the rest of a name starting from an abbreviation for
it. Completion works by comparing the user’s input against a list of valid names and
determining how much of the name is determined uniquely by what the user has typed.
For example, when you type C-x b (switch-to-buffer) and then type the first few letters
of the name of the buffer to which you wish to switch, and then type TAB (minibuffer-
complete), Emacs extends the name as far as it can.
Standard Emacs commands offer completion for names of symbols, files, buffers, and
processes; with the functions in this section, you can implement completion for other kinds
of names.
The try-completion function is the basic primitive for completion: it returns the longest
determined completion of a given initial string, with a given set of strings to match against.
The function completing-read provides a higher-level interface for completion. A call
to completing-read specifies how to determine the list of valid names. The function then
activates the minibuffer with a local keymap that binds a few keys to commands useful for
completion. Other functions provide convenient simple interfaces for reading certain kinds
of names with completion.
In the following example, numerous symbols begin with the characters ‘forw’, and all
of them begin with the word ‘forward’. In most of the symbols, this is followed with
a ‘-’, but not in all, so no more than ‘forward’ can be completed.
(try-completion "forw" obarray)
⇒ "forward"
Finally, in the following example, only two of the three possible matches pass the
predicate test (the string ‘foobaz’ is too short). Both of those begin with the string
‘foobar’.
Chapter 20: Minibuffers 287
(all-completions
"foo"
’(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
’test)
⇒ ("foobar1" "foobar2")
search (see Section 34.2 [Searching and Case], page 663) bound to the value of
completion-ignore-case.
minibuffer-completion-table [Variable]
The value of this variable is the collection used for completion in the minibuffer.
This is the global variable that contains what completing-read passes to try-
completion. It is used by minibuffer completion commands such as minibuffer-
complete-word.
minibuffer-completion-predicate [Variable]
This variable’s value is the predicate that completing-read passes to try-
completion. The variable is also used by the other minibuffer completion
functions.
minibuffer-completion-confirm [Variable]
When the value of this variable is non-nil, Emacs asks for confirmation of a com-
pletion before exiting the minibuffer. completing-read binds this variable, and the
function minibuffer-complete-and-exit checks the value before exiting.
minibuffer-complete-word [Command]
This function completes the minibuffer contents by at most a single word. Even if
the minibuffer contents have only one completion, minibuffer-complete-word does
not add any characters beyond the first character that is not a word constituent. See
Chapter 35 [Syntax Tables], page 684.
Chapter 20: Minibuffers 290
minibuffer-complete [Command]
This function completes the minibuffer contents as far as possible.
minibuffer-complete-and-exit [Command]
This function completes the minibuffer contents, and exits if confirmation is not
required, i.e., if minibuffer-completion-confirm is nil. If confirmation is required,
it is given by repeating this command immediately—the command is programmed to
work without confirmation when run twice in succession.
minibuffer-completion-help [Command]
This function creates a list of the possible completions of the current minibuffer
contents. It works by calling all-completions using the value of the variable
minibuffer-completion-table as the collection argument, and the value of
minibuffer-completion-predicate as the predicate argument. The list of
completions is displayed as text in a buffer named ‘*Completions*’.
minibuffer-local-completion-map [Variable]
completing-read uses this value as the local keymap when an exact match of one
of the completions is not required. By default, this keymap makes the following
bindings:
? minibuffer-completion-help
SPC minibuffer-complete-word
Chapter 20: Minibuffers 291
TAB minibuffer-complete
with other characters bound as in minibuffer-local-map (see [Definition of
minibuffer-local-map], page 280).
minibuffer-local-must-match-map [Variable]
completing-read uses this value as the local keymap when an exact match of one of
the completions is required. Therefore, no keys are bound to exit-minibuffer, the
command that exits the minibuffer unconditionally. By default, this keymap makes
the following bindings:
? minibuffer-completion-help
SPC minibuffer-complete-word
TAB minibuffer-complete
C-j minibuffer-complete-and-exit
RET minibuffer-complete-and-exit
with other characters bound as in minibuffer-local-map.
minibuffer-local-filename-completion-map [Variable]
This is like minibuffer-local-completion-map except that it does not bind SPC.
This keymap is used by the function read-file-name.
minibuffer-local-must-match-filename-map [Variable]
This is like minibuffer-local-must-match-map except that it does not bind SPC.
This keymap is used by the function read-file-name.
In the following example, the user enters ‘minibuffer.t’, and then types RET. The
argument existing is t, and the only buffer name starting with the given input is
‘minibuffer.texi’, so that name is the value.
(read-buffer "Buffer name: " "foo" t)
;; After evaluation of the preceding expression,
;; the following prompt appears,
;; with an empty minibuffer:
read-buffer-function [Variable]
This variable specifies how to read buffer names. For example, if you set this variable
to iswitchb-read-buffer, all Emacs commands that call read-buffer to read a
buffer name will actually use the iswitchb package to read it.
non-nil, directory is also inserted in the minibuffer as initial input. It defaults to the
current buffer’s value of default-directory.
If you specify initial, that is an initial file name to insert in the buffer (after directory,
if that is inserted). In this case, point goes at the beginning of initial. The default for
initial is nil—don’t insert any file name. To see what initial does, try the command
C-x C-v. Please note: we recommend using default rather than initial in most cases.
If default is non-nil, then the function returns default if the user exits the minibuffer
with the same non-empty contents that read-file-name inserted initially. The initial
minibuffer contents are always non-empty if insert-default-directory is non-nil,
as it is by default. default is not checked for validity, regardless of the value of
existing. However, if existing is non-nil, the initial minibuffer contents should be a
valid file (or directory) name. Otherwise read-file-name attempts completion if the
user exits without any editing, and does not return default. default is also available
through the history commands.
If default is nil, read-file-name tries to find a substitute default to use in its place,
which it treats in exactly the same way as if it had been specified explicitly. If default
is nil, but initial is non-nil, then the default is the absolute file name obtained from
directory and initial. If both default and initial are nil and the buffer is visiting a
file, read-file-name uses the absolute file name of that file as default. If the buffer
is not visiting a file, then there is no default. In that case, if the user types RET
without any editing, read-file-name simply returns the pre-inserted contents of the
minibuffer.
If the user types RET in an empty minibuffer, this function returns an empty string,
regardless of the value of existing. This is, for instance, how the user can make the
current buffer visit no file using M-x set-visited-file-name.
If predicate is non-nil, it specifies a function of one argument that decides which file
names are acceptable completion possibilities. A file name is an acceptable value if
predicate returns non-nil for it.
read-file-name does not automatically expand file names. You must call expand-
file-name yourself if an absolute file name is required.
Here is an example:
(read-file-name "The file is ")
read-file-name-function [Variable]
If non-nil, this should be a function that accepts the same arguments as read-
file-name. When read-file-name is called, it calls this function with the supplied
arguments instead of doing its usual work.
read-file-name-completion-ignore-case [Variable]
If this variable is non-nil, read-file-name ignores case when performing completion.
read-directory-name prompt &optional directory default existing [Function]
initial
This function is like read-file-name but allows only directory names as completion
possibilities.
If default is nil and initial is non-nil, read-directory-name constructs a substitute
default by combining directory (or the current buffer’s default directory if directory
is nil) and initial. If both default and initial are nil, this function uses directory as
substitute default, or the current buffer’s default directory if directory is nil.
insert-default-directory [User Option]
This variable is used by read-file-name, and thus, indirectly, by most commands
reading file names. (This includes all commands that use the code letters ‘f’ or ‘F’ in
their interactive form. See Section 21.2.2 [Code Characters for interactive], page 307.)
Its value controls whether read-file-name starts by placing the name of the default
directory in the minibuffer, plus the initial file name if any. If the value of this variable
is nil, then read-file-name does not place any initial input in the minibuffer (unless
you specify initial input with the initial argument). In that case, the default directory
is still used for completion of relative file names, but is not displayed.
If this variable is nil and the initial minibuffer contents are empty, the user may have
to explicitly fetch the next history element to access a default value. If the variable
is non-nil, the initial minibuffer contents are always non-empty and the user can
always request a default value by immediately typing RET in an unedited minibuffer.
(See above.)
For example:
;; Here the minibuffer starts out with the default directory.
(let ((insert-default-directory t))
(read-file-name "The file is "))
If either of these functions is called in a command that was invoked using the mouse—
more precisely, if last-nonmenu-event (see Section 21.4 [Command Loop Info], page 312)
is either nil or a list—then it uses a dialog box or pop-up menu to ask the question.
Otherwise, it uses keyboard input. You can force use of the mouse or use of keyboard input
by binding last-nonmenu-event to a suitable value around the call.
Strictly speaking, yes-or-no-p uses the minibuffer and y-or-n-p does not; but it seems
best to describe them together.
The optional argument confirm, if non-nil, says to read the password twice and insist
it must be the same both times. If it isn’t the same, the user has to type it over and
over until the last two times match.
The optional argument default specifies the default password to return if the user
enters empty input. If default is nil, then read-passwd returns the null string in
that case.
exit-minibuffer [Command]
This command exits the active minibuffer. It is normally bound to keys in minibuffer
local keymaps.
self-insert-and-exit [Command]
This command exits the active minibuffer after inserting the last character typed on
the keyboard (found in last-command-char; see Section 21.4 [Command Loop Info],
page 312).
previous-history-element n [Command]
This command replaces the minibuffer contents with the value of the nth previous
(older) history element.
next-history-element n [Command]
This command replaces the minibuffer contents with the value of the nth more recent
history element.
active-minibuffer-window [Function]
This function returns the currently active minibuffer window, or nil if none is cur-
rently active.
minibuffer-depth [Function]
This function returns the current depth of activations of the minibuffer, a nonnegative
integer. If no minibuffers are active, it returns zero.
minibuffer-setup-hook [Variable]
This is a normal hook that is run whenever the minibuffer is entered. See Section 23.1
[Hooks], page 382.
minibuffer-exit-hook [Variable]
This is a normal hook that is run whenever the minibuffer is exited. See Section 23.1
[Hooks], page 382.
minibuffer-help-form [Variable]
The current value of this variable is used to rebind help-form locally inside the
minibuffer (see Section 24.5 [Help Functions], page 431).
minibuffer-scroll-window [Variable]
If the value of this variable is non-nil, it should be a window object. When the
function scroll-other-window is called in the minibuffer, it scrolls this window.
minibuffer-selected-window [Function]
This function returns the window which was selected when the minibuffer was entered.
If selected window is not a minibuffer window, it returns nil.
Chapter 20: Minibuffers 303
21 Command Loop
When you run Emacs, it enters the editor command loop almost immediately. This loop
reads key sequences, executes their definitions, and displays the results. In this chapter,
we describe how these things are done, and the subroutines that allow Lisp programs to do
them.
pre-command-hook [Variable]
The editor command loop runs this normal hook before each command. At that
time, this-command contains the command that is about to run, and last-command
describes the previous command. See Section 21.4 [Command Loop Info], page 312.
post-command-hook [Variable]
The editor command loop runs this normal hook after each command (including com-
mands terminated prematurely by quitting or by errors), and also when the command
loop is first entered. At that time, this-command refers to the command that just
ran, and last-command refers to the command before that.
Chapter 21: Command Loop 305
Strings], page 56). For example, here is how you could read the name of an existing
buffer followed by a new name to give to that buffer:
(interactive "bBuffer to rename: \nsRename buffer %s to: ")
If the first character in the string is ‘*’, then an error is signaled if the buffer is read-only.
If the first character in the string is ‘@’, and if the key sequence used to invoke the
command includes any mouse events, then the window associated with the first of
those events is selected before the command is run.
You can use ‘*’ and ‘@’ together; the order does not matter. Actual reading of arguments
is controlled by the rest of the prompt string (starting with the first character that is
not ‘*’ or ‘@’).
• It may be a Lisp expression that is not a string; then it should be a form that is
evaluated to get a list of arguments to pass to the command. Usually this form will
call various functions to read input from the user, most often through the minibuffer
(see Chapter 20 [Minibuffers], page 278) or directly from the keyboard (see Section 21.7
[Reading Input], page 329).
Providing point or the mark as an argument value is also common, but if you do this
and read input (whether using the minibuffer or not), be sure to get the integer values
of point or the mark after reading. The current buffer may be receiving subprocess
output; if subprocess output arrives while the command is waiting for input, it could
relocate point and the mark.
Here’s an example of what not to do:
(interactive
(list (region-beginning) (region-end)
(read-string "Foo: " nil ’my-history)))
Here’s how to avoid the problem, by examining point and the mark after reading the
keyboard input:
(interactive
(let ((string (read-string "Foo: " nil ’my-history)))
(list (region-beginning) (region-end) string)))
Warning: the argument values should not include any data types that can’t be printed
and then read. Some facilities save command-history in a file to be read in the subse-
quent sessions; if a command’s arguments contain a data type that prints using ‘#<...>’
syntax, those facilities won’t work.
There are, however, a few exceptions: it is ok to use a limited set of expressions such as
(point), (mark), (region-beginning), and (region-end), because Emacs recognizes
them specially and puts the expression (rather than its value) into the command history.
To see whether the expression you wrote is one of these exceptions, run the command,
then examine (car command-history).
‘e’ The first or next mouse event in the key sequence that invoked the command.
More precisely, ‘e’ gets events that are lists, so you can look at the data in the
lists. See Section 21.6 [Input Events], page 315. No I/O.
You can use ‘e’ more than once in a single command’s interactive specification.
If the key sequence that invoked the command has n events that are lists, the
nth ‘e’ provides the nth such event. Events that are not lists, such as function
keys and ASCII characters, do not count where ‘e’ is concerned.
‘f’ A file name of an existing file (see Section 25.8 [File Names], page 453). The de-
fault directory is default-directory. Existing, Completion, Default, Prompt.
‘F’ A file name. The file need not exist. Completion, Default, Prompt.
‘G’ A file name. The file need not exist. If the user enters just a directory name,
then the value is just that directory name, with no file name within the directory
added. Completion, Default, Prompt.
‘i’ An irrelevant argument. This code always supplies nil as the argument’s value.
No I/O.
‘k’ A key sequence (see Section 22.1 [Key Sequences], page 347). This keeps reading
events until a command (or undefined command) is found in the current key
maps. The key sequence argument is represented as a string or vector. The
cursor does not move into the echo area. Prompt.
If ‘k’ reads a key sequence that ends with a down-event, it also reads and
discards the following up-event. You can get access to that up-event with the
‘U’ code character.
This kind of input is used by commands such as describe-key and global-
set-key.
‘K’ A key sequence, whose definition you intend to change. This works like ‘k’,
except that it suppresses, for the last input event in the key sequence, the
conversions that are normally used (when necessary) to convert an undefined
key into a defined one.
‘m’ The position of the mark, as an integer. No I/O.
‘M’ Arbitrary text, read in the minibuffer using the current buffer’s input method,
and returned as a string (see section “Input Methods” in The GNU Emacs
Manual). Prompt.
‘n’ A number, read with the minibuffer. If the input is not a number, the user has
to try again. ‘n’ never uses the prefix argument. Prompt.
‘N’ The numeric prefix argument; but if there is no prefix argument, read a number
as with n. The value is always a number. See Section 21.11 [Prefix Command
Arguments], page 340. Prompt.
‘p’ The numeric prefix argument. (Note that this ‘p’ is lower case.) No I/O.
‘P’ The raw prefix argument. (Note that this ‘P’ is upper case.) No I/O.
‘r’ Point and the mark, as two numeric arguments, smallest first. This is the only
code letter that specifies two successive arguments rather than one. No I/O.
Chapter 21: Command Loop 309
‘s’ Arbitrary text, read in the minibuffer and returned as a string (see Section 20.2
[Text from Minibuffer], page 279). Terminate the input with either C-j or RET.
(C-q may be used to include either of these characters in the input.) Prompt.
‘S’ An interned symbol whose name is read in the minibuffer. Any whitespace char-
acter terminates the input. (Use C-q to include whitespace in the string.) Other
characters that normally terminate a symbol (e.g., parentheses and brackets)
do not do so here. Prompt.
‘U’ A key sequence or nil. Can be used after a ‘k’ or ‘K’ argument to get the
up-event that was discarded (if any) after ‘k’ or ‘K’ read a down-event. If no
up-event has been discarded, ‘U’ provides nil as the argument. No I/O.
‘v’ A variable declared to be a user option (i.e., satisfying the predicate user-
variable-p). This reads the variable using read-variable. See [Definition of
read-variable], page 293. Existing, Completion, Prompt.
‘x’ A Lisp object, specified with its read syntax, terminated with a C-j or RET.
The object is not evaluated. See Section 20.3 [Object from Minibuffer],
page 281. Prompt.
‘X’ A Lisp form’s value. ‘X’ reads as ‘x’ does, then evaluates the form so that its
value becomes the argument for the command. Prompt.
‘z’ A coding system name (a symbol). If the user enters null input, the argu-
ment value is nil. See Section 33.10 [Coding Systems], page 648. Completion,
Existing, Prompt.
‘Z’ A coding system name (a symbol)—but only if this command has a prefix
argument. With no prefix argument, ‘Z’ provides nil as the argument value.
Completion, Existing, Prompt.
If record-flag is non-nil, then this command and its arguments are unconditionally
added to the list command-history. Otherwise, the command is added only if it uses
the minibuffer to read an argument. See Section 21.14 [Command History], page 344.
The argument keys, if given, should be a vector which specifies the sequence of events
to supply if the command inquires which events were used to invoke it. If keys is
omitted or nil, the default is the return value of this-command-keys-vector. See
[Definition of this-command-keys-vector], page 314.
interactive-p [Function]
This function returns t if the containing function (the one whose code includes the
call to interactive-p) was called in direct response to user input. This means that
it was called with the function call-interactively, and that a keyboard macro is
not running, and that Emacs is not running in batch mode.
If the containing function was called by Lisp evaluation (or with apply or funcall),
then it was not called interactively.
Chapter 21: Command Loop 312
The most common use of interactive-p is for deciding whether to give the user addi-
tional visual feedback (such as by printing an informative message). For example:
;; Here’s the usual way to use interactive-p.
(defun foo ()
(interactive)
(when (interactive-p)
(message "foo")))
⇒ foo
foobar
⇒ (nil t)
If you want to test only whether the function was called using call-interactively,
add an optional argument print-message which should be non-nil in an interactive call,
and use the interactive spec to make sure it is non-nil. Here’s an example:
(defun foo (&optional print-message)
(interactive "p")
(when print-message
(message "foo")))
Defined in this way, the function does display the message when called from a keyboard
macro. We use "p" because the numeric prefix argument is never nil.
called-interactively-p [Function]
This function returns t when the calling function was called using call-
interactively.
When possible, instead of using this function, you should use the method in the
example above; that method makes it possible for a caller to “pretend” that the
function was called interactively.
last-command [Variable]
This variable records the name of the previous command executed by the command
loop (the one before the current command). Normally the value is a symbol with a
function definition, but this is not guaranteed.
The value is copied from this-command when a command returns to the command
loop, except when the command has specified a prefix argument for the following
command.
This variable is always local to the current terminal and cannot be buffer-local. See
Section 29.2 [Multiple Displays], page 530.
real-last-command [Variable]
This variable is set up by Emacs just like last-command, but never altered by Lisp
programs.
this-command [Variable]
This variable records the name of the command now being executed by the editor
command loop. Like last-command, it is normally a symbol with a function definition.
The command loop sets this variable just before running a command, and copies its
value into last-command when the command finishes (unless the command specified
a prefix argument for the following command).
Some commands set this variable during their execution, as a flag for whatever com-
mand runs next. In particular, the functions for killing text set this-command to
kill-region so that any kill commands immediately following will know to append
the killed text to the previous kill.
If you do not want a particular command to be recognized as the previous command in
the case where it got an error, you must code that command to prevent this. One way is
to set this-command to t at the beginning of the command, and set this-command back to
its proper value at the end, like this:
(defun foo (args...)
(interactive ...)
(let ((old-this-command this-command))
(setq this-command t)
. . . do the work. . .
(setq this-command old-this-command)))
We do not bind this-command with let because that would restore the old value in case
of error—a feature of let which in this case does precisely what we want to avoid.
this-original-command [Variable]
This has the same value as this-command except when command remapping occurs
(see Section 22.13 [Remapping Commands], page 364). In that case, this-command
gives the command actually run (the result of remapping), and this-original-
command gives the command that was specified to run but remapped into another
command.
this-command-keys [Function]
This function returns a string or vector containing the key sequence that invoked the
present command, plus any previous commands that generated the prefix argument
Chapter 21: Command Loop 314
for this command. Any events read by the command using read-event without a
timeout get tacked on to the end.
However, if the command has called read-key-sequence, it returns the last read key
sequence. See Section 21.7.1 [Key Sequence Input], page 330. The value is a string if
all events in the sequence were characters that fit in a string. See Section 21.6 [Input
Events], page 315.
(this-command-keys)
;; Now use C-u C-x C-e to evaluate that.
⇒ "^U^X^E"
this-command-keys-vector [Function]
Like this-command-keys, except that it always returns the events in a vector, so
you don’t need to deal with the complexities of storing input events in a string (see
Section 21.6.14 [Strings of Events], page 328).
last-nonmenu-event [Variable]
This variable holds the last input event read as part of a key sequence, not counting
events resulting from mouse menus.
One use of this variable is for telling x-popup-menu where to pop up a menu. It is
also used internally by y-or-n-p (see Section 20.7 [Yes-or-No Queries], page 296).
last-command-event [Variable]
last-command-char [Variable]
This variable is set to the last input event that was read by the command loop as
part of a command. The principal use of this variable is in self-insert-command,
which uses it to decide which character to insert.
last-command-event
;; Now use C-u C-x C-e to evaluate that.
⇒ 5
The value is 5 because that is the ASCII code for C-e.
The alias last-command-char exists for compatibility with Emacs version 18.
last-event-frame [Variable]
This variable records which frame the last input event was directed to. Usually this
is the frame that was selected when the event was generated, but if that frame has
redirected input focus to another frame, the value is the frame to which the event was
redirected. See Section 29.9 [Input Focus], page 543.
If the last event came from a keyboard macro, the value is macro.
Chapter 21: Command Loop 315
disable-point-adjustment [Variable]
If this variable is non-nil when a command returns to the command loop, then the
command loop does not check for those text properties, and does not move point out
of sequences that have them.
The command loop sets this variable to nil before each command, so if a command
sets it, the effect applies only to that command.
global-disable-point-adjustment [Variable]
If you set this variable to a non-nil value, the feature of moving point out of these
sequences is completely turned off.
But if you type a control combination not in ASCII, such as % with the control
key, the numeric value you get is the code for % plus 226 (assuming the terminal
supports non-ASCII control characters).
shift The 225 bit in the character code indicates an ASCII control character typed
with the shift key held down.
For letters, the basic code itself indicates upper versus lower case; for digits and
punctuation, the shift key selects an entirely different character with a different
basic code. In order to keep within the ASCII character set whenever possible,
Emacs avoids using the 225 bit for those characters.
However, ASCII provides no way to distinguish C-A from C-a, so Emacs uses
the 225 bit in C-A and not in C-a.
hyper The 224 bit in the character code indicates a character typed with the hyper
key held down.
super The 223 bit in the character code indicates a character typed with the super
key held down.
alt The 222 bit in the character code indicates a character typed with the alt key
held down. (On some terminals, the key labeled ALT is actually the meta key.)
It is best to avoid mentioning specific bit numbers in your program. To test the modifier
bits of a character, use the function event-modifiers (see Section 21.6.12 [Classifying
Events], page 324). When making key bindings, you can use the read syntax for characters
with modifier bits (‘\C-’, ‘\M-’, and so on). For making key bindings with define-key,
you can use lists such as (control hyper ?x) to specify the characters (see Section 22.12
[Changing Key Bindings], page 361). The function event-convert-list converts such a
list into an event type (see Section 21.6.12 [Classifying Events], page 324).
applies to tab. Likewise for the other symbols in this group. The function
read-char likewise converts these events into characters.
In ASCII, BS is really C-h. But backspace converts into the character code 127
(DEL), not into code 8 (BS). This is what most users prefer.
left, up, right, down
Cursor arrow keys
kp-add, kp-decimal, kp-divide, . . .
Keypad keys (to the right of the regular keyboard).
kp-0, kp-1, . . .
Keypad keys with digits.
kp-f1, kp-f2, kp-f3, kp-f4
Keypad PF keys.
kp-home, kp-left, kp-up, kp-right, kp-down
Keypad arrow keys. Emacs normally translates these into the corresponding
non-keypad keys home, left, . . .
kp-prior, kp-next, kp-end, kp-begin, kp-insert, kp-delete
Additional keypad duplicates of keys ordinarily found elsewhere. Emacs nor-
mally translates these into the like-named non-keypad keys.
You can use the modifier keys ALT, CTRL, HYPER, META, SHIFT, and SUPER with
function keys. The way to represent them is with prefixes in the symbol name:
‘A-’ The alt modifier.
‘C-’ The control modifier.
‘H-’ The hyper modifier.
‘M-’ The meta modifier.
‘S-’ The shift modifier.
‘s-’ The super modifier.
Thus, the symbol for the key F3 with META held down is M-f3. When you use more
than one prefix, we recommend you write them in alphabetical order; but the order does
not matter in arguments to the key-binding lookup and modification functions.
A key sequence that starts with a mouse event is read using the keymaps of the buffer
in the window that the mouse was in, not the current buffer. This does not imply that
clicking in a window selects that window or its buffer—that is entirely under the control of
the command binding of the key sequence.
string-pos This is the position in the string on which the click occurred, relevant if prop-
erties at the click need to be looked up.
text-pos For clicks on a marginal area or on a fringe, this is the buffer position of the
first visible character in the corresponding line in the window. For other events,
it is the current buffer position in the window.
col, row These are the actual coordinates of the glyph under the x, y position, possibly
padded with default character width glyphs if x is beyond the last glyph on the
line.
image This is the image object on which the click occurred. It is either nil if there
is no image at the position clicked on, or it is an image object as returned by
find-image if click was in an image.
dx, dy These are the pixel-denominated coordinates of the click, relative to the top left
corner of object, which is (0 . 0). If object is nil, the coordinates are relative
to the top left corner of the character glyph clicked on.
For mouse clicks on a scroll-bar, position has this form:
(window area (portion . whole ) timestamp part )
window This is the window whose scroll-bar was clicked on.
area This is the scroll bar where the click occurred. It is one of the symbols
vertical-scroll-bar or horizontal-scroll-bar.
portion This is the distance of the click from the top or left end of the scroll bar.
whole This is the length of the entire scroll bar.
timestamp
This is the time at which the event occurred, in milliseconds.
part This is the part of the scroll-bar which was clicked on. It is one of the sym-
bols above-handle, handle, below-handle, up, down, top, bottom, and end-
scroll.
In one special case, buffer-pos is a list containing a symbol (one of the symbols listed
above) instead of just the symbol. This happens after the imaginary prefix keys for the event
are inserted into the input stream. See Section 21.7.1 [Key Sequence Input], page 330.
For a drag event, the name of the symbol event-type contains the prefix ‘drag-’. For
example, dragging the mouse with button 2 held down generates a drag-mouse-2 event.
The second and third elements of the event give the starting and ending position of the drag.
Aside from that, the data have the same meanings as in a click event (see Section 21.6.4
[Click Events], page 318). You can access the second element of any mouse event in the
same way, with no need to distinguish drag events from others.
The ‘drag-’ prefix follows the modifier key prefixes such as ‘C-’ and ‘M-’.
If read-key-sequence receives a drag event that has no key binding, and the corre-
sponding click event does have a binding, it changes the drag event into a click event at the
drag’s starting position. This means that you don’t have to distinguish between click and
drag events unless you want to.
1
Button-down is the conservative antithesis of drag.
Chapter 21: Command Loop 321
This is convenient, if the meaning of a double click somehow “builds on” the meaning
of a single click—which is recommended user interface design practice for double clicks.
If you click a button, then press it down again and start moving the mouse with the
button held down, then you get a double-drag event when you ultimately release the button.
Its event type contains ‘double-drag’ instead of just ‘drag’. If a double-drag event has no
binding, Emacs looks for an alternate binding as if the event were an ordinary drag.
Before the double-click or double-drag event, Emacs generates a double-down event when
the user presses the button down for the second time. Its event type contains ‘double-down’
instead of just ‘down’. If a double-down event has no binding, Emacs looks for an alternate
binding as if the event were an ordinary button-down event. If it finds no binding that way
either, the double-down event is ignored.
To summarize, when you click a button and then press it again right away, Emacs
generates a down event and a click event for the first click, a double-down event when you
press the button again, and finally either a double-click or a double-drag event.
If you click a button twice and then press it again, all in quick succession, Emacs gener-
ates a triple-down event, followed by either a triple-click or a triple-drag. The event types
of these events contain ‘triple’ instead of ‘double’. If any triple event has no binding,
Emacs uses the binding that it would use for the corresponding double event.
If you click a button three or more times and then press it again, the events for the
presses beyond the third are all triple events. Emacs does not have separate event types
for quadruple, quintuple, etc. events. However, you can look at the event list to find out
precisely how many times the button was pressed.
(wheel-up position )
(wheel-down position )
These kinds of event are generated by moving a mouse wheel. Their usual
meaning is a kind of scroll or zoom.
The element position is a list describing the position of the event, in the same
format as used in a mouse-click event.
This kind of event is generated only on some kinds of systems. On some systems,
mouse-4 and mouse-5 are used instead. For portable code, use the variables
mouse-wheel-up-event and mouse-wheel-down-event defined in ‘mwheel.el’
to determine what event types to expect for the mouse wheel.
(drag-n-drop position files )
This kind of event is generated when a group of files is selected in an application
outside of Emacs, and then dragged and dropped onto an Emacs frame.
The element position is a list describing the position of the event, in the same
format as used in a mouse-click event, and files is the list of file names that
were dragged and dropped. The usual way to handle this event is by visiting
these files.
This kind of event is generated, at present, only on some kinds of systems.
help-echo
This kind of event is generated when a mouse pointer moves onto a portion of
buffer text which has a help-echo text property. The generated event has this
form:
(help-echo frame help window object pos )
The precise meaning of the event parameters and the way these parameters are
used to display the help-echo text are described in [Text help-echo], page 621.
sigusr1
sigusr2 These events are generated when the Emacs process receives the signals SIGUSR1
and SIGUSR2. They contain no additional data because signals do not carry
additional information.
To catch a user signal, bind the corresponding event to an interactive command
in the special-event-map (see Section 22.7 [Active Keymaps], page 353). The
command is called with no arguments, and the specific signal event is available
in last-input-event. For example:
(defun sigusr-handler ()
(interactive)
(message "Caught signal %S" last-input-event))
If one of these events arrives in the middle of a key sequence—that is, after a prefix
key—then Emacs reorders the events so that this event comes either before or after the
multi-event key sequence, not within it.
Chapter 21: Command Loop 324
the current Emacs session, then event-modifiers can return nil, even when event
actually has modifiers.
Here are some examples:
(event-modifiers ?a)
⇒ nil
(event-modifiers ?A)
⇒ (shift)
(event-modifiers ?\C-a)
⇒ (control)
(event-modifiers ?\C-%)
⇒ (control)
(event-modifiers ?\C-\S-a)
⇒ (control shift)
(event-modifiers ’f5)
⇒ nil
(event-modifiers ’s-f5)
⇒ (super)
(event-modifiers ’M-S-f5)
⇒ (meta shift)
(event-modifiers ’mouse-1)
⇒ (click)
(event-modifiers ’down-mouse-1)
⇒ (down)
The modifiers list for a click event explicitly contains click, but the event symbol
name itself does not contain ‘click’.
These functions take a position list as described above, and return various parts of it.
These functions compute a position list given particular buffer position or screen position.
You can access the data in this position list with the functions described above.
posn-at-point &optional pos window [Function]
This function returns a position list for position pos in window. pos defaults to point
in window; window defaults to the selected window.
posn-at-point returns nil if pos is not visible in window.
posn-at-x-y x y &optional frame-or-window whole [Function]
This function returns position information corresponding to pixel coordinates x and
y in a specified frame or window, frame-or-window, which defaults to the selected
window. The coordinates x and y are relative to the frame or window used. If whole
is nil, the coordinates are relative to the window text area, otherwise they are relative
to the entire window area including scroll bars, margins and fringes.
These functions are useful for decoding scroll bar events.
scroll-bar-event-ratio event [Function]
This function returns the fractional vertical position of a scroll bar event within the
scroll bar. The value is a cons cell (portion . whole ) containing two integers whose
ratio is the fractional position.
scroll-bar-scale ratio total [Function]
This function multiplies (in effect) ratio by total, rounding the result to an integer.
The argument ratio is not a number, but rather a pair (num . denom )—typically a
value returned by scroll-bar-event-ratio.
This function is handy for scaling a position on a scroll bar into a buffer position.
Here’s how to do that:
(+ (point-min)
(scroll-bar-scale
(posn-x-y (event-start event))
(- (point-max) (point-min))))
Recall that scroll bar events have two integers forming a ratio, in place of a pair of x
and y coordinates.
• Use vectors to write key sequence constants containing meta characters, even when
passing them directly to define-key.
• When you have to look at the contents of a key sequence that might be a string,
use listify-key-sequence (see Section 21.7.6 [Event Input Misc], page 335) first, to
convert it to a list.
The complexities stem from the modifier bits that keyboard input characters can include.
Aside from the Meta modifier, none of these modifier bits can be included in a string, and
the Meta modifier is allowed only in special cases.
The earliest GNU Emacs versions represented meta characters as codes in the range of
128 to 255. At that time, the basic character codes ranged from 0 to 127, so all keyboard
character codes did fit in a string. Many Lisp programs used ‘\M-’ in string constants to
stand for meta characters, especially in arguments to define-key and similar functions,
and key sequences and sequences of events were always represented as strings.
When we added support for larger basic character codes beyond 127, and additional
modifier bits, we had to change the representation of meta characters. Now the flag that
represents the Meta modifier in a character is 227 and such numbers cannot be included in
a string.
To support programs with ‘\M-’ in string constants, there are special rules for including
certain meta characters in a string. Here are the rules for interpreting a string as a sequence
of input characters:
• If the keyboard character value is in the range of 0 to 127, it can go in the string
unchanged.
• The meta variants of those characters, with codes in the range of 227 to 227 + 127, can
also go in the string, but you must change their numeric values. You must set the 27
bit instead of the 227 bit, resulting in a value between 128 and 255. Only a unibyte
string can include these codes.
• Non-ASCII characters above 256 can be included in a multibyte string.
• Other keyboard character events cannot fit in a string. This includes keyboard events
in the range of 128 to 255.
Functions such as read-key-sequence that construct strings of keyboard input charac-
ters follow these rules: they construct vectors instead of strings, when the events won’t fit
in a string.
When you use the read syntax ‘\M-’ in a string, it produces a code in the range of 128
to 255—the same code that you get if you modify the corresponding keyboard event to put
it in the string. Thus, meta events in strings work consistently regardless of how they get
into the strings.
However, most programs would do well to avoid these issues by following the recommen-
dations at the beginning of this section.
Displays], page 752, and sit-for in Section 21.9 [Waiting], page 337. See Section 39.12
[Terminal Input], page 832, for functions and variables for controlling terminal input modes
and debugging terminal input.
For higher-level input facilities, see Chapter 20 [Minibuffers], page 278.
⇒ "^X^F"
The function read-key-sequence suppresses quitting: C-g typed while reading with
this function works like any other character, and does not set quit-flag. See Sec-
tion 21.10 [Quitting], page 338.
If an input character is upper-case (or has the shift modifier) and has no key binding,
but its lower-case equivalent has one, then read-key-sequence converts the character to
lower case. Note that lookup-key does not perform case conversion in this way.
The function read-key-sequence also transforms some mouse events. It converts un-
bound drag events into click events, and discards unbound button-down events entirely. It
also reshuffles focus events and miscellaneous window events so that they never appear in
a key sequence with any other events.
When mouse events occur in special parts of a window, such as a mode line or a scroll bar,
the event type shows nothing special—it is the same symbol that would normally represent
that combination of mouse button and modifier keys. The information about the window
part is kept elsewhere in the event—in the coordinates. But read-key-sequence translates
this information into imaginary “prefix keys,” all of which are symbols: header-line,
horizontal-scroll-bar, menu-bar, mode-line, vertical-line, and vertical-scroll-
bar. You can define meanings for mouse clicks in special window parts by defining key
sequences using these imaginary prefix keys.
For example, if you call read-key-sequence and then click the mouse on the window’s
mode line, you get two events, like this:
(read-key-sequence "Click on the mode line: ")
⇒ [mode-line
(mouse-1
(#<window 6 on NEWS> mode-line
(40 . 63) 5959987))]
num-input-keys [Variable]
This variable’s value is the number of key sequences processed so far in this Emacs
session. This includes key sequences read from the terminal and key sequences read
from keyboard macros being executed.
(read-char)
⇒ 49
num-nonmacro-input-events [Variable]
This variable holds the total number of input events received so far from the
terminal—not counting those generated by keyboard macros.
extra-keyboard-modifiers [Variable]
This variable lets Lisp programs “press” the modifier keys on the keyboard. The
value is a character. Only the modifiers of the character matter. Each time the user
types a keyboard key, it is altered as if those modifier keys were held down. For
instance, if you bind extra-keyboard-modifiers to ?\C-\M-a, then all keyboard
input characters typed during the scope of the binding will have the control and meta
modifiers applied to them. The character ?\C-@, equivalent to the integer 0, does not
count as a control character for this purpose, but as a character with no modifiers.
Thus, setting extra-keyboard-modifiers to zero cancels any modification.
When using a window system, the program can “press” any of the modifier keys in
this way. Otherwise, only the CTL and META keys can be virtually pressed.
Note that this variable applies only to events that really come from the keyboard,
and has no effect on mouse events or any other events.
keyboard-translate-table [Variable]
This variable is the translate table for keyboard characters. It lets you reshuffle the
keys on the keyboard without changing any command bindings. Its value is normally
a char-table, or else nil. (It can also be a string or vector, but this is considered
obsolete.)
If keyboard-translate-table is a char-table (see Section 6.6 [Char-Tables],
page 93), then each character read from the keyboard is looked up in this char-table.
If the value found there is non-nil, then it is used instead of the actual input
character.
Chapter 21: Command Loop 334
Note that this translation is the first thing that happens to a character after it is read
from the terminal. Record-keeping features such as recent-keys and dribble files
record the characters after translation.
Note also that this translation is done before the characters are supplied to input
methods (see Section 33.11 [Input Methods], page 659). Use translation-table-
for-input (see Section 33.9 [Translation of Characters], page 647), if you want to
translate characters after input methods operate.
Here’s an example of using the keyboard-translate-table to make C-x, C-c and C-v
perform the cut, copy and paste operations:
(keyboard-translate ?\C-x ’control-x)
(keyboard-translate ?\C-c ’control-c)
(keyboard-translate ?\C-v ’control-v)
(global-set-key [control-x] ’kill-region)
(global-set-key [control-c] ’kill-ring-save)
(global-set-key [control-v] ’yank)
On a graphical terminal that supports extended ASCII input, you can still get the standard
Emacs meanings of one of those characters by typing it with the shift key. That makes it
a different character as far as keyboard translation is concerned, but it has the same usual
meaning.
See Section 22.14 [Translation Keymaps], page 365, for mechanisms that translate event
sequences at the level of read-key-sequence.
input-method-function [Variable]
If this is non-nil, its value specifies the current input method function.
Warning: don’t bind this variable with let. It is often buffer-local, and if you bind
it around reading input (which is exactly when you would bind it), switching buffers
asynchronously while Emacs is waiting will cause the value to be restored in the wrong
buffer.
The input method function should return a list of events which should be used as input.
(If the list is nil, that means there is no input, so read-event waits for another event.)
These events are processed before the events in unread-command-events (see Section 21.7.6
[Event Input Misc], page 335). Events returned by the input method function are not passed
to the input method function again, even if they are printing characters with no modifier
bits.
Chapter 21: Command Loop 335
⇒ 127
unread-command-events [Variable]
This variable holds a list of events waiting to be read as command input. The events
are used in the order they appear in the list, and removed one by one as they are
used.
The variable is needed because in some cases a function reads an event and then
decides not to use it. Storing the event in this variable causes it to be processed
normally, by the command loop or by the functions to read command input.
Chapter 21: Command Loop 336
For example, the function that implements numeric prefix arguments reads any num-
ber of digits. When it finds a non-digit event, it must unread the event so that it
can be read normally by the command loop. Likewise, incremental search uses this
feature to unread events with no special meaning in a search, because these events
should exit the search and then execute normally.
The reliable and easy way to extract events from a key sequence so as to put them
in unread-command-events is to use listify-key-sequence (see Section 21.6.14
[Strings of Events], page 328).
Normally you add events to the front of this list, so that the events most recently
unread will be reread first.
Events read from this list are not normally added to the current command’s key
sequence (as returned by e.g. this-command-keys), as the events will already have
been added once as they were read for the first time. An element of the form (t .
event ) forces event to be added to the current command’s key sequence.
listify-key-sequence key [Function]
This function converts the string or vector key to a list of individual events, which
you can put in unread-command-events.
unread-command-char [Variable]
This variable holds a character to be read as command input. A value of -1 means
“empty.”
This variable is mostly obsolete now that you can use unread-command-events in-
stead; it exists only to support programs written for Emacs versions 18 and earlier.
input-pending-p [Function]
This function determines whether any command input is currently available to be
read. It returns immediately, with value t if there is available input, nil otherwise.
On rare occasions it may return t when no input is available.
last-input-event [Variable]
last-input-char [Variable]
This variable records the last terminal input event read, whether as part of a command
or explicitly by a Lisp program.
In the example below, the Lisp program reads the character 1, ASCII code 49. It
becomes the value of last-input-event, while C-e (we assume C-x C-e command is
used to evaluate this expression) remains the value of last-command-event.
(progn (print (read-char))
(print last-command-event)
last-input-event)
a 49
a 5
⇒ 49
The alias last-input-char exists for compatibility with Emacs version 18.
while-no-input body. . . [Macro]
This construct runs the body forms and returns the value of the last one—but only
if no input arrives. If any input arrives during the execution of the body forms, it
Chapter 21: Command Loop 337
aborts them (working much like a quit). The while-no-input form returns nil if
aborted by a real quit, and returns t if aborted by arrival of other input.
If a part of body binds inhibit-quit to non-nil, arrival of input during those parts
won’t cause an abort until the end of that part.
If you want to be able to distinguish all possible values computed by body from both
kinds of abort conditions, write the code like this:
(while-no-input
(list
(progn . body )))
discard-input [Function]
This function discards the contents of the terminal input buffer and cancels any
keyboard macro that might be in the process of definition. It returns nil.
In the following example, the user may type a number of characters right after starting
the evaluation of the form. After the sleep-for finishes sleeping, discard-input
discards any characters typed during the sleep.
(progn (sleep-for 2)
(discard-input))
⇒ nil
is to give the user time to read text that you display. The value is t if sit-for waited
the full time with no input arriving (see Section 21.7.6 [Event Input Misc], page 335).
Otherwise, the value is nil.
The argument seconds need not be an integer. If it is a floating point number, sit-
for waits for a fractional number of seconds. Some systems support only a whole
number of seconds; on these systems, seconds is rounded down.
The expression (sit-for 0) is equivalent to (redisplay), i.e. it requests a redisplay,
without any delay, if there is no pending input. See Section 38.2 [Forcing Redisplay],
page 739.
If nodisp is non-nil, then sit-for does not redisplay, but it still returns as soon as
input is available (or when the timeout elapses).
In batch mode (see Section 39.16 [Batch Mode], page 836), sit-for cannot be in-
terrupted, even by input from the standard input descriptor. It is thus equivalent to
sleep-for, which is described below.
It is also possible to call sit-for with three arguments, as (sit-for seconds mil-
lisec nodisp ), but that is considered obsolete.
sleep-for seconds &optional millisec [Function]
This function simply pauses for seconds seconds without updating the display. It
pays no attention to available input. It returns nil.
The argument seconds need not be an integer. If it is a floating point number, sleep-
for waits for a fractional number of seconds. Some systems support only a whole
number of seconds; on these systems, seconds is rounded down.
The optional argument millisec specifies an additional waiting period measured in
milliseconds. This adds to the period specified by seconds. If the system doesn’t
support waiting fractions of a second, you get an error if you specify nonzero millisec.
Use sleep-for when you wish to guarantee a delay.
See Section 39.5 [Time of Day], page 824, for functions to get the current time.
21.10 Quitting
Typing C-g while a Lisp function is running causes Emacs to quit whatever it is doing. This
means that control returns to the innermost active command loop.
Typing C-g while the command loop is waiting for keyboard input does not cause a quit;
it acts as an ordinary input character. In the simplest case, you cannot tell the difference,
because C-g normally runs the command keyboard-quit, whose effect is to quit. However,
when C-g follows a prefix key, they combine to form an undefined key. The effect is to
cancel the prefix key as well as any prefix argument.
In the minibuffer, C-g has a different definition: it aborts out of the minibuffer. This
means, in effect, that it exits the minibuffer and then quits. (Simply quitting would return
to the command loop within the minibuffer.) The reason why C-g does not quit directly
when the command reader is reading input is so that its meaning can be redefined in the
minibuffer in this way. C-g following a prefix key is not redefined in the minibuffer, and it
has its normal effect of canceling the prefix key and prefix argument. This too would not
be possible if C-g always quit directly.
Chapter 21: Command Loop 339
When C-g does directly quit, it does so by setting the variable quit-flag to t. Emacs
checks this variable at appropriate times and quits if it is not nil. Setting quit-flag
non-nil in any way thus causes a quit.
At the level of C code, quitting cannot happen just anywhere; only at the special places
that check quit-flag. The reason for this is that quitting at other places might leave
an inconsistency in Emacs’s internal state. Because quitting is delayed until a safe place,
quitting cannot make Emacs crash.
Certain functions such as read-key-sequence or read-quoted-char prevent quitting
entirely even though they wait for input. Instead of quitting, C-g serves as the requested
input. In the case of read-key-sequence, this serves to bring about the special behavior
of C-g in the command loop. In the case of read-quoted-char, this is so that C-q can be
used to quote a C-g.
You can prevent quitting for a portion of a Lisp function by binding the variable
inhibit-quit to a non-nil value. Then, although C-g still sets quit-flag to t as usual,
the usual result of this—a quit—is prevented. Eventually, inhibit-quit will become nil
again, such as when its binding is unwound at the end of a let form. At that time, if
quit-flag is still non-nil, the requested quit happens immediately. This behavior is ideal
when you wish to make sure that quitting does not happen within a “critical section” of
the program.
In some functions (such as read-quoted-char), C-g is handled in a special way that
does not involve quitting. This is done by reading the input with inhibit-quit bound to
t, and setting quit-flag to nil before inhibit-quit becomes nil again. This excerpt
from the definition of read-quoted-char shows how this is done; it also shows that normal
quitting is permitted after the first character of input.
(defun read-quoted-char (&optional prompt)
"...documentation ..."
(let ((message-log-max nil) done (first t) (code 0) char)
(while (not done)
(let ((inhibit-quit first)
...)
(and prompt (message "%s-" prompt))
(setq char (read-event))
(if inhibit-quit (setq quit-flag nil)))
. . . set the variable code. . . )
code))
quit-flag [Variable]
If this variable is non-nil, then Emacs quits immediately, unless inhibit-quit is
non-nil. Typing C-g ordinarily sets quit-flag non-nil, regardless of inhibit-quit.
inhibit-quit [Variable]
This variable determines whether Emacs should quit when quit-flag is set to a value
other than nil. If inhibit-quit is non-nil, then quit-flag has no special effect.
Chapter 21: Command Loop 340
Here are the results of calling display-prefix with various raw prefix arguments:
M-x display-prefix a nil
universal-argument [Command]
This command reads input and specifies a prefix argument for the following command.
Don’t call this command yourself unless you know what you are doing.
the user different text to edit “recursively,” create and select a new buffer in a special mode.
In this mode, define a command to complete the processing and go back to the previous
buffer. (The m command in Rmail does this.)
Recursive edits are useful in debugging. You can insert a call to debug into a function
definition as a sort of breakpoint, so that you can look around when the function gets there.
debug invokes a recursive edit but also provides the other features of the debugger.
Recursive editing levels are also used when you type C-r in query-replace or use C-x
q (kbd-macro-query).
recursive-edit [Function]
This function invokes the editor command loop. It is called automatically by the ini-
tialization of Emacs, to let the user begin editing. When called from a Lisp program,
it enters a recursive editing level.
If the current buffer is not the same as the selected window’s buffer, recursive-edit
saves and restores the current buffer. Otherwise, if you switch buffers, the buffer you
switched to is current after recursive-edit returns.
In the following example, the function simple-rec first advances point one word,
then enters a recursive edit, printing out a message in the echo area. The user can
then do any editing desired, and then type C-M-c to exit and continue executing
simple-rec.
(defun simple-rec ()
(forward-word 1)
(message "Recursive edit in progress")
(recursive-edit)
(forward-word 1))
⇒ simple-rec
(simple-rec)
⇒ nil
exit-recursive-edit [Command]
This function exits from the innermost recursive edit (including minibuffer input).
Its definition is effectively (throw ’exit nil).
abort-recursive-edit [Command]
This function aborts the command that requested the innermost recursive edit (includ-
ing minibuffer input), by signaling quit after exiting the recursive edit. Its definition
is effectively (throw ’exit t). See Section 21.10 [Quitting], page 338.
top-level [Command]
This function exits all recursive editing levels; it does not return a value, as it jumps
completely out of any computation directly back to the main command loop.
recursion-depth [Function]
This function returns the current depth of recursive edits. When no recursive edit is
active, it returns 0.
Chapter 21: Command Loop 344
editing session, but when it reaches the maximum size (see Section 20.4 [Minibuffer
History], page 282), the oldest elements are deleted as new ones are added.
command-history
⇒ ((switch-to-buffer "chistory.texi")
(describe-key "^X^[")
(visit-tags-table "~/emacs/src/")
(find-tag "repeat-complex-command"))
This history list is actually a special case of minibuffer history (see Section 20.4 [Mini-
buffer History], page 282), with one special twist: the elements are expressions rather than
strings.
There are a number of commands devoted to the editing and recall of previous com-
mands. The commands repeat-complex-command, and list-command-history are de-
scribed in the user manual (see section “Repetition” in The GNU Emacs Manual). Within
the minibuffer, the usual minibuffer history commands are available.
executing-kbd-macro [Variable]
This variable contains the string or vector that defines the keyboard macro that is
currently executing. It is nil if no macro is currently executing. A command can
test this variable so as to behave differently when run from an executing macro. Do
not set this variable yourself.
Chapter 21: Command Loop 346
defining-kbd-macro [Variable]
This variable is non-nil if and only if a keyboard macro is being defined. A command
can test this variable so as to behave differently while a macro is being defined. The
value is append while appending to the definition of an existing macro. The commands
start-kbd-macro, kmacro-start-macro and end-kbd-macro set this variable—do
not set it yourself.
The variable is always local to the current terminal and cannot be buffer-local. See
Section 29.2 [Multiple Displays], page 530.
last-kbd-macro [Variable]
This variable is the definition of the most recently defined keyboard macro. Its value
is a string or vector, or nil.
The variable is always local to the current terminal and cannot be buffer-local. See
Section 29.2 [Multiple Displays], page 530.
kbd-macro-termination-hook [Variable]
This normal hook (see Appendix I [Standard Hooks], page 903) is run when a keyboard
macro terminates, regardless of what caused it to terminate (reaching the macro end
or an error which ended the macro prematurely).
Chapter 22: Keymaps 347
22 Keymaps
The command bindings of input events are recorded in data structures called keymaps.
Each entry in a keymap associates (or binds) an individual event type, either to another
keymap or to a command. When an event type is bound to a keymap, that keymap is
used to look up the next input event; this continues until a command is found. The whole
process is called key lookup.
(type . binding )
This specifies one binding, for events of type type. Each ordinary binding
applies to events of a particular event type, which is always a character or a
symbol. See Section 21.6.12 [Classifying Events], page 324. In this kind of
binding, binding is a command.
Chapter 22: Keymaps 349
(27 keymap
;; M-C-x, treated as ESC C-x
(24 . lisp-send-defun)
keymap
;; M-C-q, treated as ESC C-q
(17 . indent-sexp))
;; This part is inherited from lisp-mode-shared-map.
keymap
;; DEL
(127 . backward-delete-char-untabify)
(27 keymap
;; M-C-q, treated as ESC C-q
(17 . indent-sexp))
(9 . lisp-indent-line))
keymapp object [Function]
This function returns t if object is a keymap, nil otherwise. More precisely, this
function tests for a list whose car is keymap, or for a symbol whose function definition
satisfies keymapp.
(keymapp ’(keymap))
⇒ t
(fset ’foo ’(keymap))
(keymapp ’foo)
⇒ t
(keymapp (current-global-map))
⇒ t
bind any other kind of event. The argument prompt specifies a prompt string, as in
make-sparse-keymap.
(make-keymap)
⇒ (keymap #^[t nil nil nil ... nil nil keymap])
A full keymap is more efficient than a sparse keymap when it holds lots of bindings;
for just a few, the sparse keymap is better.
copy-keymap keymap [Function]
This function returns a copy of keymap. Any keymaps that appear directly as bindings
in keymap are also copied recursively, and so on to any number of levels. However,
recursive copying does not take place when the definition of a character is a symbol
whose function definition is a keymap; the same symbol appears in the new copy.
(setq map (copy-keymap (current-local-map)))
⇒ (keymap
;; (This implements meta characters.)
(27 keymap
(83 . center-paragraph)
(115 . center-line))
(9 . tab-to-tab-stop))
If keymap has submaps (bindings for prefix keys), they too receive new parent
keymaps that reflect what parent specifies for those prefix keys.
Here is an example showing how to make a keymap that inherits from text-mode-map:
(let ((map (make-sparse-keymap)))
(set-keymap-parent map text-mode-map)
map)
A non-sparse keymap can have a parent too, but this is not very useful. A non-sparse
keymap always specifies something as the binding for every numeric character code without
modifier bits, even if it is nil, so these character’s bindings are never inherited from the
parent keymap.
Major and minor modes can redefine a key as a prefix by putting a prefix key definition for
it in the local map or the minor mode’s map. See Section 22.7 [Active Keymaps], page 353.
If a key is defined as a prefix in more than one active map, then its various definitions
are in effect merged: the commands defined in the minor mode keymaps come first, followed
by those in the local map’s prefix definition, and then by those from the global map.
In the following example, we make C-p a prefix key in the local keymap, in such a way
that C-p is identical to C-x. Then the binding for C-p C-f is the function find-file, just
like C-x C-f. The key sequence C-p 6 is not found in any active keymap.
(use-local-map (make-sparse-keymap))
⇒ nil
(local-set-key "\C-p" ctl-x-map)
⇒ nil
(key-binding "\C-p\C-f")
⇒ find-file
(key-binding "\C-p6")
⇒ nil
Each buffer may have another keymap, its local keymap, which may contain new or
overriding definitions for keys. The current buffer’s local keymap is always active except
when overriding-local-map overrides it. The local-map text or overlay property can
specify an alternative local keymap for certain parts of the buffer; see Section 32.19.4
[Special Properties], page 620.
Each minor mode can have a keymap; if it does, the keymap is active when the minor
mode is enabled. Modes for emulation can specify additional active keymaps through the
variable emulation-mode-map-alists.
The highest precedence normal keymap comes from the keymap text or overlay property.
If that is non-nil, it is the first keymap to be processed, in normal circumstances.
However, there are also special ways for programs to substitute other keymaps for some
of those. The variable overriding-local-map, if non-nil, specifies a keymap that replaces
all the usual active keymaps except the global keymap. Another way to do this is with
overriding-terminal-local-map; it operates on a per-terminal basis. These variables are
documented below.
Since every buffer that uses the same major mode normally uses the same local keymap,
you can think of the keymap as local to the mode. A change to the local keymap of a
buffer (using local-set-key, for example) is seen also in the other buffers that share that
keymap.
The local keymaps that are used for Lisp mode and some other major modes exist even
if they have not yet been used. These local keymaps are the values of variables such as
lisp-mode-map. For most major modes, which are less frequently used, the local keymap
is constructed only when the mode is used for the first time in a session.
The minibuffer has local keymaps, too; they contain various completion and exit com-
mands. See Section 20.1 [Intro to Minibuffers], page 278.
Emacs has other keymaps that are used in a different way—translating events within
read-key-sequence. See Section 22.14 [Translation Keymaps], page 365.
See Appendix H [Standard Keymaps], page 899, for a list of standard keymaps.
If key starts with a mouse event (perhaps following a prefix event), the maps to
be consulted are determined based on the event’s position. Otherwise, they are de-
termined based on the value of point. However, you can override either of them
by specifying position. If position is non-nil, it should be either a buffer position
or an event position like the value of event-start. Then the maps consulted are
determined based on position.
An error is signaled if key is not a string or a vector.
(key-binding "\C-x\C-f")
⇒ find-file
current-global-map [Function]
This function returns the current global keymap. This is the same as the value of
global-map unless you change one or the other.
(current-global-map)
⇒ (keymap [set-mark-command beginning-of-line ...
delete-backward-char])
current-local-map [Function]
This function returns the current buffer’s local keymap, or nil if it has none. In
the following example, the keymap for the ‘*scratch*’ buffer (using Lisp Interaction
mode) is a sparse keymap in which the entry for ESC, ASCII code 27, is another
sparse keymap.
(current-local-map)
⇒ (keymap
(10 . eval-print-last-sexp)
(9 . lisp-indent-line)
(127 . backward-delete-char-untabify)
(27 keymap
(24 . eval-defun)
(17 . indent-sexp)))
current-minor-mode-maps [Function]
This function returns a list of the keymaps of currently enabled minor modes.
minor-mode-map-alist [Variable]
This variable is an alist describing keymaps that may or may not be active according
to the values of certain variables. Its elements look like this:
(variable . keymap )
Chapter 22: Keymaps 357
The keymap keymap is active whenever variable has a non-nil value. Typically
variable is the variable that enables or disables a minor mode. See Section 23.3.2
[Keymaps and Minor Modes], page 399.
Note that elements of minor-mode-map-alist do not have the same structure as
elements of minor-mode-alist. The map must be the cdr of the element; a list with
the map as the second element will not do. The cdr can be either a keymap (a list)
or a symbol whose function definition is a keymap.
When more than one minor mode keymap is active, the earlier one in minor-mode-
map-alist takes priority. But you should design minor modes so that they don’t
interfere with each other. If you do this properly, the order will not matter.
See Section 23.3.2 [Keymaps and Minor Modes], page 399, for more information about
minor modes. See also minor-mode-key-binding (see Section 22.11 [Functions for
Key Lookup], page 360).
minor-mode-overriding-map-alist [Variable]
This variable allows major modes to override the key bindings for particular minor
modes. The elements of this alist look like the elements of minor-mode-map-alist:
(variable . keymap ).
If a variable appears as an element of minor-mode-overriding-map-alist, the map
specified by that element totally replaces any map specified for the same variable in
minor-mode-map-alist.
minor-mode-overriding-map-alist is automatically buffer-local in all buffers.
overriding-local-map [Variable]
If non-nil, this variable holds a keymap to use instead of the buffer’s local keymap,
any text property or overlay keymaps, and any minor mode keymaps. This keymap, if
specified, overrides all other maps that would have been active, except for the current
global map.
overriding-terminal-local-map [Variable]
If non-nil, this variable holds a keymap to use instead of overriding-local-map,
the buffer’s local keymap, text property or overlay keymaps, and all the minor mode
keymaps.
This variable is always local to the current terminal and cannot be buffer-local. See
Section 29.2 [Multiple Displays], page 530. It is used to implement incremental search
mode.
overriding-local-map-menu-flag [Variable]
If this variable is non-nil, the value of overriding-local-map or overriding-
terminal-local-map can affect the display of the menu bar. The default value is
nil, so those map variables have no effect on the menu bar.
Note that these two map variables do affect the execution of key sequences entered
using the menu bar, even if they do not affect the menu bar display. So if a menu
bar key sequence comes in, you should clear the variables before looking up and
executing that key sequence. Modes that use the variables would typically do this
anyway; normally they respond to events that they do not handle by “unreading”
them and exiting.
Chapter 22: Keymaps 358
special-event-map [Variable]
This variable holds a keymap for special events. If an event type has a binding in this
keymap, then it is special, and the binding for the event is run directly by read-event.
See Section 21.8 [Special Events], page 337.
emulation-mode-map-alists [Variable]
This variable holds a list of keymap alists to use for emulations modes. It is intended
for modes or packages using multiple minor-mode keymaps. Each element is a keymap
alist which has the same format and meaning as minor-mode-map-alist, or a symbol
with a variable binding which is such an alist. The “active” keymaps in each alist are
used before minor-mode-map-alist and minor-mode-overriding-map-alist.
• If the car of list is the symbol keymap, then the list is a keymap, and is
treated as a keymap (see above).
• If the car of list is lambda, then the list is a lambda expression. This is
presumed to be a function, and is treated as such (see above). In order
to execute properly as a key binding, this function must be a command—
it must have an interactive specification. See Section 21.2 [Defining
Commands], page 305.
• If the car of list is a keymap and the cdr is an event type, then this is an
indirect entry:
(othermap . othertype )
When key lookup encounters an indirect entry, it looks up instead the
binding of othertype in othermap and uses that.
This feature permits you to define one key as an alias for another key. For
example, an entry whose car is the keymap called esc-map and whose
cdr is 32 (the code for SPC) means, “Use the global binding of Meta-SPC,
whatever that may be.”
symbol The function definition of symbol is used in place of symbol. If that too is a
symbol, then this process is repeated, any number of times. Ultimately this
should lead to an object that is a keymap, a command, or a keyboard macro.
A list is allowed if it is a keymap or a command, but indirect entries are not
understood when found via symbols.
Note that keymaps and keyboard macros (strings and vectors) are not valid
functions, so a symbol with a keymap, string, or vector as its function definition
is invalid as a function. It is, however, valid as a key binding. If the definition
is a keyboard macro, then the symbol is also valid as an argument to command-
execute (see Section 21.3 [Interactive Call], page 310).
The symbol undefined is worth special mention: it means to treat the key as
undefined. Strictly speaking, the key is defined, and its binding is the command
undefined; but that command does the same thing that is done automatically
for an undefined key: it rings the bell (by calling ding) but does not signal an
error.
undefined is used in local keymaps to override a global key binding and make
the key “undefined” locally. A local binding of nil would fail to do this because
it would not override the global binding.
anything else
If any other type of object is found, the events used so far in the lookup form
a complete key, and the object is its binding, but the binding is not executable
as a command.
In short, a keymap entry may be a keymap, a command, a keyboard macro, a symbol
that leads to one of them, or an indirection or nil. Here is an example of a sparse keymap
with two characters bound to commands and one bound to another keymap. This map is
the normal value of emacs-lisp-mode-map. Note that 9 is the code for TAB, 127 for DEL,
27 for ESC, 17 for C-q and 24 for C-x.
Chapter 22: Keymaps 360
(keymap (9 . lisp-indent-line)
(127 . backward-delete-char-untabify)
(27 keymap (17 . indent-sexp) (24 . eval-defun)))
meta-prefix-char [Variable]
This variable is the meta-prefix character code. It is used for translating a meta
character to a two-character sequence so it can be looked up in a keymap. For useful
results, the value should be a prefix event (see Section 22.6 [Prefix Keys], page 352).
The default value is 27, which is the ASCII code for ESC.
As long as the value of meta-prefix-char remains 27, key lookup translates M-b into
ESC b, which is normally defined as the backward-word command. However, if you
were to set meta-prefix-char to 24, the code for C-x, then Emacs will translate
M-b into C-x b, whose standard binding is the switch-to-buffer command. (Don’t
actually do this!) Here is an illustration of what would happen:
meta-prefix-char ; The default value.
⇒ 27
(key-binding "\M-b")
⇒ backward-word
?\C-x ; The print representation
⇒ 24 ; of a character.
(setq meta-prefix-char 24)
⇒ 24
(key-binding "\M-b")
⇒ switch-to-buffer ; Now, typing M-b is
; like typing C-x b.
in buffers that shadow the global binding with a local one). If you change the current
buffer’s local map, that usually affects all buffers using the same major mode. The global-
set-key and local-set-key functions are convenient interfaces for these operations (see
Section 22.15 [Key Binding Commands], page 367). You can also use define-key, a more
general function; then you must specify explicitly the map to change.
When choosing the key sequences for Lisp programs to rebind, please follow the Emacs
conventions for use of various keys (see Section D.2 [Key Binding Conventions], page 859).
In writing the key sequence to rebind, it is good to use the special escape sequences for
control and meta characters (see Section 2.3.8 [String Type], page 18). The syntax ‘\C-’
means that the following character is a control character and ‘\M-’ means that the following
character is a meta character. Thus, the string "\M-x" is read as containing a single M-x,
"\C-f" is read as containing a single C-f, and "\M-\C-x" and "\C-\M-x" are both read
as containing a single C-M-x. You can also use this escape syntax in vectors, as well as
others that aren’t allowed in strings; one example is ‘[?\C-\H-x home]’. See Section 2.3.3
[Character Type], page 10.
The key definition and lookup functions accept an alternate syntax for event types in
a key sequence that is a vector: you can use a list containing modifier names plus one
base event (a character or function key name). For example, (control ?a) is equivalent to
?\C-a and (hyper control left) is equivalent to C-H-left. One advantage of such lists
is that the precise numeric codes for the modifier bits don’t appear in compiled files.
The functions below signal an error if keymap is not a keymap, or if key is not a string
or vector representing a key sequence. You can use event types (symbols) as shorthand
for events that are lists. The kbd macro (see Section 22.1 [Key Sequences], page 347) is a
convenient way to specify the key sequence.
This example creates a sparse keymap and makes a number of bindings in it:
(setq map (make-sparse-keymap))
⇒ (keymap)
(define-key map "\C-f" ’forward-char)
⇒ forward-char
Chapter 22: Keymaps 363
map
⇒ (keymap (6 . forward-char))
Here’s an example. Suppose that My mode uses special commands my-kill-line and
my-kill-word, which should be invoked instead of kill-line and kill-word. It can
establish this by making these two command-remapping bindings in its keymap:
(define-key my-mode-map [remap kill-line] ’my-kill-line)
(define-key my-mode-map [remap kill-word] ’my-kill-word)
Whenever my-mode-map is an active keymap, if the user types C-k, Emacs will find the
standard global binding of kill-line (assuming nobody has changed it). But my-mode-
map remaps kill-line to my-kill-line, so instead of running kill-line, Emacs runs
my-kill-line.
Remapping only works through a single level. In other words,
(define-key my-mode-map [remap kill-line] ’my-kill-line)
(define-key my-mode-map [remap my-kill-line] ’my-other-kill-line)
does not have the effect of remapping kill-line into my-other-kill-line. If an ordinary
key binding specifies kill-line, this keymap will remap it to my-kill-line; if an ordinary
binding specifies my-kill-line, this keymap will remap it to my-other-kill-line.
command-remapping command &optional position keymaps [Function]
This function returns the remapping for command (a symbol), given the current
active keymaps. If command is not remapped (which is the usual situation), or not a
symbol, the function returns nil. position can optionally specify a buffer position
or an event position to determine the keymaps to use, as in key-binding.
If the optional argument keymaps is non-nil, it specifies a list of keymaps to search
in. This argument is ignored if position is non-nil.
that function keys send should not have command bindings in their own right—but
if they do, the ordinary bindings take priority.
The value of function-key-map is usually set up automatically according to the
terminal’s Terminfo or Termcap entry, but sometimes those need help from terminal-
specific Lisp files. Emacs comes with terminal-specific files for many common termi-
nals; their main purpose is to make entries in function-key-map beyond those that
can be deduced from Termcap and Terminfo. See Section 39.1.3 [Terminal-Specific],
page 814.
key-translation-map [Variable]
This variable is another keymap used just like function-key-map to translate input
events into other events. It differs from function-key-map in two ways:
• key-translation-map goes to work after function-key-map is finished; it re-
ceives the results of translation by function-key-map.
• Non-prefix bindings in key-translation-map override actual key bindings. For
example, if C-x f has a non-prefix binding in key-translation-map, that trans-
lation takes effect even though C-x f also has a key binding in the global map.
Note however that actual key bindings can have an effect on key-translation-map,
even though they are overridden by it. Indeed, actual key bindings override function-
key-map and thus may alter the key sequence that key-translation-map receives.
Clearly, it is better to avoid this type of situation.
The intent of key-translation-map is for users to map one character set to another,
including ordinary characters normally bound to self-insert-command.
You can use function-key-map or key-translation-map for more than simple aliases,
by using a function, instead of a key sequence, as the “translation” of a key. Then this
function is called to compute the translation of that key.
The key translation function receives one argument, which is the prompt that was speci-
fied in read-key-sequence—or nil if the key sequence is being read by the editor command
loop. In most cases you can ignore the prompt value.
If the function reads input itself, it can have the effect of altering the event that follows.
For example, here’s how to define C-c h to turn the character that follows into a Hyper
character:
(defun hyperify (prompt)
(let ((e (read-event)))
(vector (if (numberp e)
(logior (lsh 1 24) e)
(if (memq ’hyper (event-modifiers e))
e
(add-event-modifier "H-" e))))))
(if (symbolp e)
symbol
(cons symbol (cdr e)))))
("^[" keymap
(83 . center-paragraph)
(115 . foo)))
In the following example, C-h is a prefix key that uses a sparse keymap starting with
(keymap (118 . describe-variable)...). Another prefix, C-x 4, uses a keymap
which is also the value of the variable ctl-x-4-map. The event mode-line is one of
several dummy events used as prefixes for mouse actions in special parts of a window.
(accessible-keymaps (current-global-map))
⇒ (([] keymap [set-mark-command beginning-of-line ...
delete-backward-char])
("^H" keymap (118 . describe-variable) ...
(8 . help-for-help))
("^X" keymap [x-flush-mouse-queue ...
backward-kill-sentence])
("^[" keymap [mark-sexp backward-sexp ...
backward-kill-word])
("^X4" keymap (15 . display-buffer) ...)
([mode-line] keymap
(S-mouse-2 . mouse-split-window-horizontally) ...))
These are not all the keymaps you would see in actuality.
command], page 353). If you do not want the keymap to operate as a menu, don’t specify
a prompt string for it.
keymap-prompt keymap [Function]
This function returns the overall prompt string of keymap, or nil if it has none.
The menu’s items are the bindings in the keymap. Each binding associates an event type
to a definition, but the event types have no significance for the menu appearance. (Usually
we use pseudo-events, symbols that the keyboard cannot generate, as the event types for
menu item bindings.) The menu is generated entirely from the bindings that correspond in
the keymap to these events.
The order of items in the menu is the same as the order of bindings in the keymap. Since
define-key puts new bindings at the front, you should define the menu items starting at the
bottom of the menu and moving to the top, if you care about the order. When you add an
item to an existing menu, you can specify its position in the menu using define-key-after
(see Section 22.17.7 [Modifying Menus], page 381).
You’ve probably noticed that menu items show the equivalent keyboard key sequence (if
any) to invoke the same command. To save time on recalculation, menu display caches this
information in a sublist in the binding, like this:
(item-string [help ] (key-binding-data ) . real-binding )
Don’t put these sublists in the menu item yourself; menu display calculates them automat-
ically. Don’t mention keyboard equivalents in the item strings themselves, since that is
redundant.
should be a form; the result of evaluating it says whether this button is currently
selected.
A toggle is a menu item which is labeled as either “on” or “off” according to
the value of selected. The command itself should toggle selected, setting it to
t if it is nil, and to nil if it is t. Here is how the menu item to toggle the
debug-on-error flag is defined:
(menu-item "Debug on Error" toggle-debug-on-error
:button (:toggle
. (and (boundp ’debug-on-error)
debug-on-error)))
This works because toggle-debug-on-error is defined as a command which
toggles the variable debug-on-error.
Radio buttons are a group of menu items, in which at any time one and only
one is “selected.” There should be a variable whose value says which one is
selected at any time. The selected form for each radio button in the group
should check whether the variable has the right value for selecting that button.
Clicking on the button should set the variable so that the button you clicked
on becomes selected.
:key-sequence key-sequence
This property specifies which key sequence is likely to be bound to the same
command invoked by this menu item. If you specify the right key sequence,
that makes preparing the menu for display run much faster.
If you specify the wrong key sequence, it has no effect; before Emacs displays
key-sequence in the menu, it verifies that key-sequence is really equivalent to
this menu item.
:key-sequence nil
This property indicates that there is normally no key binding which is equivalent
to this menu item. Using this property saves time in preparing the menu for
display, because Emacs does not need to search the keymaps for a keyboard
equivalent for this menu item.
However, if the user has rebound this item’s definition to a key sequence, Emacs
ignores the :keys property and finds the keyboard equivalent anyway.
:keys string
This property specifies that string is the string to display as the keyboard equiv-
alent for this menu item. You can use the ‘\\[...]’ documentation construct
in string.
:filter filter-fn
This property provides a way to compute the menu item dynamically. The
property value filter-fn should be a function of one argument; when it is called,
its argument will be real-binding. The function should return the binding to
use instead.
Emacs can call this function at any time that it does redisplay or operates on
menu data structures, so you should write it so it can safely be called at any
time.
Chapter 22: Keymaps 374
You can also give these names in another style, adding a colon after the double-dash
and replacing each single dash with capitalization of the following word. Thus,
"--:singleLine", is equivalent to "--single-line".
Some systems and display toolkits don’t really handle all of these separator types. If
you use a type that isn’t supported, the menu displays a similar kind of separator that is
supported.
X toolkit menus don’t have panes; instead, they can have submenus. Every nested
keymap becomes a submenu, whether the item string starts with ‘@’ or not. In a toolkit
version of Emacs, the only thing special about ‘@’ at the beginning of an item string is that
the ‘@’ doesn’t appear in the menu item.
Multiple keymaps that define the same menu prefix key produce separate panes or sep-
arate submenus.
menu-prompt-more-char [Variable]
This variable specifies the character to use to ask to see the next line of a menu. Its
initial value is 32, the code for SPC.
The menu in this example is intended for use with the mouse. If a menu is intended
for use with the keyboard, that is, if it is bound to a key sequence ending with a keyboard
event, then the menu items should be bound to characters or “real” function keys, that can
be typed with the keyboard.
The binding whose definition is ("--") is a separator line. Like a real menu item, the
separator has a key symbol, in this case separator-replace-tags. If one menu has two
separators, they must have two different key symbols.
Here is how we make this menu appear as an item in the parent menu:
(define-key menu-bar-edit-menu [replace]
(list ’menu-item "Replace" menu-bar-replace-menu))
Note that this incorporates the submenu keymap, which is the value of the variable menu-
bar-replace-menu, rather than the symbol menu-bar-replace-menu itself. Using that
symbol in the parent menu item would be meaningless because menu-bar-replace-menu is
not a command.
If you wanted to attach the same replace menu to a mouse click, you can do it this way:
(define-key global-map [C-S-down-mouse-1]
menu-bar-replace-menu)
The usual menu keymap item properties, :visible, :enable, :button, and :filter,
are useful in tool bar bindings and have their normal meanings. The real-binding in the
item must be a command, not a keymap; in other words, it does not work to define a tool
bar icon as a prefix key.
The :help property specifies a “help-echo” string to display while the mouse is on that
item. This is displayed in the same way as help-echo text properties (see [Help display],
page 624).
In addition, you should use the :image property; this is how you specify the image to
display in the tool bar:
:image image
images is either a single image specification or a vector of four image specifica-
tions. If you use a vector of four, one of them is used, depending on circum-
stances:
item 0 Used when the item is enabled and selected.
item 1 Used when the item is enabled and deselected.
item 2 Used when the item is disabled and selected.
item 3 Used when the item is disabled and deselected.
If image is a single image specification, Emacs draws the tool bar button in disabled
state by applying an edge-detection algorithm to the image.
The default tool bar is defined so that items specific to editing do not appear for major
modes whose command symbol has a mode-class property of special (see Section 23.2.2
[Major Mode Conventions], page 385). Major modes may add items to the global bar by
binding [tool-bar foo ] in their local map. It makes sense for some major modes to replace
the default tool bar items completely, since not many can be accommodated conveniently,
and the default bindings make this easy by using an indirection through tool-bar-map.
tool-bar-map [Variable]
By default, the global map binds [tool-bar] as follows:
(global-set-key [tool-bar]
’(menu-item "tool bar" ignore
:filter (lambda (ignore) tool-bar-map)))
Thus the tool bar map is derived dynamically from the value of variable tool-bar-
map and you should normally adjust the default (global) tool bar by changing that
map. Major modes may replace the global bar completely by making tool-bar-map
buffer-local and set to a keymap containing only the desired items. Info mode provides
an example.
There are two convenience functions for defining tool bar items, as follows.
display, the search order is ‘.pbm’, ‘.xbm’ and ‘.xpm’. The binding to use is the
command def, and key is the fake function key symbol in the prefix keymap. The
remaining arguments props are additional property list elements to add to the menu
item specification.
To define items in some local map, bind tool-bar-map with let around calls of this
function:
(defvar foo-tool-bar-map
(let ((tool-bar-map (make-sparse-keymap)))
(tool-bar-add-item ...)
...
tool-bar-map))
auto-resize-tool-bar [Variable]
If this variable is non-nil, the tool bar automatically resizes to show all defined tool
bar items—but not larger than a quarter of the frame’s height.
If the value is grow-only, the tool bar expands automatically, but does not contract
automatically. To contract the tool bar, the user has to redraw the frame by entering
C-l.
auto-raise-tool-bar-buttons [Variable]
If this variable is non-nil, tool bar items display in raised form when the mouse
moves over them.
tool-bar-button-margin [Variable]
This variable specifies an extra margin to add around tool bar items. The value is an
integer, a number of pixels. The default is 4.
tool-bar-button-relief [Variable]
This variable specifies the shadow width for tool bar items. The value is an integer,
a number of pixels. The default is 1.
Chapter 22: Keymaps 381
tool-bar-border [Variable]
This variable specifies the height of the border drawn below the tool bar area. An
integer value specifies height as a number of pixels. If the value is one of internal-
border-width (the default) or border-width, the tool bar border height corresponds
to the corresponding frame parameter.
You can define a special meaning for clicking on a tool bar item with the shift, control,
meta, etc., modifiers. You do this by setting up additional items that relate to the origi-
nal item through the fake function keys. Specifically, the additional items should use the
modified versions of the same fake function key used to name the original item.
Thus, if the original item was defined this way,
(define-key global-map [tool-bar shell]
’(menu-item "Shell" shell
:image (image :type xpm :file "shell.xpm")))
then here is how you can define clicking on the same tool bar image with the shift modifier:
(define-key global-map [tool-bar S-shell] ’some-command)
See Section 21.6.2 [Function Keys], page 316, for more information about how to add
modifiers to function keys.
23.1 Hooks
A hook is a variable where you can store a function or functions to be called on a particular
occasion by an existing program. Emacs provides hooks for the sake of customization.
Most often, hooks are set up in the init file (see Section 39.1.2 [Init File], page 813), but
Lisp programs can set them also. See Appendix I [Standard Hooks], page 903, for a list of
standard hook variables.
Most of the hooks in Emacs are normal hooks. These variables contain lists of functions
to be called with no arguments. By convention, whenever the hook name ends in ‘-hook’,
that tells you it is normal. We try to make all hooks normal, as much as possible, so that
you can use them in a uniform way.
Every major mode function is supposed to run a normal hook called the mode hook as
the one of the last steps of initialization. This makes it easy for a user to customize the
behavior of the mode, by overriding the buffer-local variable assignments already made by
the mode. Most minor mode functions also run a mode hook at the end. But hooks are
used in other contexts too. For example, the hook suspend-hook runs just before Emacs
suspends itself (see Section 39.2.2 [Suspending Emacs], page 817).
The recommended way to add a hook function to a normal hook is by calling add-hook
(see below). The hook functions may be any of the valid kinds of functions that funcall
accepts (see Section 12.1 [What Is a Function], page 160). Most normal hook variables are
initially void; add-hook knows how to deal with this. You can add hooks either globally or
buffer-locally with add-hook.
If the hook variable’s name does not end with ‘-hook’, that indicates it is probably an
abnormal hook. That means the hook functions are called with arguments, or their return
values are used in some way. The hook’s documentation says how the functions are called.
You can use add-hook to add a function to an abnormal hook, but you must write the
function to follow the hook’s calling convention.
By convention, abnormal hook names end in ‘-functions’ or ‘-hooks’. If the variable’s
name ends in ‘-function’, then its value is just a single function, not a list of functions.
Here’s an example that uses a mode hook to turn on Auto Fill mode when in Lisp
Interaction mode:
(add-hook ’lisp-interaction-mode-hook ’turn-on-auto-fill)
At the appropriate time, Emacs uses the run-hooks function to run particular hooks.
Chapter 23: Major and Minor Modes 383
buffer-local value. The latter acts as a flag to run the hook functions in the default
value as well as in the local value.
first. Using an alternative major mode avoids this limitation. See Section 21.12 [Recursive
Editing], page 342.
The standard GNU Emacs Lisp library directory tree contains the code for several major
modes, in files such as ‘text-mode.el’, ‘texinfo.el’, ‘lisp-mode.el’, ‘c-mode.el’, and
‘rmail.el’. They are found in various subdirectories of the ‘lisp’ directory. You can study
these libraries to see how modes are written. Text mode is perhaps the simplest major
mode aside from Fundamental mode. Rmail mode is a complicated and specialized mode.
• The major mode should usually have its own keymap, which is used as the local keymap
in all buffers in that mode. The major mode command should call use-local-map to
install this local map. See Section 22.7 [Active Keymaps], page 353, for more informa-
tion.
This keymap should be stored permanently in a global variable named modename -
mode-map. Normally the library that defines the mode sets this variable.
See Section 11.6 [Tips for Defining], page 141, for advice about how to write the code
to set up the mode’s keymap variable.
• The key sequences bound in a major mode keymap should usually start with C-c,
followed by a control character, a digit, or {, }, <, >, : or ;. The other punctuation
characters are reserved for minor modes, and ordinary letters are reserved for users.
A major mode can also rebind the keys M-n, M-p and M-s. The bindings for M-n and
M-p should normally be some kind of “moving forward and backward,” but this does
not necessarily mean cursor motion.
It is legitimate for a major mode to rebind a standard key sequence if it provides a
command that does “the same job” in a way better suited to the text this mode is used
for. For example, a major mode for editing a programming language might redefine
C-M-a to “move to the beginning of a function” in a way that works better for that
language.
It is also legitimate for a major mode to rebind a standard key sequence whose standard
meaning is rarely useful in that mode. For instance, minibuffer modes rebind M-r, whose
standard meaning is rarely of any use in the minibuffer. Major modes such as Dired or
Rmail that do not allow self-insertion of text can reasonably redefine letters and other
printing characters as special commands.
• Major modes modes for editing text should not define RET to do anything other than
insert a newline. However, it is ok for specialized modes for text that users don’t
directly edit, such as Dired and Info modes, to redefine RET to do something entirely
different.
• Major modes should not alter options that are primarily a matter of user preference,
such as whether Auto-Fill mode is enabled. Leave this to each user to decide. How-
ever, a major mode should customize other variables so that Auto-Fill mode will work
usefully if the user decides to use it.
• The mode may have its own syntax table or may share one with other related modes.
If it has its own syntax table, it should store this in a variable named modename -mode-
syntax-table. See Chapter 35 [Syntax Tables], page 684.
• If the mode handles a language that has a syntax for comments, it should set the
variables that define the comment syntax. See section “Options Controlling Comments”
in The GNU Emacs Manual.
• The mode may have its own abbrev table or may share one with other related modes.
If it has its own abbrev table, it should store this in a variable named modename -mode-
abbrev-table. If the major mode command defines any abbrevs itself, it should pass t
for the system-flag argument to define-abbrev. See Section 36.3 [Defining Abbrevs],
page 700.
Chapter 23: Major and Minor Modes 387
• The mode should specify how to do highlighting for Font Lock mode, by setting up a
buffer-local value for the variable font-lock-defaults (see Section 23.6 [Font Lock
Mode], page 412).
• The mode should specify how Imenu should find the definitions or sections of a buffer,
by setting up a buffer-local value for the variable imenu-generic-expression, for the
two variables imenu-prev-index-position-function and imenu-extract-index-
name-function, or for the variable imenu-create-index-function (see Section 23.5
[Imenu], page 410).
• The mode can specify a local value for eldoc-documentation-function to tell ElDoc
mode how to handle this mode.
• Use defvar or defcustom to set mode-related variables, so that they are not reinitial-
ized if they already have a value. (Such reinitialization could discard customizations
made by the user.)
• To make a buffer-local binding for an Emacs customization variable, use make-local-
variable in the major mode command, not make-variable-buffer-local. The latter
function would make the variable local to every buffer in which it is subsequently set,
which would affect buffers that do not use this mode. It is undesirable for a mode to
have such global effects. See Section 11.10 [Buffer-Local Variables], page 147.
With rare exceptions, the only reasonable way to use make-variable-buffer-local
in a Lisp package is for a variable which is used only within that package. Using it on
a variable used by other packages would interfere with them.
• Each major mode should have a normal mode hook named modename -mode-hook. The
very last thing the major mode command should do is to call run-mode-hooks. This
runs the mode hook, and then runs the normal hook after-change-major-mode-hook.
See Section 23.2.7 [Mode Hooks], page 393.
• The major mode command may start by calling some other major mode command
(called the parent mode) and then alter some of its settings. A mode that does this
is called a derived mode. The recommended way to define one is to use define-
derived-mode, but this is not required. Such a mode should call the parent mode
command inside a delay-mode-hooks form. (Using define-derived-mode does this
automatically.) See Section 23.2.5 [Derived Modes], page 391, and Section 23.2.7 [Mode
Hooks], page 393.
• If something special should be done if the user switches a buffer from this mode to any
other major mode, this mode can set up a buffer-local value for change-major-mode-
hook (see Section 11.10.2 [Creating Buffer-Local], page 149).
• If this mode is appropriate only for specially-prepared text, then the major mode
command symbol should have a property named mode-class with value special, put
on as follows:
(put ’funny-mode ’mode-class ’special)
This tells Emacs that new buffers created while the current buffer is in Funny mode
should not inherit Funny mode, in case default-major-mode is nil. Modes such as
Dired, Rmail, and Buffer List use this feature.
• If you want to make the new mode the default for files with certain recognizable names,
add an element to auto-mode-alist to select the mode for those file names (see Sec-
Chapter 23: Major and Minor Modes 388
tion 23.2.3 [Auto Major Mode], page 388). If you define the mode command to au-
toload, you should add this element in the same file that calls autoload. If you use an
autoload cookie for the mode command, you can also use an autoload cookie for the
form that adds the element (see [autoload cookie], page 207). If you do not autoload
the mode command, it is sufficient to add the element in the file that contains the mode
definition.
• In the comments that document the file, you should provide a sample autoload form
and an example of how to add to auto-mode-alist, that users can include in their init
files (see Section 39.1.2 [Init File], page 813).
• The top-level forms in the file defining the mode should be written so that they may
be evaluated more than once without adverse consequences. Even if you never load the
file more than once, someone else will.
fundamental-mode [Command]
Fundamental mode is a major mode that is not specialized for anything in particular.
Other major modes are defined in effect by comparison with this one—their defini-
tions say what to change, starting from Fundamental mode. The fundamental-mode
function does not run any mode hooks; you’re not supposed to customize it. (If you
want Emacs to behave differently in Fundamental mode, change the global state of
Emacs.)
magic-fallback-mode-alist [Variable]
This works like magic-mode-alist, except that it is handled only if auto-mode-alist
does not specify a mode for this file.
auto-mode-alist [Variable]
This variable contains an association list of file name patterns (regular expressions)
and corresponding major mode commands. Usually, the file name patterns test for
suffixes, such as ‘.el’ and ‘.c’, but this need not be the case. An ordinary element
of the alist looks like (regexp . mode-function ).
For example,
(("\\‘/tmp/fol/" . text-mode)
("\\.texinfo\\’" . texinfo-mode)
("\\.texi\\’" . texinfo-mode)
("\\.el\\’" . emacs-lisp-mode)
("\\.c\\’" . c-mode)
("\\.h\\’" . c-mode)
...)
When you visit a file whose expanded file name (see Section 25.8.4 [File Name Expan-
sion], page 457), with version numbers and backup suffixes removed using file-name-
sans-versions (see Section 25.8.1 [File Name Components], page 453), matches a
regexp, set-auto-mode calls the corresponding mode-function. This feature enables
Emacs to select the proper major mode for most files.
If an element of auto-mode-alist has the form (regexp function t), then after
calling function, Emacs searches auto-mode-alist again for a match against the
portion of the file name that did not match before. This feature is useful for uncom-
pression packages: an entry of the form ("\\.gz\\’" function t) can uncompress
the file and then put the uncompressed file in the proper mode according to the name
sans ‘.gz’.
Here is an example of how to prepend several pattern pairs to auto-mode-alist.
(You might use this sort of expression in your init file.)
(setq auto-mode-alist
(append
;; File name (within directory) starts with a dot.
’(("/\\.[^/]*\\’" . fundamental-mode)
;; File name has no dot.
("[^\\./]*\\’" . fundamental-mode)
;; File name ends in ‘.C’.
("\\.C\\’" . c++-mode))
auto-mode-alist))
major-mode [Variable]
This buffer-local variable holds the symbol for the current buffer’s major mode. This
symbol should have a function definition that is the command to switch to that major
mode. The describe-mode function uses the documentation string of the function as
the documentation of the major mode.
parent, or the standard syntax table if parent is nil. (Note that this
does not follow the convention used for non-keyword arguments that a
nil value is equivalent with not specifying the argument.)
:abbrev-table
You can use this to explicitly specify an abbrev table for the new mode.
If you specify a nil value, the new mode uses the same abbrev table as
parent, or fundamental-mode-abbrev-table if parent is nil. (Again, a
nil value is not equivalent to not specifying this keyword.)
:group If this is specified, the value should be the customization group for this
mode. (Not all major modes have one.) Only the (still experimental and
unadvertised) command customize-mode currently uses this. define-
derived-mode does not automatically define the specified customization
group.
Here is a hypothetical example:
(define-derived-mode hypertext-mode
text-mode "Hypertext"
"Major mode for hypertext.
\\{hypertext-mode-map}"
(setq case-fold-search nil))
(define-key hypertext-mode-map
[down-mouse-3] ’do-hyper-link)
Do not write an interactive spec in the definition; define-derived-mode does that
automatically.
after-change-major-mode-hook [Variable]
This is a normal hook run by run-mode-hooks. It is run at the very end of every
properly-written major mode function.
Chapter 23: Major and Minor Modes 394
(defun text-mode ()
"Major mode for editing text intended for humans to read...
Special commands: \\{text-mode-map}
Turning on text-mode runs the hook ‘text-mode-hook’."
(interactive)
(kill-all-local-variables)
(use-local-map text-mode-map)
(setq local-abbrev-table text-mode-abbrev-table)
(set-syntax-table text-mode-syntax-table)
Chapter 23: Major and Minor Modes 395
(defvar emacs-lisp-mode-syntax-table
(let ((table (make-syntax-table)))
(let ((i 0))
In Lisp and most programming languages, we want the paragraph commands to treat
only blank lines as paragraph separators. And the modes should undestand the Lisp con-
ventions for comments. The rest of lisp-mode-variables sets this up:
(make-local-variable ’paragraph-start)
(setq paragraph-start (concat page-delimiter "\\|$" ))
(make-local-variable ’paragraph-separate)
(setq paragraph-separate paragraph-start)
...
(make-local-variable ’comment-indent-function)
(setq comment-indent-function ’lisp-comment-indent))
...
Each of the different Lisp modes has a slightly different keymap. For example, Lisp mode
binds C-c C-z to run-lisp, but the other Lisp modes do not. However, all Lisp modes have
some commands in common. The following code sets up the common commands:
(defvar shared-lisp-mode-map ()
"Keymap for commands shared by all sorts of Lisp modes.")
And here is the code to set up the keymap for Lisp mode:
(defvar lisp-mode-map ()
"Keymap for ordinary Lisp mode...")
(if lisp-mode-map
()
(setq lisp-mode-map (make-sparse-keymap))
(set-keymap-parent lisp-mode-map shared-lisp-mode-map)
(define-key lisp-mode-map "\e\C-x" ’lisp-eval-defun)
(define-key lisp-mode-map "\C-c\C-z" ’run-lisp))
Finally, here is the complete major mode function definition for Lisp mode.
(defun lisp-mode ()
"Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{lisp-mode-map}
Note that ‘run-lisp’ may be used either to start an inferior Lisp job
or to switch back to an existing one.
minor-mode-list [Variable]
The value of this variable is a list of all minor mode commands.
If possible, implement the mode so that setting the variable automatically enables or
disables the mode. Then the minor mode command does not need to do anything
except set the variable.
This variable is used in conjunction with the minor-mode-alist to display the minor
mode name in the mode line. It can also enable or disable a minor mode keymap.
Individual commands or hooks can also check the variable’s value.
If you want the minor mode to be enabled separately in each buffer, make the variable
buffer-local.
• Define a command whose name is the same as the mode variable. Its job is to enable
and disable the mode by setting the variable.
The command should accept one optional argument. If the argument is nil, it should
toggle the mode (turn it on if it is off, and off if it is on). It should turn the mode on
if the argument is a positive integer, the symbol t, or a list whose car is one of those.
It should turn the mode off if the argument is a negative integer or zero, the symbol
-, or a list whose car is a negative integer or zero. The meaning of other arguments
is not specified.
Here is an example taken from the definition of transient-mark-mode. It shows the
use of transient-mark-mode as a variable that enables or disables the mode’s behavior,
and also shows the proper way to toggle, enable or disable the minor mode based on
the raw prefix argument value.
(setq transient-mark-mode
(if (null arg) (not transient-mark-mode)
(> (prefix-numeric-value arg) 0)))
• Add an element to minor-mode-alist for each minor mode (see [Definition of minor-
mode-alist], page 406), if you want to indicate the minor mode in the mode line. This
element should be a list of the following form:
(mode-variable string )
Here mode-variable is the variable that controls enabling of the minor mode, and string
is a short string, starting with a space, to represent the mode in the mode line. These
strings must be short so that there is room for several of them at once.
When you add an element to minor-mode-alist, use assq to check for an existing
element, to avoid duplication. For example:
(unless (assq ’leif-mode minor-mode-alist)
(setq minor-mode-alist
(cons ’(leif-mode " Leif") minor-mode-alist)))
or like this, using add-to-list (see Section 5.5 [List Variables], page 71):
(add-to-list ’minor-mode-alist ’(leif-mode " Leif"))
Global minor modes distributed with Emacs should if possible support enabling and
disabling via Custom (see Chapter 14 [Customization], page 185). To do this, the first step
is to define the mode variable with defcustom, and specify :type boolean.
If just setting the variable is not sufficient to enable the mode, you should also specify
a :set method which enables the mode by invoking the mode command. Note in the
variable’s documentation string that setting the variable other than via Custom may not
take effect.
Chapter 23: Major and Minor Modes 399
Also mark the definition with an autoload cookie (see [autoload cookie], page 207),
and specify a :require so that customizing the variable will load the library that defines
the mode. This will copy suitable definitions into ‘loaddefs.el’ so that users can use
customize-option to enable the mode. For example:
;;;###autoload
(defcustom msb-mode nil
"Toggle msb-mode.
Setting this variable directly does not take effect;
use either \\[customize] or the function ‘msb-mode’."
:set ’custom-set-minor-mode
:initialize ’custom-initialize-default
:version "20.4"
:type ’boolean
:group ’msb
:require ’msb)
The above three arguments init-value, lighter, and keymap can be (partially) omit-
ted when keyword-args are used. The keyword-args consist of keywords followed by
corresponding values. A few keywords have special meanings:
:group group
Custom group name to use in all generated defcustom forms. Defaults
to mode without the possible trailing ‘-mode’. Warning: don’t use this
default group name unless you have written a defgroup to define that
group properly. See Section 14.2 [Group Definitions], page 187.
:global global
If non-nil, this specifies that the minor mode should be global rather
than buffer-local. It defaults to nil.
One of the effects of making a minor mode global is that the mode vari-
able becomes a customization variable. Toggling it through the Custom
interface turns the mode on and off, and its value can be saved for fu-
ture Emacs sessions (see section “Saving Customizations” in The GNU
Emacs Manual. For the saved variable to work, you should ensure that
the define-minor-mode form is evaluated each time Emacs starts; for
packages that are not part of Emacs, the easiest way to do this is to
specify a :require keyword.
:init-value init-value
This is equivalent to specifying init-value positionally.
:lighter lighter
This is equivalent to specifying lighter positionally.
:keymap keymap
This is equivalent to specifying keymap positionally.
Any other keyword arguments are passed directly to the defcustom generated for the
variable mode.
The command named mode first performs the standard actions such as setting the
variable named mode and then executes the body forms, if any. It finishes by running
the mode hook variable mode -hook.
The initial value must be nil except in cases where (1) the mode is preloaded in Emacs,
or (2) it is painless for loading to enable the mode even though the user did not request it.
For instance, if the mode has no effect unless something else is enabled, and will always be
loaded by that time, enabling it by default is harmless. But these are unusual circumstances.
Normally, the initial value must be nil.
The name easy-mmode-define-minor-mode is an alias for this macro.
Here is an example of using define-minor-mode:
(define-minor-mode hungry-mode
"Toggle Hungry mode.
With no argument, this command toggles the mode.
Non-null prefix argument turns on the mode.
Null prefix argument turns off the mode.
Use :group group in keyword-args to specify the custom group for the mode variable
of the global minor mode.
mode-line-format [Variable]
The value of this variable is a mode-line construct that controls the contents of the
mode-line. It is always buffer-local in all buffers.
If you set this variable to nil in a buffer, that buffer does not have a mode line. (A
window that is just one line tall never displays a mode line.)
The default value of mode-line-format is designed to use the values of other variables
such as mode-line-position and mode-line-modes (which in turn incorporates the values
of the variables mode-name and minor-mode-alist). Very few modes need to alter mode-
line-format itself. For most purposes, it is sufficient to alter some of the variables that
mode-line-format either directly or indirectly refers to.
If you do alter mode-line-format itself, the new value should use the same variables
that appear in the default value (see Section 23.4.4 [Mode Line Variables], page 405), rather
than duplicating their contents or displaying the information in another fashion. This way,
customizations made by the user or by Lisp programs (such as display-time and major
modes) via changes to those variables remain effective.
Here is an example of a mode-line-format that might be useful for shell-mode, since
it contains the host name and default directory.
(setq mode-line-format
(list "-"
’mode-line-mule-info
’mode-line-modified
’mode-line-frame-identification
"%b--"
;; Note that this is evaluated while making the list.
;; It makes a mode-line construct which is just a string.
(getenv "HOST")
":"
’default-directory
" "
’global-mode-string
" %[("
’(:eval (mode-line-mode-name))
Chapter 23: Major and Minor Modes 405
’mode-line-process
’minor-mode-alist
"%n"
")%]--"
’(which-func-mode ("" which-func-format "--"))
’(line-number-mode "L%l--")
’(column-number-mode "C%c--")
’(-3 "%p")
"-%-"))
(The variables line-number-mode, column-number-mode and which-func-mode enable
particular minor modes; as usual, these variable names are also the minor mode command
names.)
mode-line-mule-info [Variable]
This variable holds the value of the mode-line construct that displays information
about the language environment, buffer coding system, and current input method.
See Chapter 33 [Non-ASCII Characters], page 640.
mode-line-modified [Variable]
This variable holds the value of the mode-line construct that displays whether the
current buffer is modified.
The default value of mode-line-modified is ("%1*%1+"). This means that the mode
line displays ‘**’ if the buffer is modified, ‘--’ if the buffer is not modified, ‘%%’ if the
buffer is read only, and ‘%*’ if the buffer is read only and modified.
Changing this variable does not force an update of the mode line.
mode-line-frame-identification [Variable]
This variable identifies the current frame. The default value is " " if you are using a
window system which can show multiple frames, or "-%F " on an ordinary terminal
which shows only one frame at a time.
mode-line-buffer-identification [Variable]
This variable identifies the buffer being displayed in the window. Its default value is
("%12b"), which displays the buffer name, padded with spaces to at least 12 columns.
mode-line-position [Variable]
This variable indicates the position in the buffer. Here is a simplified version of its
default value. The actual default value also specifies addition of the help-echo text
property.
Chapter 23: Major and Minor Modes 406
((-3 "%p")
(size-indication-mode (8 " of %I"))
(line-number-mode
((column-number-mode
(10 " (%l,%c)")
(6 " L%l")))
((column-number-mode
(5 " C%c")))))
This means that mode-line-position displays at least the buffer percentage and
possibly the buffer size, the line number and the column number.
vc-mode [Variable]
The variable vc-mode, buffer-local in each buffer, records whether the buffer’s visited
file is maintained with version control, and, if so, which kind. Its value is a string
that appears in the mode line, or nil for no version control.
mode-line-modes [Variable]
This variable displays the buffer’s major and minor modes. Here is a simplified version
of its default value. The real default value also specifies addition of text properties.
("%[(" mode-name
mode-line-process minor-mode-alist
"%n" ")%]--")
So mode-line-modes normally also displays the recursive editing level, information
on the process status and whether narrowing is in effect.
mode-name [Variable]
This buffer-local variable holds the “pretty” name of the current buffer’s major mode.
Each major mode should set this variable so that the mode name will appear in the
mode line.
mode-line-process [Variable]
This buffer-local variable contains the mode-line information on process status in
modes used for communicating with subprocesses. It is displayed immediately follow-
ing the major mode name, with no intervening space. For example, its value in the
‘*shell*’ buffer is (":%s"), which allows the shell to display its status along with
the major mode as: ‘(Shell:run)’. Normally this variable is nil.
minor-mode-alist [Variable]
This variable holds an association list whose elements specify how the mode line
should indicate that a minor mode is active. Each element of the minor-mode-alist
should be a two-element list:
(minor-mode-variable mode-line-string )
More generally, mode-line-string can be any mode-line spec. It appears in the mode
line when the value of minor-mode-variable is non-nil, and not otherwise. These
strings should begin with spaces so that they don’t run together. Conventionally, the
Chapter 23: Major and Minor Modes 407
minor-mode-variable for a specific mode is set to a non-nil value when that minor
mode is activated.
minor-mode-alist itself is not buffer-local. Each variable mentioned in the alist
should be buffer-local if its minor mode can be enabled separately in each buffer.
global-mode-string [Variable]
This variable holds a mode-line spec that, by default, appears in the mode line just
after the which-func-mode minor mode if set, else after mode-line-modes. The
command display-time sets global-mode-string to refer to the variable display-
time-string, which holds a string containing the time and load information.
The ‘%M’ construct substitutes the value of global-mode-string, but that is obsolete,
since the variable is included in the mode line from mode-line-format.
default-mode-line-format [Variable]
This variable holds the default mode-line-format for buffers that do not override it.
This is the same as (default-value ’mode-line-format).
Here is a simplified version of the default value of default-mode-line-format. The
real default value also specifies addition of text properties.
("-"
mode-line-mule-info
mode-line-modified
mode-line-frame-identification
mode-line-buffer-identification
" "
mode-line-position
(vc-mode vc-mode)
" "
mode-line-modes
(which-func-mode ("" which-func-format "--"))
(global-mode-string ("--" global-mode-string))
"-%-")
%f The visited file name, obtained with the buffer-file-name function. See Sec-
tion 27.4 [Buffer File Name], page 485.
%F The title (only on a window system) or the name of the selected frame. See
Section 29.3.3.1 [Basic Parameters], page 533.
%i The size of the accessible part of the current buffer; basically (- (point-max)
(point-min)).
%I Like ‘%i’, but the size is printed in a more readable way by using ‘k’ for 10^3,
‘M’ for 10^6, ‘G’ for 10^9, etc., to abbreviate.
%l The current line number of point, counting within the accessible portion of the
buffer.
%n ‘Narrow’ when narrowing is in effect; nothing otherwise (see narrow-to-region
in Section 30.4 [Narrowing], page 569).
%p The percentage of the buffer text above the top of window, or ‘Top’, ‘Bottom’
or ‘All’. Note that the default mode-line specification truncates this to three
characters.
%P The percentage of the buffer text that is above the bottom of the window (which
includes the text visible in the window, as well as the text above the top), plus
‘Top’ if the top of the buffer is visible on screen; or ‘Bottom’ or ‘All’.
%s The status of the subprocess belonging to the current buffer, obtained with
process-status. See Section 37.6 [Process Information], page 712.
%t Whether the visited file is a text file or a binary file. This is a meaningful
distinction only on certain operating systems (see Section 33.10.9 [MS-DOS
File Types], page 658).
%z The mnemonics of keyboard, terminal, and buffer coding systems.
%Z Like ‘%z’, but including the end-of-line format.
%* ‘%’ if the buffer is read only (see buffer-read-only);
‘*’ if the buffer is modified (see buffer-modified-p);
‘-’ otherwise. See Section 27.5 [Buffer Modification], page 487.
%+ ‘*’ if the buffer is modified (see buffer-modified-p);
‘%’ if the buffer is read only (see buffer-read-only);
‘-’ otherwise. This differs from ‘%*’ only for a modified read-only buffer. See
Section 27.5 [Buffer Modification], page 487.
%& ‘*’ if the buffer is modified, and ‘-’ otherwise.
%[ An indication of the depth of recursive editing levels (not counting minibuffer
levels): one ‘[’ for each editing level. See Section 21.12 [Recursive Editing],
page 342.
%] One ‘]’ for each recursive editing level (not counting minibuffer levels).
%- Dashes sufficient to fill the remainder of the mode line.
%% The character ‘%’—this is how to include a literal ‘%’ in a string in which %-
constructs are allowed.
Chapter 23: Major and Minor Modes 409
The following two %-constructs are still supported, but they are obsolete, since you can
get the same results with the variables mode-name and global-mode-string.
%m The value of mode-name.
%M The value of global-mode-string.
header-line-format [Variable]
This variable, local in every buffer, specifies how to display the header line, for win-
dows displaying the buffer. The format of the value is the same as for mode-line-
format (see Section 23.4.2 [Mode Line Data], page 402).
default-header-line-format [Variable]
This variable holds the default header-line-format for buffers that do not override
it. This is the same as (default-value ’header-line-format).
It is normally nil, so that ordinary buffers have no header line.
A window that is just one line tall never displays a header line. A window that is two
lines tall cannot display both a mode line and a header line at once; if it has a mode line,
then it does not display a header line.
Chapter 23: Major and Minor Modes 410
23.5 Imenu
Imenu is a feature that lets users select a definition or section in the buffer, from a menu
which lists all of them, to go directly to that location in the buffer. Imenu works by
constructing a buffer index which lists the names and buffer positions of the definitions, or
other named portions of the buffer; then the user can choose one of them and move point
to it. Major modes can add a menu bar item to use Imenu using imenu-add-to-menubar.
imenu-add-to-menubar name [Function]
This function defines a local menu bar item named name to run Imenu.
The user-level commands for using Imenu are described in the Emacs Manual (see section
“Imenu” in the Emacs Manual). This section explains how to customize Imenu’s method
of finding definitions or buffer portions for a particular major mode.
The usual and simplest way is to set the variable imenu-generic-expression:
imenu-generic-expression [Variable]
This variable, if non-nil, is a list that specifies regular expressions for finding defini-
tions for Imenu. Simple elements of imenu-generic-expression look like this:
(menu-title regexp index )
Here, if menu-title is non-nil, it says that the matches for this element should go in
a submenu of the buffer index; menu-title itself specifies the name for the submenu.
If menu-title is nil, the matches for this element go directly in the top level of the
buffer index.
The second item in the list, regexp, is a regular expression (see Section 34.3 [Reg-
ular Expressions], page 663); anything in the buffer that it matches is considered a
Chapter 23: Major and Minor Modes 411
definition, something to mention in the buffer index. The third item, index, is a non-
negative integer that indicates which subexpression in regexp matches the definition’s
name.
An element can also look like this:
(menu-title regexp index function arguments ...)
Each match for this element creates an index item, and when the index item is selected
by the user, it calls function with arguments consisting of the item name, the buffer
position, and arguments.
For Emacs Lisp mode, imenu-generic-expression could look like this:
((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
("*Vars*" "^\\s-*(def\\(var\\|const\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
("*Types*"
"^\\s-*\
(def\\(type\\|struct\\|class\\|ine-condition\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2))
Setting this variable makes it buffer-local in the current buffer.
imenu-case-fold-search [Variable]
This variable controls whether matching against the regular expressions in the value of
imenu-generic-expression is case-sensitive: t, the default, means matching should
ignore case.
Setting this variable makes it buffer-local in the current buffer.
imenu-syntax-alist [Variable]
This variable is an alist of syntax table modifiers to use while processing imenu-
generic-expression, to override the syntax table of the current buffer. Each element
should have this form:
(characters . syntax-description )
The car, characters, can be either a character or a string. The element says to
give that character or characters the syntax specified by syntax-description, which
is passed to modify-syntax-entry (see Section 35.3 [Syntax Table Functions],
page 688).
This feature is typically used to give word syntax to characters which normally
have symbol syntax, and thus to simplify imenu-generic-expression and speed
up matching. For example, Fortran mode uses it this way:
(setq imenu-syntax-alist ’(("_$" . "w")))
The imenu-generic-expression regular expressions can then use ‘\\sw+’ instead
of ‘\\(\\sw\\|\\s_\\)+’. Note that this technique may be inconvenient when the
mode needs to limit the initial character of a name to a smaller set of characters than
are allowed in the rest of a name.
Setting this variable makes it buffer-local in the current buffer.
Another way to customize Imenu for a major mode is to set the variables imenu-prev-
index-position-function and imenu-extract-index-name-function:
Chapter 23: Major and Minor Modes 412
imenu-prev-index-position-function [Variable]
If this variable is non-nil, its value should be a function that finds the next “def-
inition” to put in the buffer index, scanning backward in the buffer from point. It
should return nil if it doesn’t find another “definition” before point. Otherwise it
should leave point at the place it finds a “definition” and return any non-nil value.
Setting this variable makes it buffer-local in the current buffer.
imenu-extract-index-name-function [Variable]
If this variable is non-nil, its value should be a function to return the name for a
definition, assuming point is in that definition as the imenu-prev-index-position-
function function would leave it.
Setting this variable makes it buffer-local in the current buffer.
The last way to customize Imenu for a major mode is to set the variable imenu-create-
index-function:
imenu-create-index-function [Variable]
This variable specifies the function to use for creating a buffer index. The function
should take no arguments, and return an index alist for the current buffer. It is called
within save-excursion, so where it leaves point makes no difference.
The index alist can have three types of elements. Simple elements look like this:
(index-name . index-position )
Selecting a simple element has the effect of moving to position index-position in the
buffer. Special elements look like this:
(index-name index-position function arguments ...)
Selecting a special element performs:
(funcall function
index-name index-position arguments ...)
A nested sub-alist element looks like this:
(menu-title sub-alist )
It creates the submenu menu-title specified by sub-alist.
The default value of imenu-create-index-function is imenu-default-create-
index-function. This function calls the value of imenu-prev-index-position-
function and the value of imenu-extract-index-name-function to produce the
index alist. However, if either of these two variables is nil, the default function uses
imenu-generic-expression instead.
Setting this variable makes it buffer-local in the current buffer.
fontification happens first; it finds comments and string constants and highlights them.
Search-based fontification happens second.
not required; it is possible to fontify some things using font-lock-face properties and set
up automatic fontification for other parts of the text.
(matcher . facespec )
In this kind of element, facespec is an expression whose value specifies the face
to use for highlighting. In the simplest case, facespec is a Lisp variable (a
symbol) whose value is a face name.
;; Highlight occurrences of ‘fubar’,
;; using the face which is the value of fubar-face.
("fubar" . fubar-face)
However, facespec can also evaluate to a list of this form:
(face face prop1 val1 prop2 val2 ...)
to specify the face face and various additional text properties to put on the
text that matches. If you do this, be sure to add the other text property
names that you set in this way to the value of font-lock-extra-managed-
props so that the properties will also be cleared out when they are no longer
appropriate. Alternatively, you can set the variable font-lock-unfontify-
region-function to a function that clears these properties. See Section 23.6.4
[Other Font Lock Variables], page 418.
(matcher . subexp-highlighter )
In this kind of element, subexp-highlighter is a list which specifies how to
highlight matches found by matcher. It has the form:
(subexp facespec [[override [laxmatch ]])
The car, subexp, is an integer specifying which subexpression of the match to
fontify (0 means the entire matching text). The second subelement, facespec,
is an expression whose value specifies the face, as described above.
The last two values in subexp-highlighter, override and laxmatch, are optional
flags. If override is t, this element can override existing fontification made by
previous elements of font-lock-keywords. If it is keep, then each character
is fontified if it has not been fontified already by some other element. If it
is prepend, the face specified by facespec is added to the beginning of the
font-lock-face property. If it is append, the face is added to the end of the
font-lock-face property.
If laxmatch is non-nil, it means there should be no error if there is no subexpres-
sion numbered subexp in matcher. Obviously, fontification of the subexpression
numbered subexp will not occur. However, fontification of other subexpressions
(and other regexps) will continue. If laxmatch is nil, and the specified subex-
pression is missing, then an error is signaled which terminates search-based
fontification.
Here are some examples of elements of this kind, and what they do:
;; Highlight occurrences of either ‘foo’ or ‘bar’, using
;; foo-bar-face, even if they have already been highlighted.
;; foo-bar-face should be a variable whose value is a face.
("foo\\|bar" 0 foo-bar-face t)
(matcher . anchored-highlighter )
In this kind of element, anchored-highlighter specifies how to highlight text
that follows a match found by matcher. So a match found by matcher acts
as the anchor for further searches specified by anchored-highlighter. anchored-
highlighter is a list of the following form:
(anchored-matcher pre-form post-form
subexp-highlighters ...)
Here, anchored-matcher, like matcher, is either a regular expression or a func-
tion. After a match of matcher is found, point is at the end of the match.
Now, Font Lock evaluates the form pre-form. Then it searches for matches of
anchored-matcher and uses subexp-highlighters to highlight these. A subexp-
highlighter is as described above. Finally, Font Lock evaluates post-form.
The forms pre-form and post-form can be used to initialize before, and cleanup
after, anchored-matcher is used. Typically, pre-form is used to move point to
some position relative to the match of matcher, before starting with anchored-
matcher. post-form might be used to move back, before resuming with matcher.
After Font Lock evaluates pre-form, it does not search for anchored-matcher
beyond the end of the line. However, if pre-form returns a buffer position
that is greater than the position of point after pre-form is evaluated, then the
position returned by pre-form is used as the limit of the search instead. It is
generally a bad idea to return a position greater than the end of the line; in
other words, the anchored-matcher search should not span lines.
For example,
;; Highlight occurrences of the word ‘item’ following
;; an occurrence of the word ‘anchor’ (on the same line)
;; in the value of item-face.
("\\<anchor\\>" "\\<item\\>" nil nil (0 item-face))
Here, pre-form and post-form are nil. Therefore searching for ‘item’ starts
at the end of the match of ‘anchor’, and searching for subsequent instances of
‘anchor’ resumes from where searching for ‘item’ concluded.
(eval . form )
Here form is an expression to be evaluated the first time this value of font-
lock-keywords is used in a buffer. Its value should have one of the forms
described in this table.
Chapter 23: Major and Minor Modes 417
font-lock-keywords-case-fold-search [Variable]
Non-nil means that regular expression matching for the sake of font-lock-keywords
should be case-insensitive.
adds two fontification patterns for C mode: one to fontify the word ‘FIXME’, even in com-
ments, and another to fontify the words ‘and’, ‘or’ and ‘not’ as keywords.
That example affects only C mode proper. To add the same patterns to C mode and all
modes derived from it, do this instead:
(add-hook ’c-mode-hook
(lambda ()
(font-lock-add-keywords nil
’(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
("\\<\\(and\\|or\\|not\\)\\>" .
font-lock-keyword-face)))))
font-lock-mark-block-function [Variable]
If this variable is non-nil, it should be a function that is called with no arguments,
to choose an enclosing range of text for refontification for the command M-o M-o
(font-lock-fontify-block).
The function should report its choice by placing the region around it. A good choice
is a range of text large enough to give proper results, but not too large so that
refontification becomes slow. Typical values are mark-defun for programming modes
or mark-paragraph for textual modes.
font-lock-extra-managed-props [Variable]
This variable specifies additional properties (other than font-lock-face) that are
being managed by Font Lock mode. It is used by font-lock-default-unfontify-
region, which normally only manages the font-lock-face property. If you want
Font Lock to manage other properties as well, you must specify them in a facespec in
font-lock-keywords as well as add them to this list. See Section 23.6.2 [Search-based
Fontification], page 414.
font-lock-fontify-buffer-function [Variable]
Function to use for fontifying the buffer. The default value is font-lock-default-
fontify-buffer.
font-lock-unfontify-buffer-function [Variable]
Function to use for unfontifying the buffer. This is used when turning off Font Lock
mode. The default value is font-lock-default-unfontify-buffer.
font-lock-fontify-region-function [Variable]
Function to use for fontifying a region. It should take two arguments, the beginning
and end of the region, and an optional third argument verbose. If verbose is non-nil,
the function should print status messages. The default value is font-lock-default-
fontify-region.
font-lock-unfontify-region-function [Variable]
Function to use for unfontifying a region. It should take two arguments, the beginning
and end of the region. The default value is font-lock-default-unfontify-region.
Chapter 23: Major and Minor Modes 419
font-lock-builtin-face
Used (typically) for built-in function names.
font-lock-function-name-face
Used (typically) for the name of a function being defined or declared, in a
function definition or declaration.
font-lock-variable-name-face
Used (typically) for the name of a variable being defined or declared, in a
variable definition or declaration.
font-lock-type-face
Used (typically) for names of user-defined data types, where they are defined
and where they are used.
font-lock-constant-face
Used (typically) for constant names.
font-lock-preprocessor-face
Used (typically) for preprocessor commands.
font-lock-negation-char-face
Used (typically) for easily-overlooked negation characters.
font-lock-warning-face
Used (typically) for constructs that are peculiar, or that greatly change the
meaning of other text. For example, this is used for ‘;;;###autoload’ cookies
in Emacs Lisp, and for #error directives in C.
font-lock-keywords-only [Variable]
Non-nil means Font Lock should not do syntactic fontification; it should only fontify
based on font-lock-keywords. The normal way for a mode to set this variable to t
is with keywords-only in font-lock-defaults.
font-lock-syntax-table [Variable]
This variable holds the syntax table to use for fontification of comments and strings.
Specify it using syntax-alist in font-lock-defaults. If this is nil, fontification uses
the buffer’s syntax table.
font-lock-beginning-of-syntax-function [Variable]
If this variable is non-nil, it should be a function to move point back to a position
that is syntactically at “top level” and outside of strings or comments. Font Lock
uses this when necessary to get the right results for syntactic fontification.
Chapter 23: Major and Minor Modes 421
This function is called with no arguments. It should leave point at the beginning of
any enclosing syntactic block. Typical values are beginning-of-line (used when the
start of the line is known to be outside a syntactic block), or beginning-of-defun
for programming modes, or backward-paragraph for textual modes.
If the value is nil, Font Lock uses syntax-begin-function to move back outside of
any comment, string, or sexp. This variable is semi-obsolete; we recommend setting
syntax-begin-function instead.
Specify this variable using syntax-begin in font-lock-defaults.
font-lock-syntactic-face-function [Variable]
A function to determine which face to use for a given syntactic element (a string
or a comment). The function is called with one argument, the parse state at point
returned by parse-partial-sexp, and should return a face. The default value returns
font-lock-comment-face for comments and font-lock-string-face for strings.
This can be used to highlighting different kinds of strings or comments differently. It
is also sometimes abused together with font-lock-syntactic-keywords to highlight
constructs that span multiple lines, but this is too esoteric to document here.
Specify this variable using other-vars in font-lock-defaults.
font-lock-syntactic-keywords [Variable]
This variable enables and controls updating syntax-table properties by Font Lock.
Its value should be a list of elements of this form:
(matcher subexp syntax override laxmatch )
The parts of this element have the same meanings as in the corresponding sort of
element of font-lock-keywords,
(matcher subexp facespec override laxmatch )
However, instead of specifying the value facespec to use for the face property, it
specifies the value syntax to use for the syntax-table property. Here, syntax can be a
string (as taken by modify-syntax-entry), a syntax table, a cons cell (as returned by
string-to-syntax), or an expression whose value is one of those two types. override
cannot be prepend or append.
For example, an element of the form:
("\\$\\(#\\)" 1 ".")
highlights syntactically a hash character when following a dollar character, with a
SYNTAX of "." (meaning punctuation syntax). Assuming that the buffer syntax
table specifies hash characters to have comment start syntax, the element will only
highlight hash characters that do not follow dollar characters as comments syntacti-
cally.
An element of the form:
Chapter 23: Major and Minor Modes 422
("\\(’\\).\\(’\\)"
(1 "\"")
(2 "\""))
highlights syntactically both single quotes which surround a single character, with a
SYNTAX of "\"" (meaning string quote syntax). Assuming that the buffer syntax
table does not specify single quotes to have quote syntax, the element will only high-
light single quotes of the form ‘’c ’’ as strings syntactically. Other forms, such as
‘foo’bar’ or ‘’fubar’’, will not be highlighted as strings.
Major modes normally set this variable with other-vars in font-lock-defaults.
font-lock-multiline [Variable]
If the font-lock-multiline variable is set to t, Font Lock will try to add the font-
lock-multiline property automatically on multiline constructs. This is not a uni-
versal solution, however, since it slows down Font Lock somewhat. It can miss some
multiline constructs, or make the property larger or smaller than necessary.
For elements whose matcher is a function, the function should ensure that submatch
0 covers the whole relevant multiline construct, even if only a small subpart will be
highlighted. It is often just as easy to add the font-lock-multiline property by
hand.
font-lock-extend-after-change-region-function [Variable]
This buffer-local variable is either nil or a function for Font-Lock to call to determine
the region to scan and fontify.
The function is given three parameters, the standard beg, end, and old-len from after-
change-functions (see Section 32.26 [Change Hooks], page 638). It should return either
Chapter 23: Major and Minor Modes 424
a cons of the beginning and end buffer positions (in that order) of the region to fontify,
or nil (which means choose the region in the standard way). This function needs
to preserve point, the match-data, and the current restriction. The region it returns
may start or end in the middle of a line.
Since this function is called after every buffer change, it should be reasonably fast.
desktop-save-buffer [Variable]
If this buffer-local variable is non-nil, the buffer will have its state saved in the
desktop file at desktop save. If the value is a function, it is called at desktop save
with argument desktop-dirname, and its value is saved in the desktop file along with
the state of the buffer for which it was called. When file names are returned as part
of the auxiliary information, they should be formatted using the call
(desktop-file-name file-name desktop-dirname )
For buffers not visiting a file to be restored, the major mode must define a function to
do the job, and that function must be listed in the alist desktop-buffer-mode-handlers.
desktop-buffer-mode-handlers [Variable]
Alist with elements
(major-mode . restore-buffer-function )
The function restore-buffer-function will be called with argument list
(buffer-file-name buffer-name desktop-buffer-misc )
and it should return the restored buffer. Here desktop-buffer-misc is the value re-
turned by the function optionally bound to desktop-save-buffer.
Chapter 24: Documentation 425
24 Documentation
GNU Emacs Lisp has convenient on-line help facilities, most of which derive their informa-
tion from the documentation strings associated with functions and variables. This chapter
describes how to write good documentation strings for your Lisp programs, as well as how
to write programs to access documentation.
Note that the documentation strings for Emacs are not the same thing as the Emacs
manual. Manuals have their own source files, written in the Texinfo language; documenta-
tion strings are specified in the definitions of the functions and variables they apply to. A
collection of documentation strings is not sufficient as a manual because a good manual is
not organized in that fashion; it is organized in terms of topics of discussion.
For commands to display documentation strings, see section “Help” in The GNU Emacs
Manual. For the conventions for writing documentation strings, see Section D.6 [Documen-
tation Tips], page 862.
To save space, the documentation for preloaded functions and variables (including prim-
itive functions and autoloaded functions) is stored in the file ‘emacs/etc/DOC-version ’—
not inside Emacs. The documentation strings for functions and variables loaded during the
Emacs session from byte-compiled files are stored in those files (see Section 16.3 [Docs and
Compilation], page 217).
The data structure inside Emacs has an integer offset into the file, or a list contain-
ing a file name and an integer, in place of the documentation string. The functions
documentation and documentation-property use that information to fetch the documen-
tation string from the appropriate file; this is transparent to the user.
The ‘emacs/lib-src’ directory contains two utilities that you can use to print nice-
looking hardcopy for the file ‘emacs/etc/DOC-version ’. These are ‘sorted-doc’ and
‘digest-doc’.
The describe-symbols function works like apropos, but provides more information.
(describe-symbols "goal")
temporary-goal-column Variable
Current goal column for vertical motion.
It is the column where point was
at the start of current run of vertical motion commands.
When the ‘track-eol’ feature is doing its job, the value is 9999.
---------- Buffer: *Help* ----------
The asterisk ‘*’ as the first character of a variable’s doc string, as shown above for the
goal-column variable, means that it is a user option; see the description of defvar in
Section 11.5 [Defining Variables], page 139.
doc-directory [Variable]
This variable holds the name of the directory which should contain the file "DOC-
version " that contains documentation strings for built-in and preloaded functions
and variables.
In most cases, this is the same as data-directory. They may be different when you
run Emacs from the directory where you built it, without actually installing it. See
[Definition of data-directory], page 433.
In older Emacs versions, exec-directory was used for this.
\<mapvar >
stands for no text itself. It is used only for a side effect: it specifies mapvar’s
value as the keymap for any following ‘\[command ]’ sequences in this documen-
tation string.
\= quotes the following character and is discarded; thus, ‘\=\[’ puts ‘\[’ into the
output, and ‘\=\=’ puts ‘\=’ into the output.
Please note: Each ‘\’ must be doubled when written in a string in Emacs Lisp.
substitute-command-keys string [Function]
This function scans string for the above special sequences and replaces them by what
they stand for, returning the result as a string. This permits display of documentation
that refers accurately to the user’s own customized key bindings.
Here are examples of the special sequences:
(substitute-command-keys
"To abort recursive edit, type: \\[abort-recursive-edit]")
⇒ "To abort recursive edit, type: C-]"
(substitute-command-keys
"The keys that are defined for the minibuffer here are:
\\{minibuffer-local-must-match-map}")
⇒ "The keys that are defined for the minibuffer here are:
? minibuffer-completion-help
SPC minibuffer-complete-word
TAB minibuffer-complete
C-j minibuffer-complete-and-exit
RET minibuffer-complete-and-exit
C-g abort-recursive-edit
"
(substitute-command-keys
"To abort a recursive edit from the minibuffer, type\
\\<minibuffer-local-must-match-map>\\[abort-recursive-edit].")
⇒ "To abort a recursive edit from the minibuffer, type C-g."
There are other special conventions for the text in documentation strings—for instance,
you can refer to functions, variables, and sections of this manual. See Section D.6 [Docu-
mentation Tips], page 862, for details.
help-map [Variable]
The value of this variable is a local keymap for characters following the Help key, C-h.
help-char [Variable]
The value of this variable is the help character—the character that Emacs recognizes
as meaning Help. By default, its value is 8, which stands for C-h. When Emacs reads
this character, if help-form is a non-nil Lisp expression, it evaluates that expression,
and displays the result in a window if it is a string.
Chapter 24: Documentation 432
Usually the value of help-form is nil. Then the help character has no special meaning
at the level of command input, and it becomes part of a key sequence in the normal
way. The standard key binding of C-h is a prefix key for several general-purpose help
features.
The help character is special after prefix keys, too. If it has no binding as a subcom-
mand of the prefix key, it runs describe-prefix-bindings, which displays a list of
all the subcommands of the prefix key.
help-event-list [Variable]
The value of this variable is a list of event types that serve as alternative “help
characters.” These events are handled just like the event specified by help-char.
help-form [Variable]
If this variable is non-nil, its value is a form to evaluate whenever the character
help-char is read. If evaluating the form produces a string, that string is displayed.
A command that calls read-event or read-char probably should bind help-form
to a non-nil expression while it does input. (The time when you should not do this
is when C-h has some other meaning.) Evaluating this expression should result in a
string that explains what the input is for and how to enter it properly.
Entry to the minibuffer binds this variable to the value of minibuffer-help-form
(see [Definition of minibuffer-help-form], page 302).
prefix-help-command [Variable]
This variable holds a function to print help for a prefix key. The function is called
when the user types a prefix key followed by the help character, and the help character
has no binding after that prefix. The variable’s default value is describe-prefix-
bindings.
describe-prefix-bindings [Function]
This function calls describe-bindings to display a list of all the subcommands of
the prefix key of the most recent key sequence. The prefix described consists of all
but the last event of that key sequence. (The last event is, presumably, the help
character.)
The following two functions are meant for modes that want to provide help without
relinquishing control, such as the “electric” modes. Their names begin with ‘Helper’ to
distinguish them from the ordinary help functions.
Helper-describe-bindings [Command]
This command pops up a window displaying a help buffer containing a listing of all
of the key bindings from both the local and global keymaps. It works by calling
describe-bindings.
Helper-help [Command]
This command provides help for the current mode. It prompts the user in the mini-
buffer with the message ‘Help (Type ? for further options)’, and then provides
assistance in finding out what the key bindings are, and what the mode is intended
for. It returns nil.
This can be customized by changing the map Helper-help-map.
Chapter 24: Documentation 433
data-directory [Variable]
This variable holds the name of the directory in which Emacs finds certain documen-
tation and text files that come with Emacs. In older Emacs versions, exec-directory
was used for this.
25 Files
In Emacs, you can find, create, view, save, and otherwise work with files and file directories.
This chapter describes most of the file-related functions of Emacs Lisp, but a few others are
described in Chapter 27 [Buffers], page 481, and those related to backups and auto-saving
are described in Chapter 26 [Backups and Auto-Saving], page 471.
Many of the file functions take one or more arguments that are file names. A file name
is actually a string. Most of these functions expand file name arguments by calling expand-
file-name, so that ‘~’ is handled correctly, as are relative file names (including ‘../’).
These functions don’t recognize environment variable substitutions such as ‘$HOME’. See
Section 25.8.4 [File Name Expansion], page 457.
When file I/O functions signal Lisp errors, they usually use the condition file-error
(see Section 10.5.3.3 [Handling Errors], page 129). The error message is in most cases
obtained from the operating system, according to locale system-message-locale, and de-
coded using coding system locale-coding-system (see Section 33.12 [Locales], page 660).
Aside from some technical details, the body of the find-file function is basically
equivalent to:
(switch-to-buffer (find-file-noselect filename nil nil wildcards))
(See switch-to-buffer in Section 28.7 [Displaying Buffers], page 506.)
If wildcards is non-nil, which is always true in an interactive call, then find-file
expands wildcard characters in filename and visits all the matching files.
When find-file is called interactively, it prompts for filename in the minibuffer.
find-file-hook [Variable]
The value of this variable is a list of functions to be called after a file is visited. The
file’s local-variables specification (if any) will have been processed before the hooks
are run. The buffer visiting the file is current when the hook functions are run.
This variable is a normal hook. See Section 23.1 [Hooks], page 382.
find-file-not-found-functions [Variable]
The value of this variable is a list of functions to be called when find-file or find-
file-noselect is passed a nonexistent file name. find-file-noselect calls these
functions as soon as it detects a nonexistent file. It calls them in the order of the list,
until one of them returns non-nil. buffer-file-name is already set up.
This is not a normal hook because the values of the functions are used, and in many
cases only some of the functions are called.
(create-file-buffer "foo")
⇒ #<buffer foo>
(create-file-buffer "foo")
⇒ #<buffer foo<2>>
(create-file-buffer "foo")
⇒ #<buffer foo<3>>
This function is used by find-file-noselect. It uses generate-new-buffer (see
Section 27.9 [Creating Buffers], page 492).
Saving a buffer runs several hooks. It also performs format conversion (see Section 25.12
[Format Conversion], page 468), and may save text properties in “annotations” (see Sec-
tion 32.19.7 [Saving Properties], page 626).
write-file-functions [Variable]
The value of this variable is a list of functions to be called before writing out a buffer
to its visited file. If one of them returns non-nil, the file is considered already written
and the rest of the functions are not called, nor is the usual code for writing the file
executed.
If a function in write-file-functions returns non-nil, it is responsible for making
a backup file (if that is appropriate). To do so, execute the following code:
(or buffer-backed-up (backup-buffer))
Chapter 25: Files 439
You might wish to save the file modes value returned by backup-buffer and use that
(if non-nil) to set the mode bits of the file that you write. This is what save-buffer
normally does. See Section 26.1.1 [Making Backup Files], page 471.
The hook functions in write-file-functions are also responsible for encoding the
data (if desired): they must choose a suitable coding system and end-of-line conversion
(see Section 33.10.3 [Lisp and Coding Systems], page 650), perform the encoding (see
Section 33.10.7 [Explicit Encoding], page 656), and set last-coding-system-used to
the coding system that was used (see Section 33.10.2 [Encoding and I/O], page 649).
If you set this hook locally in a buffer, it is assumed to be associated with the file or
the way the contents of the buffer were obtained. Thus the variable is marked as a
permanent local, so that changing the major mode does not alter a buffer-local value.
On the other hand, calling set-visited-file-name will reset it. If this is not what
you want, you might like to use write-contents-functions instead.
Even though this is not a normal hook, you can use add-hook and remove-hook to
manipulate the list. See Section 23.1 [Hooks], page 382.
write-contents-functions [Variable]
This works just like write-file-functions, but it is intended for hooks that pertain
to the buffer’s contents, not to the particular visited file or its location. Such hooks
are usually set up by major modes, as buffer-local bindings for this variable. This
variable automatically becomes buffer-local whenever it is set; switching to a new
major mode always resets this variable, but calling set-visited-file-name does
not.
If any of the functions in this hook returns non-nil, the file is considered already
written and the rest are not called and neither are the functions in write-file-
functions.
before-save-hook [User Option]
This normal hook runs before a buffer is saved in its visited file, regardless of whether
that is done normally or by one of the hooks described above. For instance, the
‘copyright.el’ program uses this hook to make sure the file you are saving has the
current year in its copyright notice.
after-save-hook [User Option]
This normal hook runs after a buffer has been saved in its visited file. One use of this
hook is in Fast Lock mode; it uses this hook to save the highlighting information in
a cache file.
file-precious-flag [User Option]
If this variable is non-nil, then save-buffer protects against I/O errors while saving
by writing the new file to a temporary name instead of the name it is supposed to
have, and then renaming it to the intended name after it is clear there are no errors.
This procedure prevents problems such as a lack of disk space from resulting in an
invalid file.
As a side effect, backups are necessarily made by copying. See Section 26.1.2 [Rename
or Copy], page 473. Yet, at the same time, saving a precious file always breaks all
hard links between the file you save and other file names.
Some modes give this variable a non-nil buffer-local value in particular buffers.
Chapter 25: Files 440
See also the function set-visited-file-name (see Section 27.4 [Buffer File Name],
page 485).
If visit is a string, it specifies the file name to visit. This way, you can write the data
to one file (filename) while recording the buffer as visiting another file (visit). The
argument visit is used in the echo area message and also for file locking; visit is stored
in buffer-file-name. This feature is used to implement file-precious-flag; don’t
use it yourself unless you really know what you’re doing.
The optional argument lockname, if non-nil, specifies the file name to use for purposes
of locking and unlocking, overriding filename and visit for that purpose.
The function write-region converts the data which it writes to the appropriate file
formats specified by buffer-file-format. See Section 25.12 [Format Conversion],
page 468. It also calls the functions in the list write-region-annotate-functions;
see Section 32.19.7 [Saving Properties], page 626.
Normally, write-region displays the message ‘Wrote filename ’ in the echo area. If
visit is neither t nor nil nor a string, then this message is inhibited. This feature is
useful for programs that use files for internal purposes, files that the user does not
need to know about.
and GNU/Linux, this is true if the file exists and you have execute permission on the
containing directories, regardless of the protection of the file itself.)
If the file does not exist, or if fascist access control policies prevent you from finding
the attributes of the file, this function returns nil.
Directories are files, so file-exists-p returns t when given a directory name. How-
ever, symbolic links are treated specially; file-exists-p returns t for a symbolic
link name only if the target file exists.
file-readable-p filename [Function]
This function returns t if a file named filename exists and you can read it. It returns
nil otherwise.
(file-readable-p "files.texi")
⇒ t
(file-exists-p "/usr/spool/mqueue")
⇒ t
(file-readable-p "/usr/spool/mqueue")
⇒ nil
file-executable-p filename [Function]
This function returns t if a file named filename exists and you can execute it. It
returns nil otherwise. On Unix and GNU/Linux, if the file is a directory, execute
permission means you can check the existence and attributes of files inside the direc-
tory, and open those files if their modes permit.
file-writable-p filename [Function]
This function returns t if the file filename can be written or created by you, and nil
otherwise. A file is writable if the file exists and you can write it. It is creatable
if it does not exist, but the specified directory does exist and you can write in that
directory.
In the third example below, ‘foo’ is not writable because the parent directory does
not exist, even though the user could create such a directory.
(file-writable-p "~/foo")
⇒ t
(file-writable-p "/foo")
⇒ nil
(file-writable-p "~/no-such-dir/foo")
⇒ nil
file-accessible-directory-p dirname [Function]
This function returns t if you have permission to open existing files in the directory
whose name as a file is dirname; otherwise (or if there is no such directory), it returns
nil. The value of dirname may be either a directory name (such as ‘/foo/’) or the
file name of a file which is a directory (such as ‘/foo’, without the final slash).
Example: after the following,
(file-accessible-directory-p "/foo")
⇒ nil
we can deduce that any attempt to read a file in ‘/foo/’ will give an error.
Chapter 25: Files 445
The next two functions recursively follow symbolic links at all levels for filename.
25.6.3 Truenames
The truename of a file is the name that you get by following symbolic links at all levels until
none remain, then simplifying away ‘.’ and ‘..’ appearing as name components. This results
in a sort of canonical name for the file. A file does not always have a unique truename;
the number of distinct truenames a file has is equal to the number of hard links to the file.
However, truenames are useful because they eliminate symbolic links as a cause of name
variation.
% ls -l diffs
-rw-rw-rw- 1 lewis 0 3063 Oct 30 16:00 diffs
If the filename argument to the next two functions is a symbolic link, then these function
do not replace it with its target. However, they both recursively follow symbolic links at
all levels of parent directories.
Chapter 25: Files 448
(file-nlinks "foo")
⇒ 2
(file-nlinks "doesnt-exist")
⇒ nil
give enough information to distinguish any two files on the system—no two files
can have the same values for both of these numbers.
For example, here are the file attributes for ‘files.texi’:
(file-attributes "files.texi" ’string)
⇒ (nil 1 "lh" "users"
(8489 20284)
(8489 20284)
(8489 20285)
14906 "-rw-rw-rw-"
nil 129500 -32252)
and here is how the result is interpreted:
nil is neither a directory nor a symbolic link.
1 has only one name (the name ‘files.texi’ in the current default direc-
tory).
"lh" is owned by the user with name "lh".
"users" is in the group with name "users".
(8489 20284)
was last accessed on Aug 19 00:09.
(8489 20284)
was last modified on Aug 19 00:09.
(8489 20285)
last had its inode changed on Aug 19 00:09.
14906 is 14906 bytes long. (It may not contain 14906 characters, though, if
some of the bytes belong to multibyte sequences.)
"-rw-rw-rw-"
has a mode of read and write access for the owner, group, and world.
nil would retain the same GID if it were recreated.
129500 has an inode number of 129500.
-32252 is on file system number -32252.
file name of the file (see Section 25.8.2 [Relative File Names], page 455); otherwise it
returns nil.
The optional argument suffixes gives the list of file-name suffixes to append to filename
when searching. locate-file tries each possible directory with each of these suffixes.
If suffixes is nil, or (""), then there are no suffixes, and filename is used only as-is.
Typical values of suffixes are exec-suffixes (see Section 37.1 [Subprocess Creation],
page 705), load-suffixes, load-file-rep-suffixes and the return value of the
function get-load-suffixes (see Section 15.2 [Load Suffixes], page 203).
Typical values for path are exec-path (see Section 37.1 [Subprocess Creation],
page 705) when looking for executable programs or load-path (see Section 15.3
[Library Search], page 203) when looking for Lisp files. If filename is absolute, path
has no effect, but the suffixes in suffixes are still tried.
The optional argument predicate, if non-nil, specifies the predicate function to use
for testing whether a candidate file is suitable. The predicate function is passed the
candidate file name as its single argument. If predicate is nil or unspecified, locate-
file uses file-readable-p as the default predicate. Useful non-default predicates
include file-executable-p, file-directory-p, and other predicates described in
Section 25.6.2 [Kinds of Files], page 445.
For compatibility, predicate can also be one of the symbols executable, readable,
writable, exists, or a list of one or more of these symbols.
executable-find program [Function]
This function searches for the executable file of the named program and returns the
full absolute name of the executable, including its file-name extensions, if any. It
returns nil if the file is not found. The functions searches in all the directories in
exec-path and tries all the file-name extensions in exec-suffixes.
Now we create a hard link, by calling add-name-to-file, then list the files again.
This shows two names for one file, ‘foo’ and ‘foo2’.
(add-name-to-file "foo" "foo2")
⇒ nil
% ls -li fo*
81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo2
84302 -rw-rw-rw- 1 rms 24 Aug 18 20:31 foo3
Finally, we evaluate the following:
(add-name-to-file "foo" "foo3" t)
and list the files again. Now there are three names for one file: ‘foo’, ‘foo2’, and
‘foo3’. The old contents of ‘foo3’ are lost.
(add-name-to-file "foo1" "foo3")
⇒ nil
% ls -li fo*
81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo2
81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo3
This function is meaningless on operating systems where multiple names for one file
are not allowed. Some systems implement multiple names by copying the file instead.
See also file-nlinks in Section 25.6.4 [File Attributes], page 447.
default-file-modes [Function]
This function returns the current default protection value.
On MS-DOS, there is no such thing as an “executable” file mode bit. So Emacs considers
a file executable if its name ends in one of the standard executable extensions, such as ‘.com’,
‘.bat’, ‘.exe’, and some others. Files that begin with the Unix-standard ‘#!’ signature,
such as shell and Perl scripts, are also considered as executable files. This is reflected in the
values returned by file-modes and file-attributes. Directories are also reported with
executable bit set, for compatibility with Unix.
Given a possibly relative file name, you can convert it to an absolute name using expand-
file-name (see Section 25.8.4 [File Name Expansion], page 457). This function converts
absolute file names to relative names:
Given a directory name, you can combine it with a relative file name using concat:
(concat dirname relfile )
Be sure to verify that the file name is relative before doing that. If you use an absolute file
name, the results could be syntactically invalid or refer to the wrong file.
If you want to use a directory file name in making such a combination, you must first
convert it to a directory name using file-name-as-directory:
(concat (file-name-as-directory dirfile ) relfile )
Don’t try concatenating a slash by hand, as in
Chapter 25: Files 457
;;; Wrong!
(concat dirfile "/" relfile )
because this is not portable. Always use file-name-as-directory.
Directory name abbreviations are useful for directories that are normally accessed
through symbolic links. Sometimes the users recognize primarily the link’s name as “the
name” of the directory, and find it annoying to see the directory’s “real” name. If you
define the link name as an abbreviation for the “real” name, Emacs shows users the
abbreviation instead.
directory-abbrev-alist [Variable]
The variable directory-abbrev-alist contains an alist of abbreviations to use for
file directories. Each element has the form (from . to ), and says to replace from
with to when it appears in a directory name. The from string is actually a regular
expression; it should always start with ‘^’. The to string should be an ordinary
absolute directory name. Do not use ‘~’ to stand for a home directory in that string.
The function abbreviate-file-name performs these substitutions.
You can set this variable in ‘site-init.el’ to describe the abbreviations appropriate
for your site.
Here’s an example, from a system on which file system ‘/home/fsf’ and so on are
normally accessed through symbolic links named ‘/fsf’ and so on.
(("^/home/fsf" . "/fsf")
("^/home/gp" . "/gp")
("^/home/gd" . "/gd"))
default-directory [Variable]
The value of this buffer-local variable is the default directory for the current buffer.
It should be an absolute directory name; it may start with ‘~’. This variable is
buffer-local in every buffer.
expand-file-name uses the default directory when its second argument is nil.
Aside from VMS, the value is always a string ending with a slash.
default-directory
⇒ "/user/lewis/manual/"
To prevent conflicts among different libraries running in the same Emacs, each Lisp
program that uses make-temp-file should have its own prefix. The number added
to the end of prefix distinguishes between the same application running in different
Emacs jobs. Additional added characters permit a large number of distinct names
even in one Emacs job.
The default directory for temporary files is controlled by the variable temporary-file-
directory. This variable gives the user a uniform way to specify the directory for all
temporary files. Some programs use small-temporary-file-directory instead, if that is
non-nil. To use it, you should expand the prefix against the proper directory before calling
make-temp-file.
In older Emacs versions where make-temp-file does not exist, you should use make-
temp-name instead:
(make-temp-name
(expand-file-name name-of-application
temporary-file-directory))
make-temp-name string [Function]
This function generates a string that can be used as a unique file name. The name
starts with string, and has several random characters appended to it, which are dif-
ferent in each Emacs job. It is like make-temp-file except that it just constructs
a name, and does not create a file. Another difference is that string should be an
absolute file name. On MS-DOS, this function can truncate the string prefix to fit
into the 8+3 file-name limits.
temporary-file-directory [Variable]
This variable specifies the directory name for creating temporary files. Its value should
be a directory name (see Section 25.8.3 [Directory Names], page 456), but it is good
for Lisp programs to cope if the value is a directory’s file name instead. Using the
value as the second argument to expand-file-name is a good way to achieve that.
The default value is determined in a reasonable way for your operating system; it
is based on the TMPDIR, TMP and TEMP environment variables, with a fall-back to a
system-dependent name if none of these variables is defined.
Even if you do not use make-temp-file to create the temporary file, you should still
use this variable to decide which directory to put the file in. However, if you expect
the file to be small, you should use small-temporary-file-directory first if that
is non-nil.
small-temporary-file-directory [Variable]
This variable specifies the directory name for creating certain temporary files, which
are likely to be small.
If you want to write a temporary file which is likely to be small, you should compute
the directory like this:
(make-temp-file
(expand-file-name prefix
(or small-temporary-file-directory
temporary-file-directory)))
Chapter 25: Files 461
The recommended way to specify a standard file name in a Lisp program is to choose
a name which fits the conventions of GNU and Unix systems, usually with a nondirectory
part that starts with a period, and pass it to convert-standard-filename instead of using
it directly. Here is an example from the completion package:
(defvar save-completions-file-name
(convert-standard-filename "~/.completions")
"*The file name to save completions to.")
On GNU and Unix systems, and on some other systems as well, convert-standard-
filename returns its argument unchanged. On some other systems, it alters the name to
fit the system’s conventions.
For example, on MS-DOS the alterations made by this function include converting a
leading ‘.’ to ‘_’, converting a ‘_’ in the middle of the name to ‘.’ if there is no other ‘.’,
inserting a ‘.’ after eight characters if there is none, and truncating to three characters after
the ‘.’. (It makes other changes as well.) Thus, ‘.abbrev_defs’ becomes ‘_abbrev.def’,
and ‘.completions’ becomes ‘_complet.ion’.
If full-directory-p is non-nil, that means the directory listing is expected to show the
full contents of a directory. You should specify t when file is a directory and switches
do not contain ‘-d’. (The ‘-d’ option to ls says to describe a directory itself as a file,
rather than showing its contents.)
On most systems, this function works by running a directory listing program whose
name is in the variable insert-directory-program. If wildcard is non-nil, it also
runs the shell specified by shell-file-name, to expand the wildcards.
MS-DOS and MS-Windows systems usually lack the standard Unix program ls, so
this function emulates the standard Unix program ls with Lisp code.
As a technical detail, when switches contains the long ‘--dired’ option, insert-
directory treats it specially, for the sake of dired. However, the normally equivalent
short ‘-D’ option is just passed on to insert-directory-program, as any other op-
tion.
insert-directory-program [Variable]
This variable’s value is the program to run to generate a directory listing for the
function insert-directory. It is ignored on systems which generate the listing with
Lisp code.
(regexp . handler )
All the Emacs primitives for file access and file name transformation check the given file
name against file-name-handler-alist. If the file name matches regexp, the primitives
handle that file by calling handler.
The first argument given to handler is the name of the primitive, as a symbol; the
remaining arguments are the arguments that were passed to that primitive. (The first of
these arguments is most often the file name itself.) For example, if you do this:
(file-exists-p filename )
and filename has handler handler, then handler is called like this:
(funcall handler ’file-exists-p filename )
When a function takes two or more arguments that must be file names, it checks each
of those names for a handler. For example, if you do this:
(expand-file-name filename dirname )
then it checks for a handler for filename and then for a handler for dirname. In either case,
the handler is called like this:
(funcall handler ’expand-file-name filename dirname )
The handler then needs to figure out whether to handle filename or dirname.
If the specified file name matches more than one handler, the one whose match starts
last in the file name gets precedence. This rule is chosen so that handlers for jobs such as
uncompression are handled first, before handlers for jobs such as remote file access.
Here are the operations that a magic file name handler gets to handle:
access-file, add-name-to-file,
byte-compiler-base-file-name,
copy-file, delete-directory,
delete-file,
diff-latest-backup-file,
directory-file-name,
directory-files,
directory-files-and-attributes,
dired-call-process,
dired-compress-file, dired-uncache,
expand-file-name,
file-accessible-directory-p,
file-attributes,
file-directory-p,
file-executable-p, file-exists-p,
file-local-copy, file-remote-p,
file-modes, file-name-all-completions,
file-name-as-directory,
file-name-completion,
file-name-directory,
file-name-nondirectory,
file-name-sans-versions, file-newer-than-file-p,
file-ownership-preserved-p,
Chapter 25: Files 466
But if the handler that would be used for them has a non-nil safe-magic property, the
‘/:’ is not added.
A file name handler can have an operations property to declare which operations it
handles in a nontrivial way. If this property has a non-nil value, it should be a list of
operations; then only those operations will call the handler. This avoids inefficiency, but
its main purpose is for autoloaded handler functions, so that they won’t be loaded except
when they have real work to do.
Simply deferring all operations to the usual primitives does not work. For instance, if
the file name handler applies to file-exists-p, then it must handle load itself, because
the usual load code won’t work properly in that case. However, if the handler uses the
operations property to say it doesn’t handle file-exists-p, then it need not handle load
nontrivially.
inhibit-file-name-handlers [Variable]
This variable holds a list of handlers whose use is presently inhibited for a certain
operation.
inhibit-file-name-operation [Variable]
The operation for which certain handlers are presently inhibited.
find-file-name-handler file operation [Function]
This function returns the handler function for file name file, or nil if there is none.
The argument operation should be the operation to be performed on the file—the
value you will pass to the handler as its first argument when you call it. If opera-
tion equals inhibit-file-name-operation, or if it is not found in the operations
property of the handler, this function returns nil.
file-local-copy filename [Function]
This function copies file filename to an ordinary non-magic file on the local machine, if
it isn’t on the local machine already. Magic file names should handle the file-local-
copy operation if they refer to files on other machines. A magic file name that is used
for other purposes than remote file access should not handle file-local-copy; then
this function will treat the file as local.
If filename is local, whether magic or not, this function does nothing and returns nil.
Otherwise it returns the file name of the local copy file.
file-remote-p filename [Function]
This function tests whether filename is a remote file. If filename is local (not remote),
the return value is nil. If filename is indeed remote, the return value is a string that
identifies the remote system.
This identifier string can include a host name and a user name, as well as characters
designating the method used to access the remote system. For example, the remote
identifier string for the filename /ssh:user@host:/some/file is /ssh:user@host:.
If file-remote-p returns the same identifier for two different filenames, that means
they are stored on the same file system and can be accessed locally with respect to
each other. This means, for example, that it is possible to start a remote process
accessing both files at the same time. Implementors of file handlers need to ensure
this principle is valid.
Chapter 25: Files 468
format-alist [Variable]
This list contains one format definition for each defined file format.
The return value is like what insert-file-contents returns: a list of the absolute
file name and the length of the data inserted (after conversion).
The argument format is a list of format names. If format is nil, no conversion takes
place. Interactively, typing just RET for format specifies nil.
buffer-auto-save-file-format [Variable]
This variable specifies the format to use for auto-saving. Its value is a list of format
names, just like the value of buffer-file-format; however, it is used instead of
buffer-file-format for writing auto-save files. If the value is t, the default, auto-
saving uses the same format as a regular save in the same buffer. This variable is
always buffer-local in all buffers.
Chapter 26: Backups and Auto-Saving 471
buffer-backed-up [Variable]
This buffer-local variable says whether this buffer’s file has been backed up on account
of this buffer. If it is non-nil, the backup file has been written. Otherwise, the
file should be backed up when it is next saved (if backups are enabled). This is a
permanent local; kill-all-local-variables does not alter it.
(add-hook ’rmail-mode-hook
(function (lambda ()
(make-local-variable
’make-backup-files)
(setq make-backup-files nil))))
backup-enable-predicate [Variable]
This variable’s value is a function to be called on certain occasions to decide whether
a file should have backup files. The function receives one argument, an absolute file
name to consider. If the function returns nil, backups are disabled for that file.
Otherwise, the other variables in this section say whether and how to make backups.
The default value is normal-backup-enable-predicate, which checks for files in
temporary-file-directory and small-temporary-file-directory.
backup-inhibited [Variable]
If this variable is non-nil, backups are inhibited. It records the result of testing
backup-enable-predicate on the visited file name. It can also coherently be used
by other mechanisms that inhibit backups based on which file is visited. For example,
VC sets this variable non-nil to prevent making backups for files managed with a
version control system.
This is a permanent local, so that changing the major mode does not lose its value.
Major modes should not set this variable—they should set make-backup-files in-
stead.
backup-directory-alist [Variable]
This variable’s value is an alist of filename patterns and backup directory names.
Each element looks like
(regexp . directory )
Backups of files with names matching regexp will be made in directory. directory
may be relative or absolute. If it is absolute, so that all matching files are backed up
into the same directory, the file names in this directory will be the full name of the
file backed up with all directory separators changed to ‘!’ to prevent clashes. This
will not work correctly if your filesystem truncates the resulting name.
For the common case of all backups going into one directory, the alist should contain
a single element pairing ‘"."’ with the appropriate directory name.
If this variable is nil, or it fails to match a filename, the backup is made in the
original file’s directory.
On MS-DOS filesystems without long names this variable is always ignored.
make-backup-file-name-function [Variable]
This variable’s value is a function to use for making backups instead of the default
make-backup-file-name. A value of nil gives the default make-backup-file-name
behavior. See Section 26.1.4 [Naming Backup Files], page 474.
This could be buffer-local to do something special for specific files. If you define it,
you may need to change backup-file-name-p and file-name-sans-versions too.
Chapter 26: Backups and Auto-Saving 473
The use of numbered backups ultimately leads to a large number of backup versions,
which must then be deleted. Emacs can do this automatically or it can ask the user whether
to delete them.
If there are backups numbered 1, 2, 3, 5, and 7, and both of these variables have the
value 2, then the backups numbered 1 and 2 are kept as old versions and those numbered
5 and 7 are kept as new versions; backup version 3 is excess. The function find-backup-
file-name (see Section 26.1.4 [Backup Names], page 474) is responsible for determining
which backup versions to delete, but does not delete them itself.
(make-backup-file-name "backups.texi")
⇒ ".backups.texi~"
Some parts of Emacs, including some Dired commands, assume that backup file names
end with ‘~’. If you do not follow that convention, it will not cause serious problems,
but these commands may give less-than-desirable results.
In this example, the value says that ‘~rms/foo.~5~’ is the name to use for the new
backup file, and ‘~rms/foo.~3~’ is an “excess” version that the caller should consider
deleting now.
(find-backup-file-name "~rms/foo")
⇒ ("~rms/foo.~5~" "~rms/foo.~3~")
26.2 Auto-Saving
Emacs periodically saves all files that you are visiting; this is called auto-saving. Auto-
saving prevents you from losing more than a limited amount of work if the system crashes.
By default, auto-saves happen every 300 keystrokes, or after around 30 seconds of idle time.
See section “Auto-Saving: Protection Against Disasters” in The GNU Emacs Manual, for
information on auto-save for users. Here we describe the functions used to implement
auto-saving and the variables that control them.
buffer-auto-save-file-name [Variable]
This buffer-local variable is the name of the file used for auto-saving the current
buffer. It is nil if the buffer should not be auto-saved.
buffer-auto-save-file-name
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
This function exists so that you can customize it if you wish to change the naming
convention for auto-save files. If you redefine it, be sure to redefine the function
make-auto-save-file-name correspondingly.
make-auto-save-file-name [Function]
This function returns the file name to use for auto-saving the current buffer. This
is just the file name with hash marks (‘#’) prepended and appended to it. This
function does not look at the variable auto-save-visited-file-name (described
below); callers of this function should check that variable first.
(make-auto-save-file-name)
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
Here is a simplified version of the standard definition of this function:
(defun make-auto-save-file-name ()
"Return file name to use for auto-saves \
of current buffer.."
(if buffer-file-name
(concat
(file-name-directory buffer-file-name)
"#"
(file-name-nondirectory buffer-file-name)
"#")
(expand-file-name
(concat "#%" (buffer-name) "#"))))
This exists as a separate function so that you can redefine it to customize the nam-
ing convention for auto-save files. Be sure to change auto-save-file-name-p in a
corresponding way.
auto-save-visited-file-name [User Option]
If this variable is non-nil, Emacs auto-saves buffers in the files they are visiting. That
is, the auto-save is done in the same file that you are editing. Normally, this variable
is nil, so auto-save files have distinct names that are created by make-auto-save-
file-name.
When you change the value of this variable, the new value does not take effect in
an existing buffer until the next time auto-save mode is reenabled in it. If auto-
save mode is already enabled, auto-saves continue to go in the same file name until
auto-save-mode is called again.
recent-auto-save-p [Function]
This function returns t if the current buffer has been auto-saved since the last time
it was read in or saved.
set-buffer-auto-saved [Function]
This function marks the current buffer as auto-saved. The buffer will not be auto-
saved again until the buffer text is changed again. The function returns nil.
auto-save-interval [User Option]
The value of this variable specifies how often to do auto-saving, in terms of number
of input events. Each time this many additional input events are read, Emacs does
Chapter 26: Backups and Auto-Saving 478
auto-saving for all buffers in which that is enabled. Setting this to zero disables
autosaving based on the number of characters typed.
auto-save-timeout [User Option]
The value of this variable is the number of seconds of idle time that should cause
auto-saving. Each time the user pauses for this long, Emacs does auto-saving for all
buffers in which that is enabled. (If the current buffer is large, the specified timeout
is multiplied by a factor that increases as the size increases; for a million-byte buffer,
the factor is almost 4.)
If the value is zero or nil, then auto-saving is not done as a result of idleness, only
after a certain number of input events as specified by auto-save-interval.
auto-save-hook [Variable]
This normal hook is run whenever an auto-save is about to happen.
auto-save-default [User Option]
If this variable is non-nil, buffers that are visiting files have auto-saving enabled by
default. Otherwise, they do not.
do-auto-save &optional no-message current-only [Command]
This function auto-saves all buffers that need to be auto-saved. It saves all buffers for
which auto-saving is enabled and that have been changed since the previous auto-save.
If any buffers are auto-saved, do-auto-save normally displays a message saying
‘Auto-saving...’ in the echo area while auto-saving is going on. However, if no-
message is non-nil, the message is inhibited.
If current-only is non-nil, only the current buffer is auto-saved.
delete-auto-save-file-if-necessary &optional force [Function]
This function deletes the current buffer’s auto-save file if delete-auto-save-files
is non-nil. It is called every time a buffer is saved.
Unless force is non-nil, this function only deletes the file if it was written by the
current Emacs session since the last true save.
delete-auto-save-files [User Option]
This variable is used by the function delete-auto-save-file-if-necessary. If it
is non-nil, Emacs deletes auto-save files when a true save is done (in the visited file).
This saves disk space and unclutters your directory.
rename-auto-save-file [Function]
This function adjusts the current buffer’s auto-save file name if the visited file name
has changed. It also renames an existing auto-save file, if it was made in the current
Emacs session. If the visited file name has not changed, this function does nothing.
buffer-saved-size [Variable]
The value of this buffer-local variable is the length of the current buffer, when it was
last read in, saved, or auto-saved. This is used to detect a substantial decrease in
size, and turn off auto-saving in response.
If it is −1, that means auto-saving is temporarily shut off in this buffer due to a
substantial decrease in size. Explicitly saving the buffer stores a positive value in this
Chapter 26: Backups and Auto-Saving 479
variable, thus reenabling auto-saving. Turning auto-save mode off or on also updates
this variable, so that the substantial decrease in size is forgotten.
auto-save-list-file-name [Variable]
This variable (if non-nil) specifies a file for recording the names of all the auto-save
files. Each time Emacs does auto-saving, it writes two lines into this file for each
buffer that has auto-saving enabled. The first line gives the name of the visited file
(it’s empty if the buffer has none), and the second gives the name of the auto-save
file.
When Emacs exits normally, it deletes this file; if Emacs crashes, you can look in the
file to find all the auto-save files that might contain work that was otherwise lost.
The recover-session command uses this file to find them.
The default name for this file specifies your home directory and starts with ‘.saves-’.
It also contains the Emacs process ID and the host name.
auto-save-list-file-prefix [Variable]
After Emacs reads your init file, it initializes auto-save-list-file-name (if you
have not already set it non-nil) based on this prefix, adding the host name and
process ID. If you set this to nil in your init file, then Emacs does not initialize
auto-save-list-file-name.
26.3 Reverting
If you have made extensive changes to a file and then change your mind about them, you
can get rid of them by reading in the previous version of the file with the revert-buffer
command. See section “Reverting a Buffer” in The GNU Emacs Manual.
revert-buffer &optional ignore-auto noconfirm preserve-modes [Command]
This command replaces the buffer text with the text of the visited file on disk. This
action undoes all changes since the file was visited or saved.
By default, if the latest auto-save file is more recent than the visited file, and the
argument ignore-auto is nil, revert-buffer asks the user whether to use that auto-
save instead. When you invoke this command interactively, ignore-auto is t if there is
no numeric prefix argument; thus, the interactive default is not to check the auto-save
file.
Normally, revert-buffer asks for confirmation before it changes the buffer; but if
the argument noconfirm is non-nil, revert-buffer does not ask for confirmation.
Normally, this command reinitializes the buffer’s major and minor modes using
normal-mode. But if preserve-modes is non-nil, the modes remain unchanged.
Reverting tries to preserve marker positions in the buffer by using the replacement
feature of insert-file-contents. If the buffer contents and the file contents are
identical before the revert operation, reverting preserves all the markers. If they are
not identical, reverting does change the buffer; in that case, it preserves the markers
in the unchanged text (if any) at the beginning and end of the buffer. Preserving any
additional markers would be problematical.
You can customize how revert-buffer does its work by setting the variables described
in the rest of this section.
Chapter 26: Backups and Auto-Saving 480
Some major modes customize revert-buffer by making buffer-local bindings for these
variables:
revert-buffer-function [Variable]
The value of this variable is the function to use to revert this buffer. If non-nil, it
should be a function with two optional arguments to do the work of reverting. The
two optional arguments, ignore-auto and noconfirm, are the arguments that revert-
buffer received. If the value is nil, reverting works the usual way.
Modes such as Dired mode, in which the text being edited does not consist of a
file’s contents but can be regenerated in some other fashion, can give this variable a
buffer-local value that is a function to regenerate the contents.
revert-buffer-insert-file-contents-function [Variable]
The value of this variable, if non-nil, specifies the function to use to insert the
updated contents when reverting this buffer. The function receives two arguments:
first the file name to use; second, t if the user has asked to read the auto-save file.
The reason for a mode to set this variable instead of revert-buffer-function is
to avoid duplicating or replacing the rest of what revert-buffer does: asking for
confirmation, clearing the undo list, deciding the proper major mode, and running
the hooks listed below.
before-revert-hook [Variable]
This normal hook is run by revert-buffer before inserting the modified contents—
but only if revert-buffer-function is nil.
after-revert-hook [Variable]
This normal hook is run by revert-buffer after inserting the modified contents—but
only if revert-buffer-function is nil.
Chapter 27: Buffers 481
27 Buffers
A buffer is a Lisp object containing text to be edited. Buffers are used to hold the contents
of files that are being visited; there may also be buffers that are not visiting files. While
several buffers may exist at one time, only one buffer is designated the current buffer at
any time. Most editing commands act on the contents of the current buffer. Each buffer,
including the current buffer, may or may not be displayed in any windows.
the way to switch visibly to a different buffer so that the user can edit it. For that, you
must use the functions described in Section 28.7 [Displaying Buffers], page 506.
Warning: Lisp functions that change to a different current buffer should not depend on
the command loop to set it back afterwards. Editing commands written in Emacs Lisp can
be called from other programs as well as from the command loop; it is convenient for the
caller if the subroutine does not change which buffer is current (unless, of course, that is
the subroutine’s purpose). Therefore, you should normally use set-buffer within a save-
current-buffer or save-excursion (see Section 30.3 [Excursions], page 568) form that
will restore the current buffer when your function is done. Here is an example, the code for
the command append-to-buffer (with the documentation string abridged):
(defun append-to-buffer (buffer start end)
"Append to specified buffer the text of the region.
..."
(interactive "BAppend to buffer: \nr")
(let ((oldbuf (current-buffer)))
(save-current-buffer
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
This function binds a local variable to record the current buffer, and then save-current-
buffer arranges to make it current again. Next, set-buffer makes the specified buffer
current. Finally, insert-buffer-substring copies the string from the original current
buffer to the specified (and now current) buffer.
If the buffer appended to happens to be displayed in some window, the next redisplay
will show how its text has changed. Otherwise, you will not see the change immediately on
the screen. The buffer becomes current temporarily during the execution of the command,
but this does not cause it to be displayed.
If you make local bindings (with let or function arguments) for a variable that may
also have buffer-local bindings, make sure that the same buffer is current at the beginning
and at the end of the local binding’s scope. Otherwise you might bind it in one buffer
and unbind it in another! There are two ways to do this. In simple cases, you may see
that nothing ever changes the current buffer within the scope of the binding. Otherwise,
use save-current-buffer or save-excursion to make sure that the buffer current at the
beginning is current again whenever the variable is unbound.
Do not rely on using set-buffer to change the current buffer back, because that won’t
do the job if a quit happens while the wrong buffer is current. Here is what not to do:
(let (buffer-read-only
(obuf (current-buffer)))
(set-buffer ...)
...
(set-buffer obuf))
Using save-current-buffer, as shown here, handles quitting, errors, and throw, as well
as ordinary evaluation.
Chapter 27: Buffers 483
(let (buffer-read-only)
(save-current-buffer
(set-buffer ...)
...))
current-buffer [Function]
This function returns the current buffer.
(current-buffer)
⇒ #<buffer buffers.texi>
See also the function get-buffer-create in Section 27.9 [Creating Buffers], page 492.
generate-new-buffer-name starting-name &optional ignore [Function]
This function returns a name that would be unique for a new buffer—but does not
create the buffer. It starts with starting-name, and produces a name not currently in
use for any buffer by appending a number inside of ‘<...>’. It starts at 2 and keeps
incrementing the number until it is not the name of an existing buffer.
If the optional second argument ignore is non-nil, it should be a string, a potential
buffer name. It means to consider that potential buffer acceptable, if it is tried, even
it is the name of an existing buffer (which would normally be rejected). Thus, if
buffers named ‘foo’, ‘foo<2>’, ‘foo<3>’ and ‘foo<4>’ exist,
(generate-new-buffer-name "foo")
⇒ "foo<5>"
(generate-new-buffer-name "foo" "foo<3>")
⇒ "foo<3>"
(generate-new-buffer-name "foo" "foo<6>")
⇒ "foo<5>"
See the related function generate-new-buffer in Section 27.9 [Creating Buffers],
page 492.
buffer-file-number [Variable]
This buffer-local variable holds the file number and directory device number of the
file visited in the current buffer, or nil if no file or a nonexistent file is visited. It is
a permanent local, unaffected by kill-all-local-variables.
The value is normally a list of the form (filenum devnum ). This pair of numbers
uniquely identifies the file among all files accessible on the system. See the function
file-attributes, in Section 25.6.4 [File Attributes], page 447, for more information
about them.
If buffer-file-name is the name of a symbolic link, then both numbers refer to the
recursive target.
Normally, this function asks the user for confirmation if there already is a buffer
visiting filename. If no-query is non-nil, that prevents asking this question. If there
already is a buffer visiting filename, and the user confirms or query is non-nil, this
function makes the new buffer name unique by appending a number inside of ‘<...>’
to filename.
If along-with-file is non-nil, that means to assume that the former visited file has
been renamed to filename. In this case, the command does not change the buffer’s
modified flag, nor the buffer’s recorded last file modification time as reported by
visited-file-modtime (see Section 27.6 [Modification Time], page 488). If along-
with-file is nil, this function clears the recorded last file modification time, after
which visited-file-modtime returns zero.
When the function set-visited-file-name is called interactively, it prompts for
filename in the minibuffer.
list-buffers-directory [Variable]
This buffer-local variable specifies a string to display in a buffer listing where the
visited file name would go, for buffers that don’t have a visited file name. Dired
buffers use this variable.
visited-file-modtime [Function]
This function returns the current buffer’s recorded last file modification time, as a
list of the form (high low ). (This is the same format that file-attributes uses
to return time values; see Section 25.6.4 [File Attributes], page 447.)
If the buffer has no recorded last modification time, this function returns zero. This
case occurs, for instance, if the buffer is not visiting a file or if the time has been
explicitly cleared by clear-visited-file-modtime. Note, however, that visited-
file-modtime returns a list for some non-file buffers too. For instance, in a Dired
buffer listing a directory, it returns the last modification time of that directory, as
recorded by Dired.
For a new buffer visiting a not yet existing file, high is −1 and low is 65535, that is,
216 − 1.
• Modes such as Dired and Rmail make buffers read-only when altering the contents with
the usual editing commands would probably be a mistake.
The special commands of these modes bind buffer-read-only to nil (with let) or
bind inhibit-read-only to t around the places where they themselves change the
text.
buffer-read-only [Variable]
This buffer-local variable specifies whether the buffer is read-only. The buffer is read-
only if this variable is non-nil.
inhibit-read-only [Variable]
If this variable is non-nil, then read-only buffers and, depending on the actual value,
some or all read-only characters may be modified. Read-only characters in a buffer
are those that have non-nil read-only properties (either text properties or overlay
properties). See Section 32.19.4 [Special Properties], page 620, for more information
about text properties. See Section 38.9 [Overlays], page 754, for more information
about overlays and their properties.
If inhibit-read-only is t, all read-only character properties have no effect. If
inhibit-read-only is a list, then read-only character properties have no effect if
they are members of the list (comparison is done with eq).
toggle-read-only &optional arg [Command]
This command toggles whether the current buffer is read-only. It is intended for
interactive use; do not use it in programs. At any given point in a program, you
should know whether you want the read-only flag on or off; so you can set buffer-
read-only explicitly to the proper value, t or nil.
If arg is non-nil, it should be a raw prefix argument. toggle-read-only sets buffer-
read-only to t if the numeric value of that prefix argument is positive and to nil
otherwise. See Section 21.11 [Prefix Command Arguments], page 340.
barf-if-buffer-read-only [Function]
This function signals a buffer-read-only error if the current buffer is read-only. See
Section 21.2.1 [Using Interactive], page 305, for another way to signal an error if the
current buffer is read-only.
the buffers most recently selected in that frame. (This order is recorded in frame’s buffer-
list frame parameter; see Section 29.3.3.5 [Buffer Parameters], page 535.) The buffers that
were never selected in frame come afterward, ordered according to the fundamental Emacs
buffer list.
buffer, and if the value is nil, that buffer is ignored. See Section 29.3.3.5 [Buffer
Parameters], page 535.
If visible-ok is nil, other-buffer avoids returning a buffer visible in any window on
any visible frame, except as a last resort. If visible-ok is non-nil, then it does not
matter whether a buffer is displayed somewhere or not.
If no suitable buffer exists, the buffer ‘*scratch*’ is returned (and created, if neces-
sary).
If the buffer is visiting a file and contains unsaved changes, kill-buffer asks the
user to confirm before the buffer is killed. It does this even if not called interactively.
To prevent the request for confirmation, clear the modified flag before calling kill-
buffer. See Section 27.5 [Buffer Modification], page 487.
Killing a buffer that is already dead has no effect.
This function returns t if it actually killed the buffer. It returns nil if the user refuses
to confirm or if buffer-or-name was already dead.
(kill-buffer "foo.unchanged")
⇒ t
(kill-buffer "foo.changed")
⇒ t
kill-buffer-query-functions [Variable]
After confirming unsaved changes, kill-buffer calls the functions in the list kill-
buffer-query-functions, in order of appearance, with no arguments. The buffer
being killed is the current buffer when they are called. The idea of this feature is that
these functions will ask for confirmation from the user. If any of them returns nil,
kill-buffer spares the buffer’s life.
kill-buffer-hook [Variable]
This is a normal hook run by kill-buffer after asking all the questions it is going to
ask, just before actually killing the buffer. The buffer to be killed is current when the
hook functions run. See Section 23.1 [Hooks], page 382. This variable is a permanent
local, so its local binding is not cleared by changing major modes.
buffer-offer-save [Variable]
This variable, if non-nil in a particular buffer, tells save-buffers-kill-emacs and
save-some-buffers (if the second optional argument to that function is t) to of-
fer to save that buffer, just as they offer to save file-visiting buffers. See [Definition
of save-some-buffers], page 438. The variable buffer-offer-save automatically be-
comes buffer-local when set for any reason. See Section 11.10 [Buffer-Local Variables],
page 147.
buffer-save-without-query [Variable]
This variable, if non-nil in a particular buffer, tells save-buffers-kill-emacs and
save-some-buffers to save this buffer (if it’s modified) without asking the user. The
variable automatically becomes buffer-local when set for any reason.
buffer-live-p object [Function]
This function returns t if object is a buffer which has not been killed, nil otherwise.
The text of the indirect buffer is always identical to the text of its base buffer; changes
made by editing either one are visible immediately in the other. This includes the text
properties as well as the characters themselves.
In all other respects, the indirect buffer and its base buffer are completely separate. They
have different names, independent values of point, independent narrowing, independent
markers and overlays (though inserting or deleting text in either buffer relocates the markers
and overlays for both), independent major modes, and independent buffer-local variable
bindings.
An indirect buffer cannot visit a file, but its base buffer can. If you try to save the
indirect buffer, that actually saves the base buffer.
Killing an indirect buffer has no effect on its base buffer. Killing the base buffer effectively
kills the indirect buffer in that it cannot ever again be the current buffer.
make-indirect-buffer base-buffer name &optional clone [Command]
This creates and returns an indirect buffer named name whose base buffer is base-
buffer. The argument base-buffer may be a live buffer or the name (a string) of an
existing buffer. If name is the name of an existing buffer, an error is signaled.
If clone is non-nil, then the indirect buffer originally shares the “state” of base-buffer
such as major mode, minor modes, buffer local variables and so on. If clone is omitted
or nil the indirect buffer’s state is set to the default state for new buffers.
If base-buffer is an indirect buffer, its base buffer is used as the base for the new
buffer. If, in addition, clone is non-nil, the initial state is copied from the actual
base buffer, not from base-buffer.
clone-indirect-buffer newname display-flag &optional norecord [Function]
This function creates and returns a new indirect buffer that shares the current buffer’s
base buffer and copies the rest of the current buffer’s attributes. (If the current buffer
is not indirect, it is used as the base buffer.)
If display-flag is non-nil, that means to display the new buffer by calling pop-to-
buffer. If norecord is non-nil, that means not to put the new buffer to the front of
the buffer list.
buffer-base-buffer &optional buffer [Function]
This function returns the base buffer of buffer, which defaults to the current buffer. If
buffer is not indirect, the value is nil. Otherwise, the value is another buffer, which
is never an indirect buffer.
gap-position [Function]
This function returns the current gap position in the current buffer.
gap-size [Function]
This function returns the current gap size of the current buffer.
Chapter 28: Windows 497
28 Windows
This chapter describes most of the functions and variables related to Emacs windows. See
Chapter 38 [Display], page 739, for information on how text is displayed in windows.
cursor-in-non-selected-windows [Variable]
If this variable is nil, Emacs displays only one cursor, in the selected window. Other
windows have no cursor at all.
For practical purposes, a window exists only while it is displayed in a frame. Once
removed from the frame, the window is effectively deleted and should not be used, even
though there may still be references to it from other Lisp objects. Restoring a saved window
configuration is the only way for a window no longer on the screen to come back to life.
(See Section 28.3 [Deleting Windows], page 501.)
Each window has the following attributes:
• containing frame
• window height
• window width
• window edges with respect to the screen or frame
• the buffer it displays
• position within the buffer at the upper left of the window
• amount of horizontal scrolling, in columns
• point
• the mark
• how recently the window was selected
• fringe settings
• display margins
• scroll-bar settings
Chapter 28: Windows 498
Users create multiple windows so they can look at several buffers at once. Lisp libraries
use multiple windows for a variety of reasons, but most often to display related information.
In Rmail, for example, you can move through a summary buffer in one window while the
other window shows messages one at a time as they are reached.
The meaning of “window” in Emacs is similar to what it means in the context of general-
purpose window systems such as X, but not identical. The X Window System places X
windows on the screen; Emacs uses one or more X windows as frames, and subdivides them
into Emacs windows. When you use Emacs on a character-only terminal, Emacs treats the
whole terminal screen as one frame.
Most window systems support arbitrarily located overlapping windows. In contrast,
Emacs windows are tiled; they never overlap, and together they fill the whole screen or
frame. Because of the way in which Emacs creates new windows and resizes them, not all
conceivable tilings of windows on an Emacs frame are actually possible. See Section 28.2
[Splitting Windows], page 498, and Section 28.14 [Size of Window], page 520.
See Chapter 38 [Display], page 739, for information on how the contents of the window’s
buffer are displayed in the window.
The following example starts with one window on a screen that is 50 lines high by 80
columns wide; then it splits the window.
(setq w (selected-window))
⇒ #<window 8 on windows.texi>
(window-edges) ; Edges in order:
⇒ (0 0 80 50) ; left–top–right–bottom
rest, but the upper window is still the one selected.) However, if split-window-
keep-point (see below) is nil, then either window can be selected.
In other respects, this function is similar to split-window. In particular, the upper
window is the original one and the return value is the new, lower window.
nil Count the windows in the selected frame, plus the minibuffer used by
that frame even if it lies in some other frame.
anything else
Count precisely the windows in the selected frame, and no others.
Chapter 28: Windows 501
window is the only window visible, then this function returns window. If omitted,
window defaults to the selected window.
The value of the argument minibuf determines whether the minibuffer is included in
the window order. Normally, when minibuf is nil, the minibuffer is included if it is
currently active; this is the behavior of C-x o. (The minibuffer window is active while
the minibuffer is in use. See Chapter 20 [Minibuffers], page 278.)
If minibuf is t, then the cyclic ordering includes the minibuffer window even if it is
not active.
If minibuf is neither t nor nil, then the minibuffer window is not included even if it
is active.
The argument all-frames specifies which frames to consider. Here are the possible
values and their meanings:
nil Consider all the windows in window’s frame, plus the minibuffer used by
that frame even if it lies in some other frame. If the minibuffer counts (as
determined by minibuf ), then all windows on all frames that share that
minibuffer count too.
t Consider all windows in all existing frames.
visible Consider all windows in all visible frames. (To get useful results, you
must ensure window is in a visible frame.)
0 Consider all windows in all visible or iconified frames.
a frame Consider all windows on that frame.
anything else
Consider precisely the windows in window’s frame, and no others.
This example assumes there are two windows, both displaying the buffer
‘windows.texi’:
(selected-window)
⇒ #<window 56 on windows.texi>
(next-window (selected-window))
⇒ #<window 52 on windows.texi>
(next-window (next-window (selected-window)))
⇒ #<window 56 on windows.texi>
previous-window &optional window minibuf all-frames [Function]
This function returns the window preceding window in the cyclic ordering of windows.
The other arguments specify which windows to include in the cycle, as in next-
window.
other-window count &optional all-frames [Command]
This function selects the countth following window in the cyclic order. If count is
negative, then it moves back −count windows in the cycle, rather than forward. It
returns nil.
The argument all-frames has the same meaning as in next-window, but the minibuf
argument of next-window is always effectively nil.
In an interactive call, count is the numeric prefix argument.
Chapter 28: Windows 505
buffer-display-count [Variable]
This buffer-local variable records the number of times a buffer is displayed in a win-
dow. It is incremented each time set-window-buffer is called for the buffer.
the cyclic ordering of windows, starting from the selected window. See Section 28.5
[Cyclic Window Ordering], page 503.
The argument all-frames controls which windows to consider.
• If it is nil, consider windows on the selected frame.
• If it is t, consider windows on all frames.
• If it is visible, consider windows on all visible frames.
• If it is 0, consider windows on all visible or iconified frames.
• If it is a frame, consider windows on that frame.
get-buffer-window-list buffer-or-name &optional minibuf all-frames [Function]
This function returns a list of all the windows currently displaying buffer-or-name.
The two optional arguments work like the optional arguments of next-window (see
Section 28.5 [Cyclic Window Ordering], page 503); they are not like the single optional
argument of get-buffer-window. Perhaps we should change get-buffer-window in
the future to make it compatible with the other functions.
buffer-display-time [Variable]
This variable records the time at which a buffer was last made visible in a window.
It is always local in each buffer; each time set-window-buffer is called, it sets this
variable to (current-time) in the specified buffer (see Section 39.5 [Time of Day],
page 824). When a buffer is first created, buffer-display-time starts out with the
value nil.
Normally the specified buffer is put at the front of the buffer list (both the selected
frame’s buffer list and the frame-independent buffer list). This affects the operation
of other-buffer. However, if norecord is non-nil, this is not done. See Section 27.8
[The Buffer List], page 490.
The switch-to-buffer function is often used interactively, as the binding of C-x b.
It is also used frequently in programs. It returns the buffer that it switched to.
The next two functions are similar to switch-to-buffer, except for the described fea-
tures.
switch-to-buffer-other-window buffer-or-name &optional norecord [Command]
This function makes buffer-or-name the current buffer and displays it in a window
not currently selected. It then selects that window. The handling of the buffer is the
same as in switch-to-buffer.
The currently selected window is absolutely never used to do the job. If it is the only
window, then it is split to make a distinct window for this purpose. If the selected
window is already displaying the buffer, then it continues to do so, but another window
is nonetheless found to display it in as well.
This function updates the buffer list just like switch-to-buffer unless norecord is
non-nil.
pop-to-buffer buffer-or-name &optional other-window norecord [Function]
This function makes buffer-or-name the current buffer and switches to it in some
window, preferably not the window previously selected. The “popped-to” window
becomes the selected window within its frame. The return value is the buffer that
was switched to. If buffer-or-name is nil, that means to choose some other buffer,
but you don’t specify which.
If the variable pop-up-frames is non-nil, pop-to-buffer looks for a window in any
visible frame already displaying the buffer; if there is one, it returns that window and
makes it be selected within its frame. If there is none, it creates a new frame and
displays the buffer in it.
If pop-up-frames is nil, then pop-to-buffer operates entirely within the selected
frame. (If the selected frame has just a minibuffer, pop-to-buffer operates within
the most recently selected frame that was not just a minibuffer.)
If the variable pop-up-windows is non-nil, windows may be split to create a new
window that is different from the original window. For details, see Section 28.8
[Choosing Window], page 508.
If other-window is non-nil, pop-to-buffer finds or creates another window even if
buffer-or-name is already visible in the selected window. Thus buffer-or-name could
end up displayed in two windows. On the other hand, if buffer-or-name is already
displayed in the selected window and other-window is nil, then the selected window
is considered sufficient display for buffer-or-name, so that nothing needs to be done.
All the variables that affect display-buffer affect pop-to-buffer as well. See
Section 28.8 [Choosing Window], page 508.
If buffer-or-name is a string that does not name an existing buffer, a buffer by that
name is created. The major mode for the new buffer is set according to the variable
default-major-mode. See Section 23.2.3 [Auto Major Mode], page 388.
Chapter 28: Windows 508
This function updates the buffer list just like switch-to-buffer unless norecord is
non-nil.
display-buffer-function [Variable]
This variable is the most flexible way to customize the behavior of display-buffer.
If it is non-nil, it should be a function that display-buffer calls to do the work.
The function should accept two arguments, the first two arguments that display-
buffer received. It should choose or create a window, display the specified buffer in
it, and then return the window.
This hook takes precedence over all the other options and hooks described above.
A window can be marked as “dedicated” to its buffer. Then display-buffer will not
try to use that window to display any other buffer.
See Chapter 30 [Positions], page 559, for more details on buffer positions.
As far as the user is concerned, point is where the cursor is, and when the user switches
to another buffer, the cursor jumps to the position of point in that buffer.
Chapter 28: Windows 512
If update is non-nil, window-end always returns an up-to-date value for where the
window ends, based on the current window-start value. If the saved value is valid,
window-end returns that; otherwise it computes the correct value by scanning the
buffer text.
Even if update is non-nil, window-end does not attempt to scroll the display if point
has moved off the screen, the way real redisplay would do. It does not alter the
window-start value. In effect, it reports where the displayed text will end if scrolling
is not required.
The display routines insist that the position of point be visible when a buffer is dis-
played. Normally, they change the display-start position (that is, scroll the window)
whenever necessary to make point visible. However, if you specify the start position
with this function using nil for noforce, it means you want display to start at position
even if that would put the location of point off the screen. If this does place point off
screen, the display routines move point to the left margin on the middle line in the
window.
For example, if point is 1 and you set the start of the window to 2, then point would
be “above” the top of the window. The display routines will automatically move
point if it is still 1 when redisplay occurs. Here is an example:
(set-window-start
(selected-window)
(1+ (window-start)))
⇒ 2
Chapter 28: Windows 514
other-window-scroll-buffer [Variable]
If this variable is non-nil, it tells scroll-other-window which buffer to scroll.
auto-window-vscroll [Variable]
If this variable is non-nil, the line-move, scroll-up, and scroll-down functions will
automatically modify the window vscroll to scroll through display rows that are taller
that the height of the window, for example in the presence of large images.
The horizontal scroll position is measured in units of the normal character width, which
is the width of space in the default font. Thus, if the value is 5, that means the window
contents are scrolled left by 5 times the normal character width. How many characters
actually disappear off to the left depends on their width, and could vary from line to line.
Because we read from side to side in the “inner loop,” and from top to bottom in the
“outer loop,” the effect of horizontal scrolling is not like that of textual or vertical scrolling.
Textual scrolling involves selection of a portion of text to display, and vertical scrolling
moves the window contents contiguously; but horizontal scrolling causes part of each line
to go off screen.
Usually, no horizontal scrolling is in effect; then the leftmost column is at the left edge of
the window. In this state, scrolling to the right is meaningless, since there is no data to the
left of the edge to be revealed by it; so this is not allowed. Scrolling to the left is allowed; it
scrolls the first columns of text off the edge of the window and can reveal additional columns
on the right that were truncated before. Once a window has a nonzero amount of leftward
horizontal scrolling, you can scroll it back to the right, but only so far as to reduce the net
horizontal scroll to zero. There is no limit to how far left you can scroll, but eventually all
the text will disappear off the left edge.
If auto-hscroll-mode is set, redisplay automatically alters the horizontal scrolling of
a window as necessary to ensure that point is always visible. However, you can still set
the horizontal scrolling value explicitly. The value you specify serves as a lower bound for
automatic scrolling, i.e. automatic scrolling will not scroll a window to a column less than
the specified one.
(window-hscroll)
⇒ 0
(scroll-left 5)
⇒ 5
(window-hscroll)
⇒ 5
Here is how you can determine whether a given position position is off the screen due to
horizontal scrolling:
(defun hscroll-on-screen (window position)
(save-excursion
(goto-char position)
(and
(>= (- (current-column) (window-hscroll window)) 0)
(< (- (current-column) (window-hscroll window))
(window-width window)))))
(split-window-vertically)
⇒ #<window 4 on windows.texi>
(window-height)
⇒ 11
Here are the results obtained on a typical 24-line terminal with just one window, with
menu bar enabled:
(window-edges (selected-window))
⇒ (0 1 80 23)
(window-inside-edges (selected-window))
⇒ (0 1 80 22)
The bottom edge is at line 23 because the last line is the echo area. The bottom inside edge
is at line 22, which is the window’s mode line.
If window is at the upper left corner of its frame, and there is no menu bar, then bottom
returned by window-edges is the same as the value of (window-height), right is almost
the same as the value of (window-width), and top and left are zero. For example, the edges
Chapter 28: Windows 522
of the following window are ‘0 0 8 5’. Assuming that the frame has more than 8 columns,
the last column of the window (column 7) holds a border rather than text. The last row
(row 4) holds the mode line, shown here with ‘xxxxxxxxx’.
0
_______
0 | |
| |
| |
| |
xxxxxxxxx 4
7
In the following example, let’s suppose that the frame is 7 columns wide. Then the edges
of the left window are ‘0 0 4 3’ and the edges of the right window are ‘4 0 7 3’. The inside
edges of the left window are ‘0 0 3 2’, and the inside edges of the right window are ‘4 0 7 2’,
___ ___
| | |
| | |
xxxxxxxxx
0 34 7
If there are various other windows from which lines or columns can be stolen, and
some of them specify fixed size (using window-size-fixed, see below), they are left
untouched while other windows are “robbed.” If it would be necessary to alter the
size of a fixed-size window, enlarge-window gets an error instead.
If size is negative, this function shrinks the window by −size lines or columns. If
that makes the window smaller than the minimum size (window-min-height and
window-min-width), enlarge-window deletes the window.
enlarge-window returns nil.
However, the command does nothing if the window is already too small to display the
whole text of the buffer, or if part of the contents are currently scrolled off screen, or
if the window is not the full width of its frame, or if the window is the only window
in its frame.
This command returns non-nil if it actually shrank the window and nil otherwise.
window-size-fixed [Variable]
If this variable is non-nil, in any given buffer, then the size of any window displaying
the buffer remains fixed unless you explicitly change it or Emacs has no other choice.
If the value is height, then only the window’s height is fixed; if the value is width,
then only the window’s width is fixed. Any other non-nil value fixes both the width
and the height.
This variable automatically becomes buffer-local when set.
Explicit size-change functions such as enlarge-window get an error if they would
have to change a window size which is fixed. Therefore, when you want to change the
size of such a window, you should bind window-size-fixed to nil, like this:
(let ((window-size-fixed nil))
(enlarge-window 10))
Note that changing the frame size will change the size of a fixed-size window, if there
is no other alternative.
The following two variables constrain the window-structure-changing functions to a min-
imum height and width.
window-min-height [User Option]
The value of this variable determines how short a window may become before it is
automatically deleted. Making a window smaller than window-min-height automat-
ically deletes it, and no window may be created shorter than this. The default value
is 4.
The absolute minimum window height is one; actions that change window sizes reset
this variable to one if it is less than one.
window-min-width [User Option]
The value of this variable determines how narrow a window may become before it is
automatically deleted. Making a window smaller than window-min-width automati-
cally deletes it, and no window may be created narrower than this. The default value
is 10.
The absolute minimum window width is two; actions that change window sizes reset
this variable to two if it is less than two.
If the root window is not split, root is the root window itself. Otherwise, root is a list
(dir edges w1 w2 ...) where dir is nil for a horizontal split, and t for a vertical
split, edges gives the combined size and position of the subwindows in the split, and
the rest of the elements are the subwindows in the split. Each of the subwindows may
again be a window or a list representing a window split, and so on. The edges element
is a list (left top right bottom ) similar to the value returned by window-edges.
includes the choice of selected window. However, it does not include the value of
point in the current buffer; use save-excursion also, if you wish to preserve that.
Don’t use this construct when save-selected-window is sufficient.
Exit from save-window-excursion always triggers execution of the window-size-
change-functions. (It doesn’t know how to tell whether the restored configuration
actually differs from the one in effect at the end of the forms.)
The return value is the value of the final form in forms. For example:
(split-window)
⇒ #<window 25 on control.texi>
(setq w (selected-window))
⇒ #<window 19 on control.texi>
(save-window-excursion
(delete-other-windows w)
(switch-to-buffer "foo")
’do-something)
⇒ do-something
;; The screen is now split again.
window-configuration-p object [Function]
This function returns t if object is a window configuration.
compare-window-configurations config1 config2 [Function]
This function compares two window configurations as regards the structure of win-
dows, but ignores the values of point and mark and the saved scrolling positions—it
can return t even if those aspects differ.
The function equal can also compare two window configurations; it regards configu-
rations as unequal if they differ in any respect, even a saved point or mark.
window-configuration-frame config [Function]
This function returns the frame for which the window configuration config was made.
Other primitives to look inside of window configurations would make sense, but are
not implemented because we did not need them. See the file ‘winner.el’ for some more
operations on windows configurations.
These functions must be careful in using window-end (see Section 28.10 [Window
Start], page 512); if you need an up-to-date value, you must use the update argument
to ensure you get it.
Warning: don’t use this feature to alter the way the window is scrolled. It’s not
designed for that, and such use probably won’t work.
window-size-change-functions [Variable]
This variable holds a list of functions to be called if the size of any window changes
for any reason. The functions are called just once per redisplay, and just once for
each frame on which size changes have occurred.
Each function receives the frame as its sole argument. There is no direct way to find
out which windows on that frame have changed size, or precisely how. However, if a
size-change function records, at each call, the existing windows and their sizes, it can
also compare the present sizes and the previous sizes.
Creating or deleting windows counts as a size change, and therefore causes these
functions to be called. Changing the frame size also counts, because it changes the
sizes of the existing windows.
It is not a good idea to use save-window-excursion (see Section 28.18 [Window
Configurations], page 526) in these functions, because that always counts as a size
change, and it would cause these functions to be called over and over. In most cases,
save-selected-window (see Section 28.4 [Selecting Windows], page 502) is what you
need here.
redisplay-end-trigger-functions [Variable]
This abnormal hook is run whenever redisplay in a window uses text that extends past
a specified end trigger position. You set the end trigger position with the function
set-window-redisplay-end-trigger. The functions are called with two arguments:
the window, and the end trigger position. Storing nil for the end trigger position
turns off the feature, and the trigger value is automatically reset to nil just after the
hook is run.
window-configuration-change-hook [Variable]
A normal hook that is run every time you change the window configuration of an
existing frame. This includes splitting or deleting windows, changing the sizes of
windows, or displaying a different buffer in a window. The frame whose window
configuration has changed is the selected frame when this hook runs.
Chapter 29: Frames 529
29 Frames
In Emacs editing, A frame is a screen object that contains one or more Emacs windows. It’s
the kind of object that is called a “window” in the terminology of graphical environments;
but we can’t call it a “window” here, because Emacs uses that word in a different way.
A frame initially contains a single main window and/or a minibuffer window; you can
subdivide the main window vertically or horizontally into smaller windows. In Emacs Lisp,
a frame object is a Lisp object that represents a frame on the screen.
When Emacs runs on a text-only terminal, it starts with one terminal frame. If you
create additional ones, Emacs displays one and only one at any given time—on the terminal
screen, of course.
When Emacs communicates directly with a supported window system, such as X, it does
not have a terminal frame; instead, it starts with a single window frame, but you can create
more, and Emacs can display several such frames at once as is usual for window systems.
framep object [Function]
This predicate returns a non-nil value if object is a frame, and nil otherwise. For a
frame, the value indicates which kind of display the frame uses:
x The frame is displayed in an X window.
t A terminal frame on a character display.
mac The frame is displayed on a Macintosh.
w32 The frame is displayed on MS-Windows 9X/NT.
pc The frame is displayed on an MS-DOS terminal.
See Chapter 38 [Display], page 739, for information about the related topic of controlling
Emacs redisplay.
before-make-frame-hook [Variable]
A normal hook run by make-frame before it actually creates the frame.
after-make-frame-functions [Variable]
An abnormal hook run by make-frame after it creates the frame. Each function in
after-make-frame-functions receives one argument, the frame just created.
the resource values recorded in the X server itself; they apply to all Emacs frames
created on this display. Here’s an example of what this string might look like:
"*BorderWidth: 3\n*InternalBorder: 2\n"
See section “X Resources” in The GNU Emacs Manual.
If must-succeed is non-nil, failure to open the connection terminates Emacs. Other-
wise, it is an ordinary Lisp error.
initial-frame-alist [Variable]
This variable’s value is an alist of parameter values used when creating the initial
window frame. You can set this variable to specify the appearance of the initial
frame without altering subsequent frames. Each element has the form:
(parameter . value )
Emacs creates the initial frame before it reads your init file. After reading that
file, Emacs checks initial-frame-alist, and applies the parameter settings in the
altered value to the already created initial frame.
If these settings affect the frame geometry and appearance, you’ll see the frame appear
with the wrong ones and then change to the specified ones. If that bothers you, you
can specify the same geometry and appearance with X resources; those do take effect
before the frame is created. See section “X Resources” in The GNU Emacs Manual.
X resource settings typically apply to all frames. If you want to specify some X
resources solely for the sake of the initial frame, and you don’t want them to apply to
subsequent frames, here’s how to achieve this. Specify parameters in default-frame-
alist to override the X resources for subsequent frames; then, to prevent these from
affecting the initial frame, specify the same parameters in initial-frame-alist with
values that match the X resources.
minibuffer-frame-alist [Variable]
This variable’s value is an alist of parameter values used when creating an initial
minibuffer-only frame—if such a frame is needed, according to the parameters for the
main initial frame.
default-frame-alist [Variable]
This is an alist specifying default values of frame parameters for all Emacs frames—
the first frame, and subsequent frames. When using the X Window System, you can
get the same results by means of X resources in many cases.
Setting this variable does not affect existing frames.
icon-left
The screen position of the left edge of the frame’s icon, in pixels, counting from
the left edge of the screen. This takes effect if and when the frame is iconified.
If you specify a value for this parameter, then you must also specify a value for
icon-top and vice versa. The window manager may ignore these two parame-
ters.
icon-top The screen position of the top edge of the frame’s icon, in pixels, counting from
the top edge of the screen. This takes effect if and when the frame is iconified.
user-position
When you create a frame and specify its screen position with the left and
top parameters, use this parameter to say whether the specified position was
user-specified (explicitly requested in some way by a human user) or merely
program-specified (chosen by a program). A non-nil value says the position
was user-specified.
Window managers generally heed user-specified positions, and some heed
program-specified positions too. But many ignore program-specified positions,
placing the window in a default fashion or letting the user place it with the
mouse. Some window managers, including twm, let the user specify whether to
obey program-specified positions or ignore them.
When you call make-frame, you should specify a non-nil value for this param-
eter if the values of the left and top parameters represent the user’s stated
preference; otherwise, use nil.
internal-border-width
The distance in pixels between text (or fringe) and the frame’s border.
vertical-scroll-bars
Whether the frame has scroll bars for vertical scrolling, and which side of the
frame they should be on. The possible values are left, right, and nil for no
scroll bars.
scroll-bar-width
The width of vertical scroll bars, in pixels, or nil meaning to use the default
width.
left-fringe
right-fringe
The default width of the left and right fringes of windows in this frame (see
Section 38.13 [Fringes], page 776). If either of these is zero, that effectively
removes the corresponding fringe. A value of nil stands for the standard fringe
width, which is the width needed to display the fringe bitmaps.
The combined fringe widths must add up to an integral number of columns, so
the actual default fringe widths for the frame may be larger than the specified
values. The extra width needed to reach an acceptable total is distributed
evenly between the left and right fringe. However, you can force one fringe or
the other to a precise width by specifying that width as a negative integer. If
both widths are negative, only the left fringe gets the specified width.
menu-bar-lines
The number of lines to allocate at the top of the frame for a menu bar. The
default is 1. A value of nil means don’t display a menu bar. See Section 22.17.5
[Menu Bar], page 377. (The X toolkit and GTK allow at most one menu bar
line; they treat larger values as 1.)
tool-bar-lines
The number of lines to use for the tool bar. A value of nil means don’t display
a tool bar. (GTK allows at most one tool bar line; it treats larger values as 1.)
line-spacing
Additional space to leave below each text line, in pixels (a positive integer).
See Section 38.11 [Line Height], page 761, for more information.
buffer, once for each buffer; if the predicate returns a non-nil value, it considers
that buffer.
buffer-list
A list of buffers that have been selected in this frame, ordered most-recently-
selected first.
unsplittable
If non-nil, this frame’s window is never split automatically.
blink-cursor-alist [Variable]
This variable specifies how to blink the cursor. Each element has the form (on-state
. off-state ). Whenever the cursor type equals on-state (comparing using equal),
the corresponding off-state specifies what the cursor looks like when it blinks “off.”
Both on-state and off-state should be suitable values for the cursor-type frame
parameter.
There are various defaults for how to blink each type of cursor, if the type is not men-
tioned as an on-state here. Changes in this variable do not take effect immediately,
because the variable is examined only when you specify the cursor-type parameter.
gamma value. If you specify 2.2 for screen-gamma, that means no correction is
needed. Other values request correction, designed to make the corrected colors
appear on your screen the way they would have appeared without correction
on an ordinary monitor with a gamma value of 2.2.
If your monitor displays colors too light, you should specify a screen-gamma
value smaller than 2.2. This requests correction that makes colors darker. A
screen gamma value of 1.5 may give good results for LCD color displays.
These frame parameters are semi-obsolete in that they are automatically equivalent to
particular face attributes of particular faces. See section “Standard Faces” in The Emacs
Manual.
font The name of the font for displaying text in the frame. This is a string, either
a valid font name for your system or the name of an Emacs fontset (see Sec-
tion 38.12.9 [Fontsets], page 774). It is equivalent to the font attribute of the
default face.
foreground-color
The color to use for the image of a character. It is equivalent to the :foreground
attribute of the default face.
background-color
The color to use for the background of characters. It is equivalent to the
:background attribute of the default face.
mouse-color
The color for the mouse pointer. It is equivalent to the :background attribute
of the mouse face.
cursor-color
The color for the cursor that shows point. It is equivalent to the :background
attribute of the cursor face.
border-color
The color for the border of the frame. It is equivalent to the :background
attribute of the border face.
scroll-bar-foreground
If non-nil, the color for the foreground of scroll bars. It is equivalent to the
:foreground attribute of the scroll-bar face.
scroll-bar-background
If non-nil, the color for the background of scroll bars. It is equivalent to the
:background attribute of the scroll-bar face.
screen-height [Function]
screen-width [Function]
These functions are old aliases for frame-height and frame-width. When you are
using a non-window terminal, the size of the frame is normally the same as the size
of the terminal screen.
29.3.5 Geometry
Here’s how to examine the data in an X-style window geometry specification:
x-parse-geometry geom [Function]
The function x-parse-geometry converts a standard X window geometry string to
an alist that you can use as part of the argument to make-frame.
The alist describes which parameters were specified in geom, and gives the values
specified for them. Each element looks like (parameter . value ). The possible
parameter values are left, top, width, and height.
For the size parameters, the value must be an integer. The position parameter names
left and top are not totally accurate, because some values indicate the position of
the right or bottom edges instead. These are the value possibilities for the position
parameters:
an integer A positive integer relates the left edge or top edge of the window to the
left or top edge of the screen. A negative integer relates the right or
bottom edge of the window to the right or bottom edge of the screen.
(+ position )
This specifies the position of the left or top edge of the window relative
to the left or top edge of the screen. The integer position may be positive
or negative; a negative value specifies a position outside the screen.
(- position )
This specifies the position of the right or bottom edge of the window
relative to the right or bottom edge of the screen. The integer position
may be positive or negative; a negative value specifies a position outside
the screen.
Here is an example:
(x-parse-geometry "35x70+0-0")
⇒ ((height . 70) (width . 35)
(top - 0) (left . 0))
frame-title-format [Variable]
This variable specifies how to compute a name for a frame when you have not explicitly
specified one. The variable’s value is actually a mode line construct, just like mode-
line-format, except that the ‘%c’ and ‘%l’ constructs are ignored. See Section 23.4.2
[Mode Line Data], page 402.
icon-title-format [Variable]
This variable specifies how to compute the name for an iconified frame, when you
have not explicitly specified the frame title. This title appears in the icon itself.
multiple-frames [Variable]
This variable is set automatically by Emacs. Its value is t when there are two or
more frames (not counting minibuffer-only frames or invisible frames). The default
value of frame-title-format uses multiple-frames so as to put the buffer name in
the frame title only when there is more than one frame.
The value of this variable is not guaranteed to be accurate except while processing
frame-title-format or icon-title-format.
visible-frame-list [Function]
This function returns a list of just the currently visible frames. See Section 29.10
[Visibility of Frames], page 545. (Terminal frames always count as “visible,” even
though only the selected one is actually displayed.)
next-frame &optional frame minibuf [Function]
The function next-frame lets you cycle conveniently through all the frames on the
current display from an arbitrary starting point. It returns the “next” frame after
frame in the cycle. If frame is omitted or nil, it defaults to the selected frame (see
Section 29.9 [Input Focus], page 543).
The second argument, minibuf, says which frames to consider:
nil Exclude minibuffer-only frames.
visible Consider all visible frames.
0 Consider all visible or iconified frames.
a window Consider only the frames using that particular window as their minibuffer.
anything else
Consider all frames.
previous-frame &optional frame minibuf [Function]
Like next-frame, but cycles through all frames in the opposite direction.
See also next-window and previous-window, in Section 28.5 [Cyclic Window Ordering],
page 503.
Lisp programs can also switch frames “temporarily” by calling the function select-
frame. This does not alter the window system’s concept of focus; rather, it escapes from
the window manager’s control until that control is somehow reasserted.
When using a text-only terminal, only one frame can be displayed at a time on the
terminal, so after a call to select-frame, the next redisplay actually displays the newly
selected frame. This frame remains selected until a subsequent call to select-frame or
select-frame-set-input-focus. Each terminal frame has a number which appears in the
mode line before the buffer name (see Section 23.4.4 [Mode Line Variables], page 405).
select-frame-set-input-focus frame [Function]
This function makes frame the selected frame, raises it (should it happen to be ob-
scured by other frames) and tries to give it the X server’s focus. On a text-only
terminal, the next redisplay displays the new frame on the entire terminal screen.
The return value of this function is not significant.
select-frame frame [Function]
This function selects frame frame, temporarily disregarding the focus of the X server
if any. The selection of frame lasts until the next time the user does something to
select a different frame, or until the next time this function is called. (If you are using
a window system, the previously selected frame may be restored as the selected frame
after return to the command loop, because it still may have the window system’s input
focus.) The specified frame becomes the selected frame, as explained above, and the
terminal that frame is on becomes the selected terminal. This function returns frame,
or nil if frame has been deleted.
In general, you should never use select-frame in a way that could switch to a
different terminal without switching back when you’re done.
Emacs cooperates with the window system by arranging to select frames as the server
and window manager request. It does so by generating a special kind of input event, called
a focus event, when appropriate. The command loop handles a focus event by calling
handle-switch-frame. See Section 21.6.9 [Focus Events], page 322.
handle-switch-frame frame [Command]
This function handles a focus event by selecting frame frame.
Focus events normally do their job by invoking this command. Don’t call it for any
other reason.
redirect-frame-focus frame &optional focus-frame [Function]
This function redirects focus from frame to focus-frame. This means that focus-
frame will receive subsequent keystrokes and events intended for frame. After such
an event, the value of last-event-frame will be focus-frame. Also, switch-frame
events specifying frame will instead select focus-frame.
If focus-frame is omitted or nil, that cancels any existing redirection for frame, which
therefore once again receives its own events.
One use of focus redirection is for frames that don’t have minibuffers. These frames
use minibuffers on other frames. Activating a minibuffer on another frame redirects
focus to that frame. This puts the focus on the minibuffer’s frame, where it belongs,
even though the mouse remains in the frame that activated the minibuffer.
Chapter 29: Frames 545
Selecting a frame can also change focus redirections. Selecting frame bar, when foo
had been selected, changes any redirections pointing to foo so that they point to bar
instead. This allows focus redirection to work properly when the user switches from
one frame to another using select-window.
This means that a frame whose focus is redirected to itself is treated differently from
a frame whose focus is not redirected. select-frame affects the former but not the
latter.
The redirection lasts until redirect-frame-focus is called to change it.
The visibility status of a frame is also available as a frame parameter. You can read or
change it as such. See Section 29.3.3.6 [Management Parameters], page 536.
Chapter 29: Frames 546
The user can iconify and deiconify frames with the window manager. This happens
below the level at which Emacs can exert any control, but Emacs does provide events that
you can use to keep track of such changes. See Section 21.6.10 [Misc Events], page 322.
You can also enable auto-raise (raising automatically when a frame is selected) or auto-
lower (lowering automatically when it is deselected) for any frame using frame parameters.
See Section 29.3.3.6 [Management Parameters], page 536.
current-frame-configuration [Function]
This function returns a frame configuration list that describes the current arrangement
of frames and their contents.
The usual purpose of tracking mouse motion is to indicate on the screen the consequences
of pushing or releasing a button at the current position.
In many cases, you can avoid the need to track the mouse by using the mouse-face text
property (see Section 32.19.4 [Special Properties], page 620). That works at a much lower
level and runs more smoothly than Lisp-level mouse tracking.
mouse-position [Function]
This function returns a description of the position of the mouse. The value looks like
(frame x . y ), where x and y are integers giving the position in characters relative
to the top left corner of the inside of frame.
mouse-position-function [Variable]
If non-nil, the value of this variable is a function for mouse-position to call. mouse-
position calls this function just before returning, with its normal return value as the
sole argument, and it returns whatever this function returns to it.
This abnormal hook exists for the benefit of packages like ‘xt-mouse.el’ that need
to do mouse handling at the Lisp level.
mouse-pixel-position [Function]
This function is like mouse-position except that it returns coordinates in units of
pixels rather than units of characters.
Usage note: Don’t use x-popup-menu to display a menu if you could do the job with a
prefix key defined with a menu keymap. If you use a menu keymap to implement a menu,
C-h c and C-h a can see the individual items in that menu and provide help for them. If
instead you implement the menu by defining a command that calls x-popup-menu, the help
facilities cannot know what happens inside that command, so they cannot give any help for
the menu’s items.
The menu bar mechanism, which lets you switch between submenus by moving the
mouse, cannot look within the definition of a command to see that it calls x-popup-menu.
Therefore, if you try to implement a submenu using x-popup-menu, it cannot work with the
menu bar in an integrated fashion. This is why all menu bar submenus are implemented with
menu keymaps within the parent menu, and never with x-popup-menu. See Section 22.17.5
[Menu Bar], page 377.
If you want a menu bar submenu to have contents that vary, you should still use a menu
keymap to implement it. To make the contents vary, add a hook function to menu-bar-
update-hook to update the contents of the menu keymap as necessary.
If the user gets rid of the dialog box without making a valid choice, for instance using
the window manager, then this produces a quit and x-popup-dialog does not return.
void-text-area-pointer [Variable]
This variable specifies the mouse pointer style for void text areas. These include the
areas after the end of a line or below the last line in the buffer. The default is to use
the arrow (non-text) pointer style.
You can specify what the text pointer style really looks like by setting the variable
x-pointer-shape.
x-pointer-shape [Variable]
This variable specifies the pointer shape to use ordinarily in the Emacs frame, for the
text pointer style.
x-sensitive-text-pointer-shape [Variable]
This variable specifies the pointer shape to use when the mouse is over mouse-sensitive
text.
These variables affect newly created frames. They do not normally affect existing frames;
however, if you set the mouse color of a frame, that also installs the current value of those
two variables. See Section 29.3.3.8 [Color Parameters], page 537.
The values you can use, to specify either of these pointer shapes, are defined in the file
‘lisp/term/x-win.el’. Use M-x apropos RET x-pointer RET to see a list of them.
Each possible type has its own selection value, which changes independently. The
usual values of type are PRIMARY, SECONDARY and CLIPBOARD; these are symbols with
upper-case names, in accord with X Window System conventions. If type is nil, that
stands for PRIMARY.
This function returns data.
x-get-selection &optional type data-type [Function]
This function accesses selections set up by Emacs or by other X clients. It takes two
optional arguments, type and data-type. The default for type, the selection type, is
PRIMARY.
The data-type argument specifies the form of data conversion to use, to convert the
raw data obtained from another X client into Lisp data. Meaningful values include
TEXT, STRING, UTF8_STRING, TARGETS, LENGTH, DELETE, FILE_NAME, CHARACTER_
POSITION, NAME, LINE_NUMBER, COLUMN_NUMBER, OWNER_OS, HOST_NAME, USER, CLASS,
ATOM, and INTEGER. (These are symbols with upper-case names in accord with X
conventions.) The default for data-type is STRING.
The X server also has a set of eight numbered cut buffers which can store text or other
data being moved between applications. Cut buffers are considered obsolete, but Emacs
supports them for the sake of X clients that still use them. Cut buffers are numbered from
0 to 7.
x-get-cut-buffer &optional n [Function]
This function returns the contents of cut buffer number n. If omitted n defaults to 0.
x-set-cut-buffer string &optional push [Function]
This function stores string into the first cut buffer (cut buffer 0). If push is nil, only
the first cut buffer is changed. If push is non-nil, that says to move the values down
through the series of cut buffers, much like the way successive kills in Emacs move
down the kill ring. In other words, the previous value of the first cut buffer moves
into the second cut buffer, and the second to the third, and so on through all eight
cut buffers.
selection-coding-system [Variable]
This variable specifies the coding system to use when reading and writing selections
or the clipboard. See Section 33.10 [Coding Systems], page 648. The default is
compound-text-with-extensions, which converts to the text representation that
X11 normally uses.
When Emacs runs on MS-Windows, it does not implement X selections in general, but
it does support the clipboard. x-get-selection and x-set-selection on MS-Windows
support the text data type only; if the clipboard holds other types of data, Emacs treats
the clipboard as empty.
On Mac OS, selection-like data transfer between applications is performed
through a mechanism called scraps. The clipboard is a particular scrap named
com.apple.scrap.clipboard. Types of scrap data are called scrap flavor types, which are
identified by four-char codes such as TEXT. Emacs associates a selection with a scrap, and
a selection type with a scrap flavor type via mac-scrap-name and mac-ostype properties,
respectively.
Chapter 29: Frames 552
⇒ nil
The color values are returned for frame’s display. If frame is omitted or nil, the
information is returned for the selected frame’s display. If the frame cannot display
colors, the value is nil.
This function used to be called x-color-values, and that name is still supported as
an alias.
29.22 X Resources
x-get-resource attribute class &optional component subclass [Function]
The function x-get-resource retrieves a resource value from the X Window defaults
database.
Resources are indexed by a combination of a key and a class. This function searches
using a key of the form ‘instance.attribute ’ (where instance is the name under
which Emacs was invoked), and using ‘Emacs.class ’ as the class.
The optional arguments component and subclass add to the key and the class, re-
spectively. You must specify both of them or neither. If you specify them, the key is
‘instance.component.attribute ’, and the class is ‘Emacs.class.subclass ’.
x-resource-class [Variable]
This variable specifies the application name that x-get-resource should look up.
The default value is "Emacs". You can examine X resources for application names
other than “Emacs” by binding this variable to some other string, around a call to
x-get-resource.
x-resource-name [Variable]
This variable specifies the instance name that x-get-resource should look up. The
default value is the name Emacs was invoked with, or the value specified with the
‘-name’ or ‘-rn’ switches.
To illustrate some of the above, suppose that you have the line:
xterm.vt100.background: yellow
in your X resources file (whose name is usually ‘~/.Xdefaults’ or ‘~/.Xresources’). Then:
(let ((x-resource-class "XTerm") (x-resource-name "xterm"))
(x-get-resource "vt100.background" "VT100.Background"))
⇒ "yellow"
(let ((x-resource-class "XTerm") (x-resource-name "xterm"))
(x-get-resource "background" "VT100" "vt100" "Background"))
⇒ "yellow"
See section “X Resources” in The GNU Emacs Manual.
is on), or nil (which refers to the selected frame’s display, see Section 29.9 [Input Focus],
page 543).
See Section 29.20 [Color Names], page 552, Section 29.21 [Text Terminal Colors],
page 554, for other functions to obtain information about displays.
30 Positions
A position is the index of a character in the text of a buffer. More precisely, a position
identifies the place between two characters (or before the first character, or after the last
character), so we can speak of the character before or after a given position. However, we
often speak of the character “at” a position, meaning the character after that position.
Positions are usually represented as integers starting from 1, but can also be represented
as markers—special objects that relocate automatically when text is inserted or deleted
so they stay with the surrounding characters. Functions that expect an argument to be a
position (an integer), but accept a marker as a substitute, normally ignore which buffer the
marker points into; they convert the marker to an integer, and use that integer, exactly as
if you had passed the integer as the argument, even if the marker points to the “wrong”
buffer. A marker that points nowhere cannot convert to an integer; using it instead of an
integer causes an error. See Chapter 31 [Markers], page 572.
See also the “field” feature (see Section 32.19.11 [Fields], page 630), which provides
functions that are used by many cursor-motion commands.
30.1 Point
Point is a special buffer position used by many editing commands, including the self-
inserting typed characters and text insertion functions. Other commands move point
through the text to allow editing and insertion at different places.
Like other positions, point designates a place between two characters (or before the first
character, or after the last character), rather than a particular character. Usually terminals
display the cursor over the character that immediately follows point; point is actually before
the character on which the cursor sits.
The value of point is a number no less than 1, and no greater than the buffer size plus 1.
If narrowing is in effect (see Section 30.4 [Narrowing], page 569), then point is constrained
to fall within the accessible portion of the buffer (possibly at one end of it).
Each buffer has its own value of point, which is independent of the value of point in
other buffers. Each window also has a value of point, which is independent of the value of
point in other windows on the same buffer. This is why point can have different values in
various windows that display the same buffer. When a buffer appears in only one window,
the buffer’s point and the window’s point normally have the same value, so the distinction
is rarely important. See Section 28.9 [Window Point], page 511, for more details.
point [Function]
This function returns the value of point in the current buffer, as an integer.
(point)
⇒ 175
point-min [Function]
This function returns the minimum accessible value of point in the current buffer.
This is normally 1, but if narrowing is in effect, it is the position of the start of the
region that you narrowed to. (See Section 30.4 [Narrowing], page 569.)
Chapter 30: Positions 560
point-max [Function]
This function returns the maximum accessible value of point in the current buffer.
This is (1+ (buffer-size)), unless narrowing is in effect, in which case it is the
position of the end of the region that you narrowed to. (See Section 30.4 [Narrowing],
page 569.)
buffer-end flag [Function]
This function returns (point-max) if flag is greater than 0, (point-min) otherwise.
The argument flag must be a number.
buffer-size &optional buffer [Function]
This function returns the total number of characters in the current buffer. In the
absence of any narrowing (see Section 30.4 [Narrowing], page 569), point-max returns
a value one larger than this.
If you specify a buffer, buffer, then the value is the size of buffer.
(buffer-size)
⇒ 35
(point-max)
⇒ 36
30.2 Motion
Motion functions change the value of point, either relative to the current value of point,
relative to the beginning or end of the buffer, or relative to the edges of the selected window.
See Section 30.1 [Point], page 559.
words-include-escapes [Variable]
This variable affects the behavior of forward-word and everything that uses it. If
it is non-nil, then characters in the “escape” and “character quote” syntax classes
count as part of words. Otherwise, they do not.
inhibit-field-text-motion [Variable]
If this variable is non-nil, certain motion functions including forward-word,
forward-sentence, and forward-paragraph ignore field boundaries.
This function does not move point across a field boundary (see Section 32.19.11
[Fields], page 630) unless doing so would move beyond there to a different line; there-
fore, if count is nil or 1, and point starts at a field boundary, point does not move.
To ignore field boundaries, either bind inhibit-field-text-motion to t, or use the
forward-line function instead. For instance, (forward-line 0) does the same thing
as (beginning-of-line), except that it ignores field boundaries.
If this function reaches the end of the buffer (or of the accessible portion, if narrowing
is in effect), it positions point there. No error is signaled.
Also see the functions bolp and eolp in Section 32.1 [Near Point], page 581. These
functions do not move point, but test whether it is already at the beginning or end of a
line.
For example, to find the buffer position of column col of screen line line of a certain
window, pass the window’s display start location as from and the window’s upper-left
coordinates as frompos. Pass the buffer’s (point-max) as to, to limit the scan to the
end of the accessible portion of the buffer, and pass line and col as topos. Here’s a
function that does this:
(defun coordinates-of-position (col line)
(car (compute-motion (window-start)
’(0 . 0)
(point-max)
(cons col line)
(window-width)
(cons (window-hscroll) 0)
(selected-window))))
When you use compute-motion for the minibuffer, you need to use minibuffer-
prompt-width to get the horizontal position of the beginning of the first screen line.
See Section 20.12 [Minibuffer Contents], page 301.
(forward-sexp 3)
⇒ nil
beginning-of-defun-function [Variable]
If non-nil, this variable holds a function for finding the beginning of a defun. The
function beginning-of-defun calls this function instead of using its normal method.
end-of-defun-function [Variable]
If non-nil, this variable holds a function for finding the end of a defun. The function
end-of-defun calls this function instead of using its normal method.
30.3 Excursions
It is often useful to move point “temporarily” within a localized portion of the program,
or to switch buffers temporarily. This is called an excursion, and it is done with the save-
excursion special form. This construct initially remembers the identity of the current
buffer, and its values of point and the mark, and restores them after the completion of the
excursion.
The forms for saving and restoring the configuration of windows are described elsewhere
(see Section 28.18 [Window Configurations], page 526, and see Section 29.12 [Frame Con-
figurations], page 546).
Chapter 30: Positions 569
Warning: Ordinary insertion of text adjacent to the saved point value relocates the
saved value, just as it relocates all markers. More precisely, the saved value is a marker
with insertion type nil. See Section 31.5 [Marker Insertion Types], page 576. Therefore,
when the saved point value is restored, it normally comes before the inserted text.
Although save-excursion saves the location of the mark, it does not prevent functions
which modify the buffer from setting deactivate-mark, and thus causing the deactivation
of the mark after the command finishes. See Section 31.7 [The Mark], page 577.
30.4 Narrowing
Narrowing means limiting the text addressable by Emacs editing commands to a limited
range of characters in a buffer. The text that remains addressable is called the accessible
portion of the buffer.
Narrowing is specified with two buffer positions which become the beginning and end
of the accessible portion. For most editing commands and most Emacs primitives, these
positions replace the values of the beginning and end of the buffer. While narrowing is in
effect, no text outside the accessible portion is displayed, and point cannot move outside
the accessible portion.
Chapter 30: Positions 570
Values such as positions or line numbers, which usually count from the beginning of the
buffer, do so despite narrowing, but the functions which use them refuse to operate on text
that is inaccessible.
The commands for saving buffers are unaffected by narrowing; they save the entire buffer
regardless of any narrowing.
widen [Command]
This function cancels any narrowing in the current buffer, so that the entire contents
are accessible. This is called widening. It is equivalent to the following expression:
(narrow-to-region 1 (1+ (buffer-size)))
(save-excursion
(save-restriction
(goto-char 1)
(forward-line 2)
(narrow-to-region 1 (point))
(goto-char (point-min))
(replace-string "foo" "bar")))
31 Markers
A marker is a Lisp object used to specify a position in a buffer relative to the surrounding
text. A marker changes its offset from the beginning of the buffer automatically whenever
text is inserted or deleted, so that it stays with the two characters on either side of it.
;; m1 is updated appropriately.
m1
⇒ #<marker at 101 in markers.texi>
make-marker [Function]
This function returns a newly created marker that does not point anywhere.
(make-marker)
⇒ #<marker in no buffer>
point-marker [Function]
This function returns a new marker that points to the present position of point in the
current buffer. See Section 30.1 [Point], page 559. For an example, see copy-marker,
below.
point-min-marker [Function]
This function returns a new marker that points to the beginning of the accessible
portion of the buffer. This will be the beginning of the buffer unless narrowing is in
effect. See Section 30.4 [Narrowing], page 569.
point-max-marker [Function]
This function returns a new marker that points to the end of the accessible portion
of the buffer. This will be the end of the buffer unless narrowing is in effect. See
Section 30.4 [Narrowing], page 569.
Here are examples of this function and point-min-marker, shown in a buffer con-
taining a version of the source file for the text of this chapter.
(point-min-marker)
⇒ #<marker at 1 in markers.texi>
(point-max-marker)
⇒ #<marker at 15573 in markers.texi>
(copy-marker 20000)
⇒ #<marker at 7572 in markers.texi>
An error is signaled if marker is neither a marker nor an integer.
Two distinct markers are considered equal (even though not eq) to each other if they
have the same position and buffer, or if they both point nowhere.
(setq p (point-marker))
⇒ #<marker at 2139 in markers.texi>
(eq p q)
⇒ nil
(equal p q)
⇒ t
Most functions that create markers, without an argument allowing to specify the inser-
tion type, create them with insertion type nil. Also, the mark has, by default, insertion
type nil.
mark-marker [Function]
This function returns the marker that represents the current buffer’s mark. It is not
a copy, it is the marker used internally. Therefore, changing this marker’s position
will directly affect the buffer’s mark. Don’t do that unless that is the effect you want.
(setq m (mark-marker))
⇒ #<marker at 3420 in markers.texi>
Chapter 31: Markers 578
(set-marker m 100)
⇒ #<marker at 100 in markers.texi>
(mark-marker)
⇒ #<marker at 100 in markers.texi>
Like any marker, this marker can be set to point at any buffer you like. If you make
it point at any buffer other than the one of which it is the mark, it will yield perfectly
consistent, but rather odd, results. We recommend that you not do it!
pop-mark [Function]
This function pops off the top element of mark-ring and makes that mark become
the buffer’s actual mark. This does not move point in the buffer, and it does nothing
if mark-ring is empty. It deactivates the mark.
The return value is not meaningful.
The next two functions signal an error if the mark does not point anywhere. If Transient
Mark mode is enabled and mark-even-if-inactive is nil, they also signal an error if the
mark is inactive.
region-beginning [Function]
This function returns the position of the beginning of the region (as an integer). This
is the position of either point or the mark, whichever is smaller.
region-end [Function]
This function returns the position of the end of the region (as an integer). This is the
position of either point or the mark, whichever is larger.
Few programs need to use the region-beginning and region-end functions. A com-
mand designed to operate on a region should normally use interactive with the ‘r’ spec-
ification to find the beginning and end of the region. This lets other Lisp programs specify
the bounds explicitly as arguments. (See Section 21.2.2 [Interactive Codes], page 307.)
Chapter 32: Text 581
32 Text
This chapter describes the functions that deal with the text in a buffer. Most examine,
insert, or delete text in the current buffer, often operating at point or on text adjacent to
point. Many are interactive. All the functions that change the text provide for undoing the
changes (see Section 32.9 [Undo], page 596).
Many text-related functions operate on a region of text defined by two buffer positions
passed in arguments named start and end. These arguments should be either markers (see
Chapter 31 [Markers], page 572) or numeric character positions (see Chapter 30 [Positions],
page 559). The order of these arguments does not matter; it is all right for start to be
the end of the region and end the beginning. For example, (delete-region 1 10) and
(delete-region 10 1) are equivalent. An args-out-of-range error is signaled if either
start or end is outside the accessible portion of the buffer. In an interactive call, point and
the mark are used for these arguments.
Throughout this chapter, “text” refers to the characters in the buffer, together with their
properties (when relevant). Keep in mind that point is always between two characters, and
the cursor appears on the character after point.
(char-to-string (preceding-char))
⇒ "a"
(char-to-string (following-char))
⇒ "c"
preceding-char [Function]
This function returns the character preceding point in the current buffer. See above,
under following-char, for an example. If point is at the beginning of the buffer,
preceding-char returns 0.
bobp [Function]
This function returns t if point is at the beginning of the buffer. If narrowing is
in effect, this means the beginning of the accessible portion of the text. See also
point-min in Section 30.1 [Point], page 559.
eobp [Function]
This function returns t if point is at the end of the buffer. If narrowing is in effect,
this means the end of accessible portion of the text. See also point-max in See
Section 30.1 [Point], page 559.
bolp [Function]
This function returns t if point is at the beginning of a line. See Section 30.2.4 [Text
Lines], page 562. The beginning of the buffer (or of its accessible portion) always
counts as the beginning of a line.
eolp [Function]
This function returns t if point is at the end of a line. The end of the buffer (or of
its accessible portion) is always considered the end of a line.
(buffer-substring 1 10)
⇒ "This is t"
(buffer-substring (point-max) 10)
⇒ "he contents of buffer foo\n"
If the text being copied has any text properties, these are copied into the string along
with the characters they belong to. See Section 32.19 [Text Properties], page 615.
However, overlays (see Section 38.9 [Overlays], page 754) in the buffer and their
properties are ignored, not copied.
For example, if Font-Lock mode is enabled, you might get results like these:
(buffer-substring 1 10)
⇒ #("This is t" 0 1 (fontified t) 1 9 (fontified t))
buffer-substring-filters [Variable]
This variable should be a list of functions that accept a single argument, a string,
and return a string. filter-buffer-substring passes the buffer substring to the
first function in this list, and the return value of each function is passed to the next
function. The return value of the last function is used as the return value of filter-
buffer-substring.
As a special convention, point is set to the start of the buffer text being operated on
(i.e., the start argument for filter-buffer-substring) before these functions are
called.
If this variable is nil, no filtering is performed.
Chapter 32: Text 584
buffer-string [Function]
This function returns the contents of the entire accessible portion of the current buffer
as a string. It is equivalent to
(buffer-substring (point-min) (point-max))
---------- Buffer: foo ----------
This is the contents of buffer foo
(buffer-string)
⇒ "This is the contents of buffer foo\n"
(thing-at-point ’word)
⇒ "Peace"
(thing-at-point ’line)
⇒ "Gentlemen may cry ‘‘Peace! Peace!,’’\n"
(thing-at-point ’whitespace)
⇒ nil
substring in the same way. You can use nil for buffer1, buffer2, or both to stand for
the current buffer.
The value is negative if the first substring is less, positive if the first is greater, and
zero if they are equal. The absolute value of the result is one plus the index of the
first differing characters within the substrings.
This function ignores case when comparing characters if case-fold-search is non-
nil. It always ignores text properties.
Suppose the current buffer contains the text ‘foobarbar haha!rara!’; then in this
example the two substrings are ‘rbar ’ and ‘rara!’. The value is 2 because the first
substring is greater at the second character.
(compare-buffer-substrings nil 6 11 nil 16 21)
⇒ 2
This function is unlike the other insertion functions in that it relocates markers ini-
tially pointing at the insertion point, to point after the inserted text. If an overlay
begins at the insertion point, the inserted text falls outside the overlay; if a nonempty
overlay ends at the insertion point, the inserted text falls inside that overlay.
See Section 32.19.6 [Sticky Properties], page 625, for other insertion functions that inherit
text properties from the nearby text in addition to inserting it. Whitespace inserted by
indentation functions also inherits text properties.
overwrite-mode [Variable]
This variable controls whether overwrite mode is in effect. The value should be
overwrite-mode-textual, overwrite-mode-binary, or nil. overwrite-mode-
textual specifies textual overwrite mode (treats newlines and tabs specially), and
overwrite-mode-binary specifies binary overwrite mode (treats newlines and tabs
like any other characters).
using the undo mechanism (see Section 32.9 [Undo], page 596). Some deletion functions do
save text in the kill ring in some special cases.
All of the deletion functions operate on the current buffer.
erase-buffer [Command]
This function deletes the entire text of the current buffer (not just the accessible por-
tion), leaving it empty. If the buffer is read-only, it signals a buffer-read-only error;
if some of the text in it is read-only, it signals a text-read-only error. Otherwise,
it deletes the text without asking for any confirmation. It returns nil.
Normally, deleting a large amount of text from a buffer inhibits further auto-saving
of that buffer “because it has shrunk.” However, erase-buffer does not do this, the
idea being that the future text is not really related to the former text, and its size
should not be compared with that of the former text.
tab. If killp is non-nil, then the command saves the deleted characters in the kill
ring.
Conversion of tabs to spaces happens only if count is positive. If it is negative, exactly
−count characters after point are deleted.
In an interactive call, count is the numeric prefix argument, and killp is the unpro-
cessed prefix argument. Therefore, if a prefix argument is supplied, the text is saved
in the kill ring. If no prefix argument is supplied, then one character is deleted, but
not saved in the kill ring.
The value returned is always nil.
backward-delete-char-untabify-method [User Option]
This option specifies how backward-delete-char-untabify should deal with white-
space. Possible values include untabify, the default, meaning convert a tab to many
spaces and delete one; hungry, meaning delete all tabs and spaces before point with
one command; all meaning delete all tabs, spaces and newlines before point, and
nil, meaning do nothing special for whitespace characters.
nil, delete-indentation joins this line to the following line instead. The function
returns nil.
If there is a fill prefix, and the second of the lines being joined starts with the pre-
fix, then delete-indentation deletes the fill prefix before joining the lines. See
Section 32.12 [Margins], page 602.
In the example below, point is located on the line starting ‘events’, and it makes no
difference if there are trailing spaces in the preceding line.
---------- Buffer: foo ----------
When in the course of human
? events, it becomes necessary
---------- Buffer: foo ----------
(delete-indentation)
⇒ nil
After the lines are joined, the function fixup-whitespace is responsible for deciding
whether to leave a space at the junction.
fixup-whitespace [Command]
This function replaces all the horizontal whitespace surrounding point with either one
space or no space, according to the context. It returns nil.
At the beginning or end of a line, the appropriate amount of space is none. Before
a character with close parenthesis syntax, or after a character with open parenthesis
or expression-prefix syntax, no space is also appropriate. Otherwise, one space is
appropriate. See Section 35.2.1 [Syntax Class Table], page 685.
In the example below, fixup-whitespace is called the first time with point before
the word ‘spaces’ in the first line. For the second invocation, point is directly after
the ‘(’.
---------- Buffer: foo ----------
This has too many ?spaces
This has too many spaces at the start of (? this list)
---------- Buffer: foo ----------
(fixup-whitespace)
⇒ nil
(fixup-whitespace)
⇒ nil
delete-blank-lines [Command]
This function deletes blank lines surrounding point. If point is on a blank line with
one or more blank lines before or after it, then all but one of them are deleted. If
point is on an isolated blank line, then it is deleted. If point is on a nonblank line,
the command deletes all blank lines immediately following it.
A blank line is defined as a line containing only tabs and spaces.
delete-blank-lines returns nil.
32.8.3 Yanking
Yanking means inserting text from the kill ring, but it does not insert the text blindly. Yank
commands and some other commands use insert-for-yank to perform special processing
on the text that they copy into the buffer.
insert-for-yank string [Function]
This function normally works like insert except that it doesn’t insert the text prop-
erties in the yank-excluded-properties list. However, if any part of string has a
non-nil yank-handler text property, that property can do various special processing
on that part of the text being inserted.
insert-buffer-substring-as-yank buf &optional start end [Function]
This function resembles insert-buffer-substring except that it doesn’t insert the
text properties in the yank-excluded-properties list.
Chapter 32: Text 593
You can put a yank-handler text property on all or part of the text to control how
it will be inserted if it is yanked. The insert-for-yank function looks for that property.
The property value must be a list of one to four elements, with the following format (where
elements after the first may be omitted):
(function param noexclude undo )
Here is what the elements do:
function When function is present and non-nil, it is called instead of insert to insert
the string. function takes one argument—the string to insert.
param If param is present and non-nil, it replaces string (or the part of string being
processed) as the object passed to function (or insert); for example, if function
is yank-rectangle, param should be a list of strings to insert as a rectangle.
noexclude If noexclude is present and non-nil, the normal removal of the yank-excluded-
properties is not performed; instead function is responsible for removing those
properties. This may be necessary if function adjusts point before or after
inserting the object.
undo If undo is present and non-nil, it is a function that will be called by yank-pop
to undo the insertion of the current object. It is called with two arguments,
the start and end of the current region. function can set yank-undo-function
to override the undo value.
This is allowed only immediately after a yank or another yank-pop. At such a time,
the region contains text that was just inserted by yanking. yank-pop deletes that
text and inserts in its place a different piece of killed text. It does not add the deleted
text to the kill ring, since it is already in the kill ring somewhere. It does however
rotate the kill ring to place the newly yanked string at the front.
If arg is nil, then the replacement text is the previous element of the kill ring. If
arg is numeric, the replacement is the argth previous kill. If arg is negative, a more
recent kill is the replacement.
The sequence of kills in the kill ring wraps around, so that after the oldest one comes
the newest one, and before the newest one goes the oldest.
The return value is always nil.
yank-undo-function [Variable]
If this variable is non-nil, the function yank-pop uses its value instead of delete-
region to delete the text inserted by the previous yank or yank-pop command. The
value must be a function of two arguments, the start and end of the current region.
The function insert-for-yank automatically sets this variable according to the undo
element of the yank-handler text property, if there is one.
If yank-handler is non-nil, this puts that value onto the string of killed text, as a
yank-handler property. See Section 32.8.3 [Yanking], page 592. Note that if yank-
handler is nil, then kill-new copies any yank-handler properties present on string
onto the kill ring, as it does with other text properties.
kill-append string before-p &optional yank-handler [Function]
This function appends the text string to the first entry in the kill ring and makes the
yanking pointer point to the combined entry. Normally string goes at the end of the
entry, but if before-p is non-nil, it goes at the beginning. This function also invokes
the value of interprogram-cut-function (see below). This handles yank-handler
just like kill-new, except that if yank-handler is different from the yank-handler
property of the first entry of the kill ring, kill-append pushes the concatenated
string onto the kill ring, instead of replacing the original first entry with it.
interprogram-paste-function [Variable]
This variable provides a way of transferring killed text from other programs, when
you are using a window system. Its value should be nil or a function of no arguments.
If the value is a function, current-kill calls it to get the “most recent kill.” If the
function returns a non-nil value, then that value is used as the “most recent kill.” If
it returns nil, then the front of the kill ring is used.
The normal use of this hook is to get the window system’s primary selection as the
most recent kill, even if the selection belongs to another application. See Section 29.18
[Window System Selections], page 550.
interprogram-cut-function [Variable]
This variable provides a way of communicating killed text to other programs, when
you are using a window system. Its value should be nil or a function of one required
and one optional argument.
If the value is a function, kill-new and kill-append call it with the new first element
of the kill ring as the first argument. The second, optional, argument has the same
meaning as the push argument to x-set-cut-buffer (see [Definition of x-set-cut-
buffer], page 551) and only affects the second and later cut buffers.
The normal use of this hook is to set the window system’s primary selection (and first
cut buffer) from the newly killed text. See Section 29.18 [Window System Selections],
page 550.
that the variable’s purpose is to identify one element of the list for use by the next yank
command.
The value of kill-ring-yank-pointer is always eq to one of the links in the kill ring
list. The element it identifies is the car of that link. Kill commands, which change the kill
ring, also set this variable to the value of kill-ring. The effect is to rotate the ring so
that the newly killed text is at the front.
Here is a diagram that shows the variable kill-ring-yank-pointer pointing to the sec-
ond entry in the kill ring ("some text" "a different piece of text" "yet older text").
kill-ring ---- kill-ring-yank-pointer
| |
| v
| --- --- --- --- --- ---
--> | | |------> | | |--> | | |--> nil
--- --- --- --- --- ---
| | |
| | |
| | -->"yet older text"
| |
| --> "a different piece of text"
|
--> "some text"
This state of affairs might occur after C-y (yank) immediately followed by M-y (yank-pop).
kill-ring [Variable]
This variable holds the list of killed text sequences, most recently killed first.
kill-ring-yank-pointer [Variable]
This variable’s value indicates which element of the kill ring is at the “front” of the
ring for yanking. More precisely, the value is a tail of the value of kill-ring, and its
car is the kill string that C-y should yank.
kill-ring-max [User Option]
The value of this variable is the maximum length to which the kill ring can grow,
before elements are thrown away at the end. The default value for kill-ring-max is
60.
32.9 Undo
Most buffers have an undo list, which records all changes made to the buffer’s text so that
they can be undone. (The buffers that don’t have one are usually special-purpose buffers
for which Emacs assumes that undoing is not useful. In particular, any buffer whose name
begins with a space has its undo recording off by default; see Section 27.3 [Buffer Names],
page 484.) All the primitives that modify the text in the buffer automatically add elements
to the front of the undo list, which is in the variable buffer-undo-list.
buffer-undo-list [Variable]
This buffer-local variable’s value is the undo list of the current buffer. A value of t
disables the recording of undo information.
Chapter 32: Text 597
The editor command loop automatically creates an undo boundary before each key
sequence is executed. Thus, each undo normally undoes the effects of one command.
Self-inserting input characters are an exception. The command loop makes a bound-
ary for the first such character; the next 19 consecutive self-inserting input characters
do not make boundaries, and then the 20th does, and so on as long as self-inserting
characters continue.
All buffer modifications add a boundary whenever the previous undoable change was
made in some other buffer. This is to ensure that each command makes a boundary
in each buffer where it makes changes.
Calling this function explicitly is useful for splitting the effects of a command into
more than one unit. For example, query-replace calls undo-boundary after each
replacement, so that the user can undo individual replacements one by one.
undo-in-progress [Variable]
This variable is normally nil, but the undo commands bind it to t. This is so
that various kinds of change hooks can tell when they’re being called for the sake of
undoing.
primitive-undo count list [Function]
This is the basic function for undoing elements of an undo list. It undoes the first
count elements of list, returning the rest of list.
primitive-undo adds elements to the buffer’s undo list when it changes the buffer.
Undo commands avoid confusion by saving the undo list value at the beginning of a
sequence of undo operations. Then the undo operations use and update the saved
value. The new elements added by undoing are not part of this saved value, so they
don’t interfere with continuing to undo.
This function does not bind undo-in-progress.
As editing continues, undo lists get longer and longer. To prevent them from using up all
available memory space, garbage collection trims them back to size limits you can set. (For
this purpose, the “size” of an undo list measures the cons cells that make up the list, plus
the strings of deleted text.) Three variables control the range of acceptable sizes: undo-
limit, undo-strong-limit and undo-outer-limit. In these variables, size is counted as
the number of bytes occupied, which includes both saved text and other data.
32.11 Filling
Filling means adjusting the lengths of lines (by moving the line breaks) so that they are
nearly (but no greater than) a specified maximum width. Additionally, lines can be justified,
which means inserting spaces to make the left and/or right margins line up precisely. The
width is controlled by the variable fill-column. For ease of reading, lines should be no
longer than 70 or so columns.
You can use Auto Fill mode (see Section 32.14 [Auto Filling], page 604) to fill text
automatically as you insert it, but changes to existing text may leave it improperly filled.
Then you must fill the text explicitly.
Most of the commands in this section return values that are not meaningful. All the
functions that do filling take note of the current left margin, current right margin, and
current justification style (see Section 32.12 [Margins], page 602). If the current justification
style is none, the filling functions don’t actually do anything.
Chapter 32: Text 600
Several of the filling functions have an argument justify. If it is non-nil, that requests
some kind of justification. It can be left, right, full, or center, to request a specific
style of justification. If it is t, that means to use the current justification style for this part
of the text (see current-justification, below). Any other value is treated as full.
When you call the filling functions interactively, using a prefix argument implies the
value full for justify.
fill-paragraph justify [Command]
This command fills the paragraph at or after point. If justify is non-nil, each line is
justified as well. It uses the ordinary paragraph motion commands to find paragraph
boundaries. See section “Paragraphs” in The GNU Emacs Manual.
fill-region start end &optional justify nosqueeze to-eop [Command]
This command fills each of the paragraphs in the region from start to end. It justifies
as well if justify is non-nil.
If nosqueeze is non-nil, that means to leave whitespace other than line breaks un-
touched. If to-eop is non-nil, that means to keep filling to the end of the paragraph—
or the next hard newline, if use-hard-newlines is enabled (see below).
The variable paragraph-separate controls how to distinguish paragraphs. See Sec-
tion 34.8 [Standard Regexps], page 683.
fill-individual-paragraphs start end &optional justify [Command]
citation-regexp
This command fills each paragraph in the region according to its individual fill prefix.
Thus, if the lines of a paragraph were indented with spaces, the filled paragraph will
remain indented in the same fashion.
The first two arguments, start and end, are the beginning and end of the region to be
filled. The third and fourth arguments, justify and citation-regexp, are optional. If
justify is non-nil, the paragraphs are justified as well as filled. If citation-regexp is
non-nil, it means the function is operating on a mail message and therefore should
not fill the header lines. If citation-regexp is a string, it is used as a regular expression;
if it matches the beginning of a line, that line is treated as a citation marker.
Ordinarily, fill-individual-paragraphs regards each change in indentation as
starting a new paragraph. If fill-individual-varying-indent is non-nil, then
only separator lines separate paragraphs. That mode can handle indented paragraphs
with additional indentation on the first line.
fill-individual-varying-indent [User Option]
This variable alters the action of fill-individual-paragraphs as described above.
fill-region-as-paragraph start end &optional justify nosqueeze [Command]
squeeze-after
This command considers a region of text as a single paragraph and fills it. If the
region was made up of many paragraphs, the blank lines between paragraphs are
removed. This function justifies as well as filling when justify is non-nil.
If nosqueeze is non-nil, that means to leave whitespace other than line breaks un-
touched. If squeeze-after is non-nil, it specifies a position in the region, and means
don’t canonicalize spaces before that position.
Chapter 32: Text 601
current-justification [Function]
This function returns the proper justification style to use for filling the text around
point.
This returns the value of the justification text property at point, or the variable
default-justification if there is no such text property. However, it returns nil rather
than none to mean “don’t justify”.
fill-paragraph-function [Variable]
This variable provides a way for major modes to override the filling of paragraphs.
If the value is non-nil, fill-paragraph calls this function to do the work. If the
function returns a non-nil value, fill-paragraph assumes the job is done, and
immediately returns that value.
The usual use of this feature is to fill comments in programming language modes. If
the function needs to fill a paragraph in the usual way, it can do so as follows:
(let ((fill-paragraph-function nil))
(fill-paragraph arg))
Chapter 32: Text 602
use-hard-newlines [Variable]
If this variable is non-nil, the filling functions do not delete newlines that have the
hard text property. These “hard newlines” act as paragraph separators.
default-fill-column [Variable]
The value of this variable is the default value for fill-column in buffers that do not
override it. This is the same as (default-value ’fill-column).
The default value for default-fill-column is 70.
current-left-margin [Function]
This function returns the proper left margin value to use for filling the text around
point. The value is the sum of the left-margin property of the character at the start
of the current line (or zero if none), and the value of the variable left-margin.
current-fill-column [Function]
This function returns the proper fill column value to use for filling the text around
point. The value is the value of the fill-column variable, minus the value of the
right-margin property of the character after point.
Chapter 32: Text 603
indent-to-left-margin [Function]
This function adjusts the indentation at the beginning of the current line to the value
specified by the variable left-margin. (That may involve either inserting or deleting
whitespace.) This function is value of indent-line-function in Paragraph-Indent
Text mode.
left-margin [Variable]
This variable specifies the base left margin column. In Fundamental mode, C-j in-
dents to this column. This variable automatically becomes buffer-local when set in
any fashion.
fill-nobreak-predicate [Variable]
This variable gives major modes a way to specify not to break a line at certain places.
Its value should be a list of functions. Whenever filling considers breaking the line at
a certain place in the buffer, it calls each of these functions with no arguments and
with point located at that place. If any of the functions returns non-nil, then the
line won’t be broken there.
line starting with this prefix wouldn’t look like the start of a paragraph. Should this
happen, the function signals the anomaly by returning nil instead.
In detail, fill-context-prefix does this:
1. It takes a candidate for the fill prefix from the first line—it tries first the function
in adaptive-fill-function (if any), then the regular expression adaptive-
fill-regexp (see below). The first non-nil result of these, or the empty string
if they’re both nil, becomes the first line’s candidate.
2. If the paragraph has as yet only one line, the function tests the validity of the
prefix candidate just found. The function then returns the candidate if it’s valid,
or a string of spaces otherwise. (see the description of adaptive-fill-first-
line-regexp below).
3. When the paragraph already has two lines, the function next looks for a prefix
candidate on the second line, in just the same way it did for the first line. If it
doesn’t find one, it returns nil.
4. The function now compares the two candidate prefixes heuristically: if the non-
whitespace characters in the line 2 candidate occur in the same order in the line
1 candidate, the function returns the line 2 candidate. Otherwise, it returns the
largest initial substring which is common to both candidates (which might be
the empty string).
adaptive-fill-regexp [User Option]
Adaptive Fill mode matches this regular expression against the text starting after
the left margin whitespace (if any) on a line; the characters it matches are that line’s
candidate for the fill prefix.
The default value matches whitespace with certain punctuation characters intermin-
gled.
adaptive-fill-first-line-regexp [User Option]
Used only in one-line paragraphs, this regular expression acts as an additional check
of the validity of the one available candidate fill prefix: the candidate must match
this regular expression, or match comment-start-skip. If it doesn’t, fill-context-
prefix replaces the candidate with a string of spaces “of the same width” as it.
The default value of this variable is "\\‘[ \t]*\\’", which matches only a string
of whitespace. The effect of this default is to force the fill prefixes found in one-line
paragraphs always to be pure whitespace.
adaptive-fill-function [User Option]
You can specify more complex ways of choosing a fill prefix automatically by setting
this variable to a function. The function is called with point after the left margin (if
any) of a line, and it must preserve point. It should return either “that line’s” fill
prefix or nil, meaning it has failed to determine a prefix.
Auto Fill mode also enables the functions that change the margins and justification style
to refill portions of the text. See Section 32.12 [Margins], page 602.
auto-fill-function [Variable]
The value of this buffer-local variable should be a function (of no arguments) to be
called after self-inserting a character from the table auto-fill-chars. It may be
nil, in which case nothing special is done in that case.
The value of auto-fill-function is do-auto-fill when Auto-Fill mode is enabled.
That is a function whose sole purpose is to implement the usual strategy for breaking
a line.
In older Emacs versions, this variable was named auto-fill-hook, but
since it is not called with the standard convention for hooks, it was re-
named to auto-fill-function in version 19.
normal-auto-fill-function [Variable]
This variable specifies the function to use for auto-fill-function, if and when Auto
Fill is turned on. Major modes can set buffer-local values for this variable to alter
how Auto Fill works.
auto-fill-chars [Variable]
A char table of characters which invoke auto-fill-function when self-inserted—
space and newline in most language environments. They have an entry t in the
table.
of point when sort-subr is called. Therefore, you should usually move point to
the beginning of the buffer before calling sort-subr.
This function can indicate there are no more sort records by leaving point at the
end of the buffer.
2. endrecfun is called with point within a record. It moves point to the end of the
record.
3. startkeyfun is called to move point from the start of a record to the start of the
sort key. This argument is optional; if it is omitted, the whole record is the sort
key. If supplied, the function should either return a non-nil value to be used as
the sort key, or return nil to indicate that the sort key is in the buffer starting
at point. In the latter case, endkeyfun is called to find the end of the sort key.
4. endkeyfun is called to move point from the start of the sort key to the end of
the sort key. This argument is optional. If startkeyfun returns nil and this
argument is omitted (or nil), then the sort key extends to the end of the record.
There is no need for endkeyfun if startkeyfun returns a non-nil value.
The argument predicate is the function to use to compare keys. If keys are numbers,
it defaults to <; otherwise it defaults to string<.
Here forward-line moves point to the start of the next record, and end-of-line
moves point to the end of record. We do not pass the arguments startkeyfun and
endkeyfun, because the entire record is used as the sort key.
The sort-paragraphs function is very much the same, except that its sort-subr
call looks like this:
Chapter 32: Text 607
(sort-subr reverse
(function
(lambda ()
(while (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1))))
’forward-paragraph)
Markers pointing into any sort records are left with no useful position after sort-subr
returns.
For example, if you plan to sort all the lines in the region by the first word on each line
starting with the letter ‘f’, you should set record-regexp to ‘^.*$’ and set key-regexp
to ‘\<f\w*\>’. The resulting expression looks like this:
(sort-regexp-fields nil "^.*$" "\\<f\\w*\\>"
(region-beginning)
(region-end))
If you call sort-regexp-fields interactively, it prompts for record-regexp and key-
regexp in the minibuffer.
sort-lines reverse start end [Command]
This command alphabetically sorts lines in the region between start and end. If
reverse is non-nil, the sort is in reverse order.
sort-paragraphs reverse start end [Command]
This command alphabetically sorts paragraphs in the region between start and end.
If reverse is non-nil, the sort is in reverse order.
sort-pages reverse start end [Command]
This command alphabetically sorts pages in the region between start and end. If
reverse is non-nil, the sort is in reverse order.
sort-fields field start end [Command]
This command sorts lines in the region between start and end, comparing them
alphabetically by the fieldth field of each line. Fields are separated by whitespace
and numbered starting from 1. If field is negative, sorting is by the −fieldth field
from the end of the line. This command is useful for sorting tables.
sort-numeric-fields field start end [Command]
This command sorts lines in the region between start and end, comparing them
numerically by the fieldth field of each line. Fields are separated by whitespace and
numbered starting from 1. The specified field must contain a number in each line of
the region. Numbers starting with 0 are treated as octal, and numbers starting with
‘0x’ are treated as hexadecimal.
If field is negative, sorting is by the −fieldth field from the end of the line. This
command is useful for sorting tables.
sort-numeric-base [User Option]
This variable specifies the default radix for sort-numeric-fields to parse numbers.
sort-columns reverse &optional beg end [Command]
This command sorts the lines in the region between beg and end, comparing them
alphabetically by a certain range of columns. The column positions of beg and end
bound the range of columns to sort on.
If reverse is non-nil, the sort is in reverse order.
One unusual thing about this command is that the entire line containing position beg,
and the entire line containing position end, are included in the region sorted.
Note that sort-columns rejects text that contains tabs, because tabs could be split
across the specified columns. Use M-x untabify to convert tabs to spaces before
sorting.
Chapter 32: Text 609
When possible, this command actually works by calling the sort utility program.
32.17 Indentation
The indentation functions are used to examine, move to, and change whitespace that is at
the beginning of a line. Some of the functions can also change whitespace elsewhere on a
line. Columns and indentation count from zero at the left margin.
Chapter 32: Text 610
indent-relative-maybe [Command]
This command indents the current line like the previous nonblank line, by calling
indent-relative with t as the unindented-ok argument. The return value is unpre-
dictable.
Chapter 32: Text 613
If the previous nonblank line has no indent points beyond the current column, this
command does nothing.
If one end of the region is in the middle of a word, the part of the word within the
region is treated as an entire word.
When capitalize-region is called interactively, start and end are point and the
mark, with the smallest first.
---------- Buffer: foo ----------
This is the contents of the 5th foo.
---------- Buffer: foo ----------
(capitalize-region 1 44)
⇒ nil
When upcase-word is called interactively, count is set to the numeric prefix argument.
Its value is a cons cell whose car is the property value, the same value get-char-
property would return with the same arguments. Its cdr is the overlay in which the
property was found, or nil, if it was found as a text property or not found at all.
If position is at the end of object, both the car and the cdr of the value are nil.
char-property-alias-alist [Variable]
This variable holds an alist which maps property names to a list of alternative prop-
erty names. If a character does not specify a direct value for a property, the alter-
native property names are consulted in order; the first non-nil value is used. This
variable takes precedence over default-text-properties, and category properties
take precedence over this variable.
default-text-properties [Variable]
This variable holds a property list giving default values for text properties. Whenever
a character does not specify a value for a property, neither directly, through a category
symbol, or through char-property-alias-alist, the value stored in this list is used
instead. Here is an example:
(setq default-text-properties ’(foo 69)
char-property-alias-alist nil)
;; Make sure character 1 has no properties of its own.
(set-text-properties 1 2 nil)
;; What we get, when we ask, is the default value.
(get-text-property 1 ’foo)
⇒ 69
The argument props specifies which properties to add. It should have the form of
a property list (see Section 8.4 [Property Lists], page 107): a list whose elements
include the property names followed alternately by the corresponding values.
The return value is t if the function actually changed some property’s value; nil
otherwise (if props is nil or its values agree with those in the text).
For example, here is how to set the comment and face properties of a range of text:
(add-text-properties start end
’(comment t face highlight))
remove-text-properties start end props &optional object [Function]
This function deletes specified text properties from the text between start and end in
the string or buffer object. If object is nil, it defaults to the current buffer.
The argument props specifies which properties to delete. It should have the form of
a property list (see Section 8.4 [Property Lists], page 107): a list whose elements are
property names alternating with corresponding values. But only the names matter—
the values that accompany them are ignored. For example, here’s how to remove the
face property.
(remove-text-properties start end ’(face nil))
The return value is t if the function actually changed some property’s value; nil
otherwise (if props is nil or if no character in the specified text had any of those
properties).
To remove all text properties from certain text, use set-text-properties and specify
nil for the new property list.
remove-list-of-text-properties start end list-of-properties [Function]
&optional object
Like remove-text-properties except that list-of-properties is a list of property
names only, not an alternating list of property names and values.
set-text-properties start end props &optional object [Function]
This function completely replaces the text property list for the text between start and
end in the string or buffer object. If object is nil, it defaults to the current buffer.
The argument props is the new property list. It should be a list whose elements are
property names alternating with corresponding values.
After set-text-properties returns, all the characters in the specified range have
identical properties.
If props is nil, the effect is to get rid of all properties from the specified range of
text. Here’s an example:
(set-text-properties start end nil)
Do not rely on the return value of this function.
The easiest way to make a string with text properties is with propertize:
propertize string &rest properties [Function]
This function returns a copy of string which has the text properties properties. These
properties apply to all the characters in the string that is returned. Here is an example
that constructs a string with a face property and a mouse-face property:
Chapter 32: Text 618
See also the function buffer-substring-no-properties (see Section 32.2 [Buffer Con-
tents], page 582) which copies text from the buffer but does not copy its properties.
(point-max))))
Process text from point to next-change . . .
(goto-char next-change)))
font-lock-face
The font-lock-face property is the same in all respects as the face property,
but its state of activation is controlled by font-lock-mode. This can be ad-
vantageous for special buffers which are not intended to be user-editable, or for
static areas of text which are always fontified in the same way. See Section 23.6.6
[Precalculated Fontification], page 419.
Strictly speaking, font-lock-face is not a built-in text property; rather, it
is implemented in Font Lock mode using char-property-alias-alist. See
Section 32.19.1 [Examining Properties], page 615.
This property is new in Emacs 22.1.
mouse-face
The property mouse-face is used instead of face when the mouse is on or
near the character. For this purpose, “near” means that all text between the
character and where the mouse is have the same mouse-face property value.
fontified
This property says whether the text is ready for display. If nil, Emacs’s
redisplay routine calls the functions in fontification-functions (see Sec-
tion 38.12.7 [Auto Faces], page 773) to prepare this part of the buffer before it
is displayed. It is used internally by the “just in time” font locking code.
display This property activates various features that change the way text is displayed.
For example, it can make text appear taller or shorter, higher or lower, wider
or narrow, or replaced with an image. See Section 38.15 [Display Property],
page 783.
help-echo
If text has a string as its help-echo property, then when you move the mouse
onto that text, Emacs displays that string in the echo area, or in the tooltip
window (see section “Tooltips” in The GNU Emacs Manual).
If the value of the help-echo property is a function, that function is called
with three arguments, window, object and pos and should return a help string
or nil for none. The first argument, window is the window in which the help
was found. The second, object, is the buffer, overlay or string which had the
help-echo property. The pos argument is as follows:
• If object is a buffer, pos is the position in the buffer.
• If object is an overlay, that overlay has a help-echo property, and pos is
the position in the overlay’s buffer.
• If object is a string (an overlay string or a string displayed with the display
property), pos is the position in that string.
If the value of the help-echo property is neither a function nor a string, it is
evaluated to obtain a help string.
You can alter the way help text is displayed by setting the variable show-help-
function (see [Help display], page 624).
This feature is used in the mode line and for other active text.
Chapter 32: Text 622
keymap The keymap property specifies an additional keymap for commands. When this
keymap applies, it is used for key lookup before the minor mode keymaps and
before the buffer’s local map. See Section 22.7 [Active Keymaps], page 353. If
the property value is a symbol, the symbol’s function definition is used as the
keymap.
The property’s value for the character before point applies if it is non-nil and
rear-sticky, and the property’s value for the character after point applies if it
is non-nil and front-sticky. (For mouse clicks, the position of the click is used
instead of the position of point.)
local-map
This property works like keymap except that it specifies a keymap to use instead
of the buffer’s local map. For most purposes (perhaps all purposes), it is better
to use the keymap property.
syntax-table
The syntax-table property overrides what the syntax table says about this
particular character. See Section 35.4 [Syntax Properties], page 690.
read-only
If a character has the property read-only, then modifying that character is
not allowed. Any command that would do so gets an error, text-read-only.
If the property value is a string, that string is used as the error message.
Insertion next to a read-only character is an error if inserting ordinary text
there would inherit the read-only property due to stickiness. Thus, you can
control permission to insert next to read-only text by controlling the stickiness.
See Section 32.19.6 [Sticky Properties], page 625.
Since changing properties counts as modifying the buffer, it is not possible to
remove a read-only property unless you know the special trick: bind inhibit-
read-only to a non-nil value and then remove the property. See Section 27.7
[Read Only Buffers], page 489.
invisible
A non-nil invisible property can make a character invisible on the screen.
See Section 38.6 [Invisible Text], page 748, for details.
intangible
If a group of consecutive characters have equal and non-nil intangible prop-
erties, then you cannot place point between them. If you try to move point
forward into the group, point actually moves to the end of the group. If you
try to move point backward into the group, point actually moves to the start
of the group.
If consecutive characters have unequal non-nil intangible properties, they
belong to separate groups; each group is separately treated as described above.
When the variable inhibit-point-motion-hooks is non-nil, the intangible
property is ignored.
field Consecutive characters with the same field property constitute a field. Some
motion functions including forward-word and beginning-of-line stop mov-
ing at a field boundary. See Section 32.19.11 [Fields], page 630.
Chapter 32: Text 623
cursor Normally, the cursor is displayed at the end of any overlay and text property
strings present at the current window position. You can place the cursor on
any desired character of these strings by giving that character a non-nil cursor
text property.
pointer This specifies a specific pointer shape when the mouse pointer is over this text
or image. See Section 29.17 [Pointer Shape], page 550, for possible pointer
shapes.
line-spacing
A newline can have a line-spacing text or overlay property that controls the
height of the display line ending with that newline. The property value overrides
the default frame line spacing and the buffer local line-spacing variable. See
Section 38.11 [Line Height], page 761.
line-height
A newline can have a line-height text or overlay property that controls the
total height of the display line ending in that newline. See Section 38.11 [Line
Height], page 761.
modification-hooks
If a character has the property modification-hooks, then its value should be
a list of functions; modifying that character calls all of those functions. Each
function receives two arguments: the beginning and end of the part of the buffer
being modified. Note that if a particular modification hook function appears on
several characters being modified by a single primitive, you can’t predict how
many times the function will be called.
If these functions modify the buffer, they should bind inhibit-modification-
hooks to t around doing so, to avoid confusing the internal mechanism that
calls these hooks.
Overlays also support the modification-hooks property, but the details are
somewhat different (see Section 38.9.2 [Overlay Properties], page 756).
insert-in-front-hooks
insert-behind-hooks
The operation of inserting text in a buffer also calls the functions listed in
the insert-in-front-hooks property of the following character and in the
insert-behind-hooks property of the preceding character. These functions
receive two arguments, the beginning and end of the inserted text. The func-
tions are called after the actual insertion takes place.
See also Section 32.26 [Change Hooks], page 638, for other hooks that are called
when you change text in a buffer.
point-entered
point-left
The special properties point-entered and point-left record hook functions
that report motion of point. Each time point moves, Emacs compares these
two property values:
• the point-left property of the character after the old location, and
Chapter 32: Text 624
right-margin
This property specifies an extra right margin for filling this part of the text.
left-margin
This property specifies an extra left margin for filling this part of the text.
justification
This property specifies the style of justification for filling this part of the text.
Here are the functions that insert text with inheritance of properties:
See Section 32.4 [Insertion], page 585, for the ordinary insertion functions which do not
inherit.
write-region-annotate-functions [Variable]
This variable’s value is a list of functions for write-region to run to encode text
properties in some fashion as annotations to the text being written in the file. See
Section 25.4 [Writing to Files], page 441.
Each function in the list is called with two arguments: the start and end of the region
to be written. These functions should not alter the contents of the buffer. Instead,
they should return lists indicating annotations to write in the file in addition to the
text in the buffer.
Each function should return a list of elements of the form (position . string ),
where position is an integer specifying the relative position within the text to be
written, and string is the annotation to add there.
Each list returned by one of these functions must be already sorted in increasing
order by position. If there is more than one function, write-region merges the lists
destructively into one sorted list.
When write-region actually writes the text from the buffer to the file, it intermixes
the specified annotations at the corresponding positions. All this takes place without
modifying the buffer.
after-insert-file-functions [Variable]
This variable holds a list of functions for insert-file-contents to call after inserting
a file’s contents. These functions should scan the inserted text for annotations, and
convert them to the text properties they stand for.
Each function receives one argument, the length of the inserted text; point indicates
the start of that text. The function should scan that text for annotations, delete
Chapter 32: Text 627
them, and create the text properties that the annotations specify. The function should
return the updated length of the inserted text, as it stands after those changes. The
value returned by one function becomes the argument to the next function.
These functions should always return with point at the beginning of the inserted text.
The intended use of after-insert-file-functions is for converting some sort of
textual annotations into actual text properties. But other uses may be possible.
We invite users to write Lisp programs to store and retrieve text properties in files,
using these hooks, and thus to experiment with various data formats and find good ones.
Eventually we hope users will produce good, general extensions we can install in Emacs.
We suggest not trying to handle arbitrary Lisp objects as text property names or values—
because a program that general is probably difficult to write, and slow. Instead, choose a
set of possible data types that are reasonably flexible, and not too hard to encode.
See Section 25.12 [Format Conversion], page 468, for a related feature.
buffer-access-fontify-functions [Variable]
This variable holds a list of functions for computing text properties. Before buffer-
substring copies the text and text properties for a portion of the buffer, it calls all
the functions in this list. Each of the functions receives two arguments that specify
the range of the buffer being accessed. (The buffer itself is always the current buffer.)
buffer-access-fontified-property [Variable]
If this variable’s value is non-nil, it is a symbol which is used as a text property
name. A non-nil value for that text property means, “the other text properties for
this character have already been computed.”
If all the characters in the range specified for buffer-substring have a non-nil value
for this property, buffer-substring does not call the buffer-access-fontify-
functions functions. It assumes these characters already have the right text proper-
ties, and just copies the properties they already have.
The normal way to use this feature is that the buffer-access-fontify-functions
functions add this property, as well as others, to the characters they operate on. That
way, they avoid being called over and over for the same text.
Chapter 32: Text 628
The first two arguments to add-text-properties specify the beginning and end of the
text.
The usual way to make the mouse do something when you click it on this text is to
define mouse-2 in the major mode’s keymap. The job of checking whether the click was on
clickable text is done by the command definition. Here is how Dired does it:
(defun dired-mouse-find-file-other-window (event)
"In Dired, visit the file or directory name you click on."
(interactive "e")
(let (window pos file)
(save-excursion
(setq window (posn-window (event-end event))
pos (posn-point (event-end event)))
(if (not (windowp window))
(error "No file chosen"))
(set-buffer (window-buffer window))
(goto-char pos)
(setq file (dired-get-file-for-visit)))
(if (file-directory-p file)
(or (and (cdr dired-subdir-alist)
(dired-goto-subdir file))
(progn
(select-window window)
(dired-other-window file)))
(select-window window)
(find-file-other-window (file-name-sans-versions file t)))))
The reason for the save-excursion construct is to avoid changing the current buffer. In this
case, Dired uses the functions posn-window and posn-point to determine which buffer the
Chapter 32: Text 629
a function If the condition is a valid function, func, then a position pos is inside a link
if (func pos ) evaluates to non-nil. The value returned by func serves as the
action code.
For example, here is how pcvs enables MOUSE-1 to follow links on file names
only:
Chapter 32: Text 630
anything else
If the condition value is anything else, then the position is inside a link and the
condition itself is the action code. Clearly you should only specify this kind of
condition on the text that constitutes a link.
The action code tells MOUSE-1 how to follow the link:
a string or vector
If the action code is a string or vector, the MOUSE-1 event is translated into
the first element of the string or vector; i.e., the action of the MOUSE-1 click
is the local or global binding of that character or symbol. Thus, if the action
code is "foo", MOUSE-1 translates into f. If it is [foo], MOUSE-1 translates
into FOO.
anything else
For any other non-nil action code, the mouse-1 event is translated into a
mouse-2 event at the same position.
To define MOUSE-1 to activate a button defined with define-button-type, give the
button a follow-link property with a value as specified above to determine how to follow
the link. For example, here is how Help mode handles MOUSE-1:
(define-button-type ’help-xref
’follow-link t
’action #’help-button-action)
To define MOUSE-1 on a widget defined with define-widget, give the widget a
:follow-link property with a value as specified above to determine how to follow the
link.
For example, here is how the link widget specifies that a MOUSE-1 click shall be
translated to RET:
(define-widget ’link ’item
"An embedded link."
:button-prefix ’widget-link-prefix
:button-suffix ’widget-link-suffix
:follow-link "\C-m"
:help-echo "Follow the link."
:format "%[%t%]")
You specify a field with a buffer position, pos. We think of each field as containing a
range of buffer positions, so the position you specify stands for the field containing that
position.
When the characters before and after pos are part of the same field, there is no doubt
which field contains pos: the one those characters both belong to. When pos is at a bound-
ary between fields, which field it belongs to depends on the stickiness of the field properties
of the two surrounding characters (see Section 32.19.6 [Sticky Properties], page 625). The
field whose property would be inherited by text inserted at pos is the field that contains
pos.
There is an anomalous case where newly inserted text at pos would not inherit the field
property from either side. This happens if the previous character’s field property is not
rear-sticky, and the following character’s field property is not front-sticky. In this case,
pos belongs to neither the preceding field nor the following field; the field functions treat it
as belonging to an empty field whose beginning and end are both at pos.
In all of these functions, if pos is omitted or nil, the value of point is used by default.
If narrowing is in effect, then pos should fall within the accessible portion. See Section 30.4
[Narrowing], page 569.
field-beginning &optional pos escape-from-edge limit [Function]
This function returns the beginning of the field specified by pos.
If pos is at the beginning of its field, and escape-from-edge is non-nil, then the return
value is always the beginning of the preceding field that ends at pos, regardless of the
stickiness of the field properties around pos.
If limit is non-nil, it is a buffer position; if the beginning of the field is before limit,
then limit will be returned instead.
field-end &optional pos escape-from-edge limit [Function]
This function returns the end of the field specified by pos.
If pos is at the end of its field, and escape-from-edge is non-nil, then the return value
is always the end of the following field that begins at pos, regardless of the stickiness
of the field properties around pos.
If limit is non-nil, it is a buffer position; if the end of the field is after limit, then
limit will be returned instead.
field-string &optional pos [Function]
This function returns the contents of the field specified by pos, as a string.
field-string-no-properties &optional pos [Function]
This function returns the contents of the field specified by pos, as a string, discarding
text properties.
delete-field &optional pos [Function]
This function deletes the text of the field specified by pos.
constrain-to-field new-pos old-pos &optional escape-from-edge [Function]
only-in-line inhibit-capture-property
This function “constrains” new-pos to the field that old-pos belongs to—in other
words, it returns the position closest to new-pos that is in the same field as old-pos.
Chapter 32: Text 632
If new-pos is nil, then constrain-to-field uses the value of point instead, and
moves point to the resulting position as well as returning it.
If old-pos is at the boundary of two fields, then the acceptable final positions depend
on the argument escape-from-edge. If escape-from-edge is nil, then new-pos must
be in the field whose field property equals what new characters inserted at old-
pos would inherit. (This depends on the stickiness of the field property for the
characters before and after old-pos.) If escape-from-edge is non-nil, new-pos can
be anywhere in the two adjacent fields. Additionally, if two fields are separated by
another field with the special value boundary, then any point within this special field
is also considered to be “on the boundary.”
Commands like C-a with no argumemt, that normally move backward to a specific
kind of location and stay there once there, probably should specify nil for escape-
from-edge. Other motion commands that check fields should probably pass t.
If the optional argument only-in-line is non-nil, and constraining new-pos in the
usual way would move it to a different line, new-pos is returned unconstrained. This
used in commands that move by line, such as next-line and beginning-of-line,
so that they respect field boundaries only in the case where they can still move to the
right line.
If the optional argument inhibit-capture-property is non-nil, and old-pos has a non-
nil property of that name, then any field boundaries are ignored.
You can cause constrain-to-field to ignore all field boundaries (and so never con-
strain anything) by binding the variable inhibit-field-text-motion to a non-nil
value.
Insertion of text at the border between intervals also raises questions that have no
satisfactory answer.
However, it is easy to arrange for editing to behave consistently for questions of the
form, “What are the properties of this character?” So we have decided these are the only
questions that make sense; we have not implemented asking questions about where intervals
start or end.
In practice, you can usually use the text property search functions in place of explicit
interval boundaries. You can think of them as finding the boundaries of intervals, assuming
that intervals are always coalesced whenever possible. See Section 32.19.3 [Property Search],
page 618.
Emacs also provides explicit intervals as a presentation feature; see Section 38.9 [Over-
lays], page 754.
(subst-char-in-region 1 20 ?i ?X)
⇒ nil
32.21 Registers
A register is a sort of variable used in Emacs editing that can hold a variety of different
kinds of values. Each register is named by a single character. All ASCII characters and
their meta variants (but with the exception of C-g) can be used to name registers. Thus,
there are 255 possible registers. A register is designated in Emacs Lisp by the character
that is its name.
register-alist [Variable]
This variable is an alist of elements of the form (name . contents ). Normally, there
is one element for each Emacs register that has been used.
The object name is a character (an integer) identifying the register.
Normally, this function inserts newline characters into the encoded text, to avoid
overlong lines. However, if the optional argument no-line-break is non-nil, these
newlines are not added, so the result string is just one long line.
2
For an explanation of what is an RFC, see the footnote in Section 32.23 [Base 64], page 635.
Chapter 32: Text 637
To use the change group, you must activate it. You must do this before making any
changes in the text of buffer.
After you activate the change group, any changes you make in that buffer become part
of it. Once you have made all the desired changes in the buffer, you must finish the change
group. There are two ways to do this: you can either accept (and finalize) all the changes,
or cancel them all.
Your code should use unwind-protect to make sure the group is always finished. The call
to activate-change-group should be inside the unwind-protect, in case the user types
C-g just after it runs. (This is one reason why prepare-change-group and activate-
change-group are separate functions, because normally you would call prepare-change-
group before the start of that unwind-protect.) Once you finish the group, don’t use the
handle again—in particular, don’t try to finish the same group twice.
Chapter 32: Text 638
To make a multibuffer change group, call prepare-change-group once for each buffer
you want to cover, then use nconc to combine the returned values, like this:
(nconc (prepare-change-group buffer-1)
(prepare-change-group buffer-2))
You can then activate the multibuffer change group with a single call to activate-
change-group, and finish it with a single call to accept-change-group or cancel-change-
group.
Nested use of several change groups for the same buffer works as you would expect.
Non-nested use of change groups for the same buffer will get Emacs confused, so don’t let it
happen; the first change group you start for any given buffer should be the last one finished.
before-change-functions [Variable]
This variable holds a list of functions to call before any buffer modification. Each
function gets two arguments, the beginning and end of the region that is about to
change, represented as integers. The buffer that is about to change is always the
current buffer.
after-change-functions [Variable]
This variable holds a list of functions to call after any buffer modification. Each
function receives three arguments: the beginning and end of the region just changed,
and the length of the text that existed before the change. All three arguments are
integers. The buffer that’s about to change is always the current buffer.
The length of the old text is the difference between the buffer positions before and
after that text as it was before the change. As for the changed text, its length is
simply the difference between the first two arguments.
Output of messages into the ‘*Messages*’ buffer does not call these functions.
Warning: if the changes you combine occur in widely scattered parts of the buffer,
this will still work, but it is not advisable, because it may lead to inefficient behavior
for some change hook functions.
The two variables above are temporarily bound to nil during the time that any of these
functions is running. This means that if one of these functions changes the buffer, that
change won’t run these functions. If you do want a hook function to make changes that run
these functions, make it bind these variables back to their usual values.
One inconvenient result of this protective feature is that you cannot have a function in
after-change-functions or before-change-functions which changes the value of that
variable. But that’s not a real limitation. If you want those functions to change the list of
functions to run, simply add one fixed function to the hook, and code that function to look
in another variable for other functions to call. Here is an example:
(setq my-own-after-change-functions nil)
(defun indirect-after-change-function (beg end len)
(let ((list my-own-after-change-functions))
(while list
(funcall (car list) beg end len)
(setq list (cdr list)))))
(add-hooks ’after-change-functions
’indirect-after-change-function)
first-change-hook [Variable]
This variable is a normal hook that is run whenever a buffer is changed that was
previously in the unmodified state.
inhibit-modification-hooks [Variable]
If this variable is non-nil, all of the change hooks are disabled; none of them run.
This affects all the hook variables described above in this section, as well as the hooks
attached to certain special text properties (see Section 32.19.4 [Special Properties],
page 620) and overlay properties (see Section 38.9.2 [Overlay Properties], page 756).
Chapter 33: Non-ASCII Characters 640
33 Non-ASCII Characters
This chapter covers the special issues relating to non-ASCII characters and how they are
stored in strings and buffers.
enable-multibyte-characters [Variable]
This variable specifies the current buffer’s text representation. If it is non-nil, the
buffer contains multibyte text; otherwise, it contains unibyte text.
You cannot set this variable directly; instead, use the function set-buffer-
multibyte to change a buffer’s representation.
default-enable-multibyte-characters [Variable]
This variable’s value is entirely equivalent to (default-value ’enable-multibyte-
characters), and setting this variable changes that default value. Setting the local
binding of enable-multibyte-characters in a specific buffer is not allowed, but
changing the default value is supported, and it is a reasonable thing to do, because
it has no effect on existing buffers.
The ‘--unibyte’ command line option does its job by setting the default value to nil
early in startup.
Chapter 33: Non-ASCII Characters 641
character in the unibyte non-ASCII range, 128 through 255. However, the functions
insert and insert-char do not perform this conversion.
The right value to use to select character set cs is (- (make-char cs ) 128). If the
value of nonascii-insert-offset is zero, then conversion actually uses the value for
the Latin 1 character set, rather than zero.
nonascii-translation-table [Variable]
This variable provides a more general alternative to nonascii-insert-offset. You
can use it to specify independently how to translate each code in the range of 128
through 255 into a multibyte character. The value should be a char-table, or nil. If
this is non-nil, it overrides nonascii-insert-offset.
The next three functions either return the argument string, or a newly created string
with no text properties.
(char-valid-p 65)
⇒ t
(char-valid-p 256)
⇒ nil
(char-valid-p 2248)
⇒ t
If the optional argument genericp is non-nil, this function also returns t if charcode
is a generic character (see Section 33.7 [Splitting Characters], page 645).
charset-list [Variable]
The value is a list of all defined character set names.
charset-list [Function]
This function returns the value of charset-list. It is only provided for backward
compatibility.
This is the simplest way to determine the byte length of a character set’s introduction
sequence:
(- (charset-bytes charset )
(charset-dimension charset ))
If you call make-char with no byte-values, the result is a generic character which stands
for charset. A generic character is an integer, but it is not valid for insertion in the buffer
as a character. It can be used in char-table-range to refer to the whole character set (see
Section 6.6 [Char-Tables], page 93). char-valid-p returns nil for generic characters. For
example:
(make-char ’latin-iso8859-1)
⇒ 2176
(char-valid-p 2176)
⇒ nil
(char-valid-p 2176 t)
⇒ t
(split-char 2176)
⇒ (latin-iso8859-1 0)
The character sets ascii, eight-bit-control, and eight-bit-graphic don’t have
corresponding generic characters. If charset is one of them and you don’t supply code1,
make-char returns the character code corresponding to the smallest code in charset.
In decoding, the translation table’s translations are applied to the characters that result
from ordinary decoding. If a coding system has property translation-table-for-decode,
that specifies the translation table to use. (This is a property of the coding system, as
returned by coding-system-get, not a property of the symbol that is the coding system’s
name. See Section 33.10.1 [Basic Concepts of Coding Systems], page 648.) Otherwise, if
standard-translation-table-for-decode is non-nil, decoding uses that table.
In encoding, the translation table’s translations are applied to the characters in the
buffer, and the result of translation is actually encoded. If a coding system has property
translation-table-for-encode, that specifies the translation table to use. Otherwise the
variable standard-translation-table-for-encode specifies the translation table.
standard-translation-table-for-decode [Variable]
This is the default translation table for decoding, for coding systems that don’t specify
any other translation table.
standard-translation-table-for-encode [Variable]
This is the default translation table for encoding, for coding systems that don’t specify
any other translation table.
Chapter 33: Non-ASCII Characters 648
translation-table-for-input [Variable]
Self-inserting characters are translated through this translation table before they are
inserted. Search commands also translate their input through this table, so they can
compare more reliably with what’s in the buffer.
set-buffer-file-coding-system sets this variable so that your keyboard input gets
translated into the character sets that the buffer is likely to contain. This variable
automatically becomes buffer-local when set.
The coding system raw-text is special in that it prevents character code conversion, and
causes the buffer visited with that coding system to be a unibyte buffer. It does not specify
the end-of-line conversion, allowing that to be determined as usual by the data, and has the
usual three variants which specify the end-of-line conversion. no-conversion is equivalent
to raw-text-unix: it specifies no conversion of either character codes or end-of-line.
The coding system emacs-mule specifies that the data is represented in the internal
Emacs encoding. This is like raw-text in that no code conversion happens, but different
in that the result is multibyte data.
buffer-file-coding-system [Variable]
This buffer-local variable records the coding system that was used to visit the cur-
rent buffer. It is used for saving the buffer, and for writing part of the buffer with
write-region. If the text to be written cannot be safely encoded using the coding
system specified by this variable, these operations select an alternative encoding by
calling the function select-safe-coding-system (see Section 33.10.4 [User-Chosen
Coding Systems], page 652). If selecting a different encoding requires to ask the user
to specify a coding system, buffer-file-coding-system is updated to the newly
selected coding system.
buffer-file-coding-system does not affect sending text to a subprocess.
Chapter 33: Non-ASCII Characters 650
save-buffer-coding-system [Variable]
This variable specifies the coding system for saving the buffer (by overriding buffer-
file-coding-system). Note that it is not used for write-region.
When a command to save the buffer starts out to use buffer-file-coding-system
(or save-buffer-coding-system), and that coding system cannot handle the ac-
tual text in the buffer, the command asks the user to choose another coding system
(by calling select-safe-coding-system). After that happens, the command also
updates buffer-file-coding-system to represent the coding system that the user
specified.
last-coding-system-used [Variable]
I/O operations for files and subprocesses set this variable to the coding system name
that was used. The explicit encoding and decoding functions (see Section 33.10.7
[Explicit Encoding], page 656) set it too.
Warning: Since receiving subprocess output sets this variable, it can change whenever
Emacs waits; therefore, you should copy the value shortly after the function call that
stores the value you are interested in.
The variable selection-coding-system specifies how to encode selections for the win-
dow system. See Section 29.18 [Window System Selections], page 550.
file-name-coding-system [Variable]
The variable file-name-coding-system specifies the coding system to use for en-
coding file names. Emacs encodes file names using that coding system for all file
operations. If file-name-coding-system is nil, Emacs uses a default coding system
determined by the selected language environment. In the default language environ-
ment, any non-ASCII characters in file names are not encoded specially; they appear
in the file system using the internal Emacs representation.
Warning: if you change file-name-coding-system (or the language environment) in
the middle of an Emacs session, problems can result if you have already visited files whose
names were encoded using the earlier coding system and are handled differently under the
new coding system. If you try to save one of these buffers under the visited file name, saving
may use the wrong file name, or it may get an error. If such a problem happens, use C-x
C-w to specify a new file name for that buffer.
Normally this function returns a list of coding systems that could handle decoding
the text that was scanned. They are listed in order of decreasing priority. But if
highest is non-nil, then the return value is just one coding system, the one that is
highest in priority.
If the region contains only ASCII characters except for such ISO-2022 control charac-
ters ISO-2022 as ESC, the value is undecided or (undecided), or a variant specifying
end-of-line conversion, if that can be deduced from the text.
detect-coding-string string &optional highest [Function]
This function is like detect-coding-region except that it operates on the contents
of string instead of bytes in the buffer.
See [Process Information], page 714, in particular the description of the functions
process-coding-system and set-process-coding-system, for how to examine or set
the coding systems used for I/O to a subprocess.
Here are two functions you can use to let the user specify a coding system, with com-
pletion. See Section 20.6 [Completion], page 285.
auto-coding-regexp-alist [Variable]
This variable is an alist of text patterns and corresponding coding systems. Each
element has the form (regexp . coding-system ); a file whose first few kilobytes
match regexp is decoded with coding-system when its contents are read into a buffer.
The settings in this alist take priority over coding: tags in the files and the contents
of file-coding-system-alist (see below). The default value is set so that Emacs
automatically recognizes mail files in Babyl format and reads them with no code
conversions.
file-coding-system-alist [Variable]
This variable is an alist that specifies the coding systems to use for reading and writing
particular files. Each element has the form (pattern . coding ), where pattern is a
regular expression that matches certain file names. The element applies to file names
that match pattern.
Chapter 33: Non-ASCII Characters 654
The cdr of the element, coding, should be either a coding system, a cons cell con-
taining two coding systems, or a function name (a symbol with a function definition).
If coding is a coding system, that coding system is used for both reading the file and
writing it. If coding is a cons cell containing two coding systems, its car specifies
the coding system for decoding, and its cdr specifies the coding system for encoding.
If coding is a function name, the function should take one argument, a list of all ar-
guments passed to find-operation-coding-system. It must return a coding system
or a cons cell containing two coding systems. This value has the same meaning as
described above.
process-coding-system-alist [Variable]
This variable is an alist specifying which coding systems to use for a subprocess,
depending on which program is running in the subprocess. It works like file-coding-
system-alist, except that pattern is matched against the program name used to
start the subprocess. The coding system or systems specified in this alist are used
to initialize the coding systems used for I/O to the subprocess, but you can specify
other coding systems later using set-process-coding-system.
Warning: Coding systems such as undecided, which determine the coding system from
the data, do not work entirely reliably with asynchronous subprocess output. This is because
Emacs handles asynchronous subprocess output in batches, as it arrives. If the coding
system leaves the character code conversion unspecified, or leaves the end-of-line conversion
unspecified, Emacs must try to detect the proper conversion from one batch at a time, and
this does not always work.
Therefore, with an asynchronous subprocess, if at all possible, use a coding system which
determines both the character code conversion and the end of line conversion—that is, one
like latin-1-unix, rather than undecided or latin-1.
network-coding-system-alist [Variable]
This variable is an alist that specifies the coding system to use for network streams.
It works much like file-coding-system-alist, with the difference that the pattern
in an element may be either a port number or a regular expression. If it is a regular
expression, it is matched against the network service name used to open the network
stream.
default-process-coding-system [Variable]
This variable specifies the coding systems to use for subprocess (and network stream)
input and output, when nothing else specifies what to do.
The value should be a cons cell of the form (input-coding . output-coding ). Here
input-coding applies to input from the subprocess, and output-coding applies to
output to it.
auto-coding-functions [Variable]
This variable holds a list of functions that try to determine a coding system for a file
based on its undecoded contents.
Each function in this list should be written to look at text in the current buffer, but
should not modify it in any way. The buffer will contain undecoded text of parts
of the file. Each function should take one argument, size, which tells it how many
Chapter 33: Non-ASCII Characters 655
characters to look at, starting from point. If the function succeeds in determining a
coding system for the file, it should return that coding system. Otherwise, it should
return nil.
If a file has a ‘coding:’ tag, that takes precedence, so these functions won’t be called.
coding-system-for-read [Variable]
If this variable is non-nil, it specifies the coding system to use for reading a file, or
for input from a synchronous subprocess.
It also applies to any asynchronous subprocess or network stream, but in a different
way: the value of coding-system-for-read when you start the subprocess or open
the network stream specifies the input decoding method for that subprocess or net-
work stream. It remains in use for that subprocess or network stream unless and until
overridden.
Chapter 33: Non-ASCII Characters 656
The right way to use this variable is to bind it with let for a specific I/O operation.
Its global value is normally nil, and you should not globally set it to any other value.
Here is an example of the right way to use the variable:
;; Read the file with no character code conversion.
;; Assume crlf represents end-of-line.
(let ((coding-system-for-read ’emacs-mule-dos))
(insert-file-contents filename))
When its value is non-nil, this variable takes precedence over all other methods of
specifying a coding system to use for input, including file-coding-system-alist,
process-coding-system-alist and network-coding-system-alist.
coding-system-for-write [Variable]
This works much like coding-system-for-read, except that it applies to output
rather than input. It affects writing to files, as well as sending output to subprocesses
and net connections.
When a single operation does both input and output, as do call-process-region
and start-process, both coding-system-for-read and coding-system-for-
write affect it.
inhibit-eol-conversion [Variable]
When this variable is non-nil, no end-of-line conversion is done, no matter which cod-
ing system is specified. This applies to all the Emacs I/O and subprocess primitives,
and to the explicit encoding and decoding functions (see Section 33.10.7 [Explicit
Encoding], page 656).
keyboard-coding-system [Function]
This function returns the coding system that is in use for decoding keyboard input—or
nil if no coding system is to be used.
terminal-coding-system [Function]
This function returns the coding system that is in use for encoding terminal output—
or nil for no encoding.
buffer-file-type [Variable]
This variable, automatically buffer-local in each buffer, records the file type of the
buffer’s visited file. When a buffer does not specify a coding system with buffer-
file-coding-system, this variable is used to determine which coding system to use
when writing the contents of the buffer. It should be nil for text, t for binary. If it
is t, the coding system is no-conversion. Otherwise, undecided-dos is used.
Normally this variable is set by visiting a file; it is set to nil if the file was visited
without any actual conversion.
current-input-method [Variable]
This variable holds the name of the input method now active in the current buffer.
(It automatically becomes local in each buffer when set in any fashion.) It is nil if
no input method is active in the buffer now.
input-method-alist [Variable]
This variable defines all the supported input methods. Each element defines one input
method, and should have the form:
(input-method language-env activate-func
title description args...)
Here input-method is the input method name, a string; language-env is another string,
the name of the language environment this input method is recommended for. (That
serves only for documentation purposes.)
activate-func is a function to call to activate this method. The args, if any, are
passed as arguments to activate-func. All told, the arguments to activate-func are
input-method and the args.
title is a string to display in the mode line while this method is active. description is
a string describing this method and what it is good for.
33.12 Locales
POSIX defines a concept of “locales” which control which language to use in language-
related features. These Emacs variables control how Emacs interacts with these features.
locale-coding-system [Variable]
This variable specifies the coding system to use for decoding system error messages
and—on X Window system only—keyboard input, for encoding the format argument
to format-time-string, and for decoding the return value of format-time-string.
system-messages-locale [Variable]
This variable specifies the locale to use for generating system error messages. Chang-
ing the locale can cause messages to come out in a different language or in a different
orthography. If the variable is nil, the locale is specified by environment variables in
the usual POSIX fashion.
system-time-locale [Variable]
This variable specifies the locale to use for formatting time values. Changing the locale
can cause messages to appear according to the conventions of a different language.
If the variable is nil, the locale is specified by environment variables in the usual
POSIX fashion.
(search-forward "fox")
⇒ 20
If repeat is supplied (it must be a positive number), then the search is repeated that
many times (each time starting at the end of the previous time’s match). If these
successive searches succeed, the function succeeds, moving point and returning its
new value. Otherwise the search fails, with results depending on the value of noerror,
as described above.
A ‘[:’ and balancing ‘:]’ enclose a character class inside a character alternative. Any other
character appearing in a regular expression is ordinary, unless a ‘\’ precedes it.
For example, ‘f’ is not a special character, so it is ordinary, and therefore ‘f’ is a regular
expression that matches the string ‘f’ and no other string. (It does not match the string
‘fg’, but it does match a part of that string.) Likewise, ‘o’ is a regular expression that
matches only ‘o’.
Any two regular expressions a and b can be concatenated. The result is a regular
expression that matches a string if a matches some amount of the beginning of that string
and b matches the rest of the string.
As a simple example, we can concatenate the regular expressions ‘f’ and ‘o’ to get the
regular expression ‘fo’, which matches only the string ‘fo’. Still trivial. To do something
more powerful, you need to use one of the special regular expression constructs.
‘?’ is a postfix operator, similar to ‘*’ except that it must match the preceding
expression either once or not at all. For example, ‘ca?r’ matches ‘car’ or ‘cr’;
nothing else.
‘*?’, ‘+?’, ‘??’
These are “non-greedy” variants of the operators ‘*’, ‘+’ and ‘?’. Where those
operators match the largest possible substring (consistent with matching the en-
tire containing expression), the non-greedy variants match the smallest possible
substring (consistent with matching the entire containing expression).
For example, the regular expression ‘c[ad]*a’ when applied to the string
‘cdaaada’ matches the whole string; but the regular expression ‘c[ad]*?a’,
applied to that same string, matches just ‘cda’. (The smallest possible match
here for ‘[ad]*?’ that permits the whole expression to match is ‘d’.)
‘[ ... ]’ is a character alternative, which begins with ‘[’ and is terminated by ‘]’. In the
simplest case, the characters between the two brackets are what this character
alternative can match.
Thus, ‘[ad]’ matches either one ‘a’ or one ‘d’, and ‘[ad]*’ matches any string
composed of just ‘a’s and ‘d’s (including the empty string), from which it follows
that ‘c[ad]*r’ matches ‘cr’, ‘car’, ‘cdr’, ‘caddaar’, etc.
You can also include character ranges in a character alternative, by writing the
starting and ending characters with a ‘-’ between them. Thus, ‘[a-z]’ matches
any lower-case ASCII letter. Ranges may be intermixed freely with individual
characters, as in ‘[a-z$%.]’, which matches any lower case ASCII letter or ‘$’,
‘%’ or period.
Note that the usual regexp special characters are not special inside a character
alternative. A completely different set of characters is special inside character
alternatives: ‘]’, ‘-’ and ‘^’.
To include a ‘]’ in a character alternative, you must make it the first character.
For example, ‘[]a]’ matches ‘]’ or ‘a’. To include a ‘-’, write ‘-’ as the first or
last character of the character alternative, or put it after a range. Thus, ‘[]-]’
matches both ‘]’ and ‘-’.
To include ‘^’ in a character alternative, put it anywhere but at the beginning.
The beginning and end of a range of multibyte characters must be in the same
character set (see Section 33.5 [Character Sets], page 644). Thus, "[\x8e0-
\x97c]" is invalid because character 0x8e0 (‘a’ with grave accent) is in the
Emacs character set for Latin-1 but the character 0x97c (‘u’ with diaeresis) is
in the Emacs character set for Latin-2. (We use Lisp string syntax to write that
example, and a few others in the next few paragraphs, in order to include hex
escape sequences in them.)
If a range starts with a unibyte character c and ends with a multibyte character
c2, the range is divided into two parts: one is ‘c..?\377’, the other is ‘c1..c2 ’,
where c1 is the first character of the charset to which c2 belongs.
You cannot always match all non-ASCII characters with the regular expression
"[\200-\377]". This works when searching a unibyte buffer or string (see Sec-
tion 33.1 [Text Representations], page 640), but not in a multibyte buffer or
Chapter 34: Searching and Matching 666
string, because many non-ASCII characters have codes above octal 0377. How-
ever, the regular expression "[^\000-\177]" does match all non-ASCII charac-
ters (see below regarding ‘^’), in both multibyte and unibyte representations,
because only the ASCII characters are excluded.
A character alternative can also specify named character classes (see
Section 34.3.1.2 [Char Classes], page 667). This is a POSIX feature whose
syntax is ‘[:class :]’. Using a character class is equivalent to mentioning
each of the characters in that class; but the latter is not feasible in practice,
since some classes include thousands of different characters.
‘[^ ... ]’ ‘[^’ begins a complemented character alternative. This matches any character
except the ones specified. Thus, ‘[^a-z0-9A-Z]’ matches all characters except
letters and digits.
‘^’ is not special in a character alternative unless it is the first character. The
character following the ‘^’ is treated as if it were first (in other words, ‘-’ and
‘]’ are not special there).
A complemented character alternative can match a newline, unless newline is
mentioned as one of the characters not to match. This is in contrast to the
handling of regexps in programs such as grep.
‘^’ When matching a buffer, ‘^’ matches the empty string, but only at the beginning
of a line in the text being matched (or the beginning of the accessible portion
of the buffer). Otherwise it fails to match anything. Thus, ‘^foo’ matches a
‘foo’ that occurs at the beginning of a line.
When matching a string instead of a buffer, ‘^’ matches at the beginning of the
string or after a newline character.
For historical compatibility reasons, ‘^’ can be used only at the beginning of
the regular expression, or after ‘\(’, ‘\(?:’ or ‘\|’.
‘$’ is similar to ‘^’ but matches only at the end of a line (or the end of the accessible
portion of the buffer). Thus, ‘x+$’ matches a string of one ‘x’ or more at the
end of a line.
When matching a string instead of a buffer, ‘$’ matches at the end of the string
or before a newline character.
For historical compatibility reasons, ‘$’ can be used only at the end of the
regular expression, or before ‘\)’ or ‘\|’.
‘\’ has two functions: it quotes the special characters (including ‘\’), and it intro-
duces additional special constructs.
Because ‘\’ quotes special characters, ‘\$’ is a regular expression that matches
only ‘$’, and ‘\[’ is a regular expression that matches only ‘[’, and so on.
Note that ‘\’ also has special meaning in the read syntax of Lisp strings (see
Section 2.3.8 [String Type], page 18), and must be quoted with ‘\’. For exam-
ple, the regular expression that matches the ‘\’ character is ‘\\’. To write a
Lisp string that contains the characters ‘\\’, Lisp syntax requires you to quote
each ‘\’ with another ‘\’. Therefore, the read syntax for a regular expression
matching ‘\’ is "\\\\".
Chapter 34: Searching and Matching 667
Please note: For historical compatibility, special characters are treated as ordinary ones
if they are in contexts where their special meanings make no sense. For example, ‘*foo’
treats ‘*’ as ordinary since there is no preceding expression on which the ‘*’ can act. It is
poor practice to depend on this behavior; quote the special character anyway, regardless of
where it appears.
As a ‘\’ is not special inside a character alternative, it can never remove the special
meaning of ‘-’ or ‘]’. So you should not quote these characters when they have no special
meaning either. This would not clarify anything, since backslashes can legitimately precede
these characters where they have special meaning, as in ‘[^\]’ ("[^\\]" for Lisp string
syntax), which matches any single character except a backslash.
In practice, most ‘]’ that occur in regular expressions close a character alternative and
hence are special. However, occasionally a regular expression may try to match a complex
pattern of literal ‘[’ and ‘]’. In such situations, it sometimes may be necessary to carefully
parse the regexp from the start to determine which square brackets enclose a character al-
ternative. For example, ‘[^][]]’ consists of the complemented character alternative ‘[^][]’
(which matches any single character that is not a square bracket), followed by a literal ‘]’.
The exact rules are that at the beginning of a regexp, ‘[’ is special and ‘]’ not. This lasts
until the first unquoted ‘[’, after which we are in a character alternative; ‘[’ is no longer
special (except when it starts a character class) but ‘]’ is special, unless it immediately
follows the special ‘[’ or that ‘[’ followed by a ‘^’. This lasts until the next special ‘]’
that does not end a character class. This ends the character alternative and restores the
ordinary syntax of regular expressions; an unquoted ‘[’ is special again and a ‘]’ not.
‘[:lower:]’
This matches any lower-case letter, as determined by the current case table (see
Section 4.9 [Case Tables], page 60).
‘[:multibyte:]’
This matches any multibyte character (see Section 33.1 [Text Representations],
page 640).
‘[:nonascii:]’
This matches any non-ASCII character.
‘[:print:]’
This matches printing characters—everything except ASCII control characters
and the delete character.
‘[:punct:]’
This matches any punctuation character. (At present, for multibyte characters,
it matches anything that has non-word syntax.)
‘[:space:]’
This matches any character that has whitespace syntax (see Section 35.2.1
[Syntax Class Table], page 685).
‘[:unibyte:]’
This matches any unibyte character (see Section 33.1 [Text Representations],
page 640).
‘[:upper:]’
This matches any upper-case letter, as determined by the current case table
(see Section 4.9 [Case Tables], page 60).
‘[:word:]’
This matches any character that has word syntax (see Section 35.2.1 [Syntax
Class Table], page 685).
‘[:xdigit:]’
This matches the hexadecimal digits: ‘0’ through ‘9’, ‘a’ through ‘f’ and ‘A’
through ‘F’.
‘\{m \}’ is a postfix operator that repeats the previous pattern exactly m times. Thus,
‘x\{5\}’ matches the string ‘xxxxx’ and nothing else. ‘c[ad]\{3\}r’ matches
string such as ‘caaar’, ‘cdddr’, ‘cadar’, and so on.
‘\{m,n \}’ is a more general postfix operator that specifies repetition with a minimum of
m repeats and a maximum of n repeats. If m is omitted, the minimum is 0; if
n is omitted, there is no maximum.
For example, ‘c[ad]\{1,2\}r’ matches the strings ‘car’, ‘cdr’, ‘caar’, ‘cadr’,
‘cdar’, and ‘cddr’, and nothing else.
‘\{0,1\}’ or ‘\{,1\}’ is equivalent to ‘?’.
‘\{0,\}’ or ‘\{,\}’ is equivalent to ‘*’.
‘\{1,\}’ is equivalent to ‘+’.
‘\( ... \)’
is a grouping construct that serves three purposes:
1. To enclose a set of ‘\|’ alternatives for other operations. Thus, the regular
expression ‘\(foo\|bar\)x’ matches either ‘foox’ or ‘barx’.
2. To enclose a complicated expression for the postfix operators ‘*’, ‘+’ and
‘?’ to operate on. Thus, ‘ba\(na\)*’ matches ‘ba’, ‘bana’, ‘banana’,
‘bananana’, etc., with any number (zero or more) of ‘na’ strings.
3. To record a matched substring for future reference with ‘\digit ’ (see be-
low).
This last application is not a consequence of the idea of a parenthetical grouping;
it is a separate feature that was assigned as a second meaning to the same ‘\(
... \)’ construct because, in practice, there was usually no conflict between
the two meanings. But occasionally there is a conflict, and that led to the
introduction of shy groups.
‘\(?: ... \)’
is the shy group construct. A shy group serves the first two purposes of an
ordinary group (controlling the nesting of other operators), but it does not get
a number, so you cannot refer back to its value with ‘\digit ’.
Shy groups are particularly useful for mechanically-constructed regular expres-
sions because they can be added automatically without altering the numbering
of any ordinary, non-shy groups.
‘\digit ’ matches the same text that matched the digitth occurrence of a grouping (‘\(
... \)’) construct.
In other words, after the end of a group, the matcher remembers the beginning
and end of the text matched by that group. Later on in the regular expression
you can use ‘\’ followed by digit to match that same text, whatever it may have
been.
The strings matching the first nine grouping constructs appearing in the entire
regular expression passed to a search or matching function are assigned num-
bers 1 through 9 in the order that the open parentheses appear in the regular
expression. So you can use ‘\1’ through ‘\9’ to refer to the text matched by
the corresponding grouping constructs.
Chapter 34: Searching and Matching 670
‘\B’ matches the empty string, but not at the beginning or end of a word, nor at
the beginning or end of the buffer (or string).
‘\<’ matches the empty string, but only at the beginning of a word. ‘\<’ matches
at the beginning of the buffer (or string) only if a word-constituent character
follows.
‘\>’ matches the empty string, but only at the end of a word. ‘\>’ matches at the
end of the buffer (or string) only if the contents end with a word-constituent
character.
‘\_<’ matches the empty string, but only at the beginning of a symbol. A symbol is a
sequence of one or more word or symbol constituent characters. ‘\_<’ matches
at the beginning of the buffer (or string) only if a symbol-constituent character
follows.
‘\_>’ matches the empty string, but only at the end of a symbol. ‘\_>’ matches at the
end of the buffer (or string) only if the contents end with a symbol-constituent
character.
Not every string is a valid regular expression. For example, a string that ends inside a
character alternative without terminating ‘]’ is invalid, and so is a string that ends with
a single ‘\’. If an invalid regular expression is passed to any of the search functions, an
invalid-regexp error is signaled.
[]\"’)}]*
The second part of the pattern matches any closing braces and quotation marks,
zero or more of them, that may follow the period, question mark or exclamation
mark. The \" is Lisp syntax for a double-quote in a string. The ‘*’ at the
end indicates that the immediately preceding regular expression (a character
alternative, in this case) may be repeated zero or more times.
\\($\\| $\\|\t\\| \\)
The third part of the pattern matches the whitespace that follows the end of a
sentence: the end of a line (optionally with a space), or a tab, or two spaces.
The double backslashes mark the parentheses and vertical bars as regular ex-
pression syntax; the parentheses delimit a group and the vertical bars separate
alternatives. The dollar sign is used to match the end of a line.
[ \t\n]* Finally, the last part of the pattern matches any additional whitespace beyond
the minimum needed to end a sentence.
(concat open-paren
(mapconcat ’regexp-quote strings "\\|")
close-paren)))
anything else
Move point to limit (or the end of the accessible portion of the buffer)
and return nil.
In the following example, point is initially before the ‘T’. Evaluating the search call
moves point to the end of that line (between the ‘t’ of ‘hat’ and the newline).
---------- Buffer: foo ----------
I read "?The cat in the hat
comes back" twice.
---------- Buffer: foo ----------
Chapter 34: Searching and Matching 674
(match-end 0)
⇒ 32
Chapter 34: Searching and Matching 675
search-spaces-regexp [Variable]
If this variable is non-nil, it should be a regular expression that says how to search for
whitespace. In that case, any group of spaces in a regular expression being searched
for stands for use of this regular expression. However, spaces inside of constructs such
as ‘[...]’ and ‘*’, ‘+’, ‘?’ are not affected by search-spaces-regexp.
Since this variable affects all regular expression search and match constructs, you
should bind it temporarily for as small as possible a part of the code.
Chapter 34: Searching and Matching 676
If you did the last search in a buffer, you should specify nil for string and make sure
that the current buffer when you call replace-match is the one in which you did the
searching or matching. Then replace-match does the replacement by editing the
buffer; it leaves point at the end of the replacement text, and returns t.
If you did the search in a string, pass the same string as string. Then replace-match
does the replacement by constructing and returning a new string.
If fixedcase is non-nil, then replace-match uses the replacement text without case
conversion; otherwise, it converts the replacement text depending upon the capital-
ization of the text to be replaced. If the original text is all upper case, this converts
the replacement text to upper case. If all words of the original text are capitalized,
this capitalizes all the words of the replacement text. If all the words are one-letter
and they are all upper case, they are treated as capitalized words rather than all-
upper-case words.
If literal is non-nil, then replacement is inserted exactly as it is, the only alterations
being case changes as needed. If it is nil (the default), then the character ‘\’ is
treated specially. If a ‘\’ appears in replacement, then it must be part of one of the
following sequences:
‘\&’ ‘\&’ stands for the entire text being replaced.
‘\n ’ ‘\n ’, where n is a digit, stands for the text that matched the nth subex-
pression in the original regexp. Subexpressions are those expressions
grouped inside ‘\(...\)’. If the nth subexpression never matched, an
empty string is substituted.
‘\\’ ‘\\’ stands for a single ‘\’ in the replacement text.
These substitutions occur after case conversion, if any, so the strings they substitute
are never case-converted.
If subexp is non-nil, that says to replace just subexpression number subexp of the
regexp that was matched, not the entire match. For example, after matching ‘foo
\(ba*r\)’, calling replace-match with 1 as subexp means to replace just the text
that matched ‘\(ba*r\)’.
search. Alternatively, you may save and restore the match data (see Section 34.6.4 [Saving
Match Data], page 680) around the call to functions that could perform another search.
A search which fails may or may not alter the match data. In the past, a failing search
did not do this, but we may change it in the future. So don’t try to rely on the value of the
match data after a failing search.
Here is an example of using the match data, with a comment showing the positions
within the text:
(string-match "\\(qu\\)\\(ick\\)"
"The quick fox jumped quickly.")
;0123456789
⇒ 4
match data.) If the last match was done on a string with string-match, then integers
are always used, since markers can’t point into a string.
If reuse is non-nil, it should be a list. In that case, match-data stores the match
data in reuse. That is, reuse is destructively modified. reuse does not need to have
the right length. If it is not long enough to contain the match data, it is extended.
If it is too long, the length of reuse stays the same, but the elements that were not
used are set to nil. The purpose of this feature is to reduce the need for garbage
collection.
If reseat is non-nil, all markers on the reuse list are reseated to point to nowhere.
As always, there must be no possibility of intervening searches between the call to a
search function and the call to match-data that is intended to access the match data
for that search.
(match-data)
⇒ (#<marker at 9 in foo>
#<marker at 17 in foo>
#<marker at 13 in foo>
#<marker at 17 in foo>)
set-match-data match-list &optional reseat [Function]
This function sets the match data from the elements of match-list, which should be
a list that was the value of a previous call to match-data. (More precisely, anything
that has the same format will work.)
If match-list refers to a buffer that doesn’t exist, you don’t get an error; that sets the
match data in a meaningless but harmless way.
If reseat is non-nil, all markers on the match-list list are reseated to point to nowhere.
store-match-data is a semi-obsolete alias for set-match-data.
If you want to write a command along the lines of query-replace, you can use perform-
replace to do the work.
query-replace-map [Variable]
This variable holds a special keymap that defines the valid user responses for perform-
replace and the commands that use it, as well as y-or-n-p and map-y-or-n-p. This
map is unusual in two ways:
• The “key bindings” are not commands, just symbols that are meaningful to the
functions that use this map.
• Prefix keys are not supported; each key binding must be for a single-event key
sequence. This is because the functions don’t use read-key-sequence to get the
input; instead, they read a single event and look it up “by hand.”
Here are the meaningful “bindings” for query-replace-map. Several of them are mean-
ingful only for query-replace and friends.
act Do take the action being considered—in other words, “yes.”
skip Do not take action for this question—in other words, “no.”
exit Answer this question “no,” and give up on the entire series of questions, assum-
ing that the answers will be “no.”
act-and-exit
Answer this question “yes,” and give up on the entire series of questions, as-
suming that subsequent answers will be “no.”
act-and-show
Answer this question “yes,” but show the results—don’t advance yet to the
next question.
automatic
Answer this question and all subsequent questions in the series with “yes,”
without further user interaction.
backup Move back to the previous place that a question was asked about.
edit Enter a recursive edit to deal with this question—instead of any other action
that would normally be taken.
Chapter 34: Searching and Matching 683
delete-and-edit
Delete the text being considered, then enter a recursive edit to replace it.
recenter Redisplay and center the window, then ask the same question again.
quit Perform a quit right away. Only y-or-n-p and related functions use this answer.
help Display some help, then ask again.
page-delimiter [Variable]
This is the regular expression describing line-beginnings that separate pages. The
default value is "^\014" (i.e., "^^L" or "^\C-l"); this matches a line that starts with
a formfeed character.
The following two regular expressions should not assume the match always starts at the
beginning of a line; they should not use ‘^’ to anchor the match. Most often, the paragraph
commands do check for a match only at the beginning of a line, which means that ‘^’ would
be superfluous. When there is a nonzero left margin, they accept matches that start after
the left margin. In that case, a ‘^’ would be incorrect. However, a ‘^’ is harmless in modes
where a left margin is never used.
paragraph-separate [Variable]
This is the regular expression for recognizing the beginning of a line that separates
paragraphs. (If you change this, you may have to change paragraph-start also.) The
default value is "[ \t\f]*$", which matches a line that consists entirely of spaces,
tabs, and form feeds (after its left margin).
paragraph-start [Variable]
This is the regular expression for recognizing the beginning of a line that starts or
separates paragraphs. The default value is "\f\\|[ \t]*$", which matches a line
containing only whitespace or starting with a form feed (after its left margin).
sentence-end [Variable]
If non-nil, the value should be a regular expression describing the end of a sentence,
including the whitespace following the sentence. (All paragraph boundaries also end
sentences, regardless.)
If the value is nil, the default, then the function sentence-end has to construct the
regexp. That is why you should always call the function sentence-end to obtain the
regexp to be used to recognize the end of a sentence.
sentence-end [Function]
This function returns the value of the variable sentence-end, if non-nil. Other-
wise it returns a default value based on the values of the variables sentence-end-
double-space (see [Definition of sentence-end-double-space], page 601), sentence-
end-without-period and sentence-end-without-space.
Chapter 35: Syntax Tables 684
35 Syntax Tables
A syntax table specifies the syntactic textual function of each character. This information is
used by the parsing functions, the complex movement commands, and others to determine
where words, symbols, and other syntactic constructs begin and end. The current syntax
table controls the meaning of the word motion functions (see Section 30.2.2 [Word Motion],
page 561) and the list motion functions (see Section 30.2.6 [List Motion], page 566), as well
as the functions in this chapter.
A syntax descriptor is a Lisp string that specifies a syntax class, a matching character
(used only for the parenthesis classes) and flags. The first character is the designator for a
syntax class. The second character is the character to match; if it is unused, put a space
there. Then come the characters for any desired flags. If no matching character or flags are
needed, one character is sufficient.
For example, the syntax descriptor for the character ‘*’ in C mode is ‘. 23’ (i.e., punctua-
tion, matching character slot unused, second character of a comment-starter, first character
of a comment-ender), and the entry for ‘/’ is ‘. 14’ (i.e., punctuation, matching character
slot unused, first character of a comment-starter, second character of a comment-ender).
The class of open parentheses is designated by ‘(’, and that of close parentheses by
‘)’.
In English text, and in C code, the parenthesis pairs are ‘()’, ‘[]’, and ‘{}’. In Emacs
Lisp, the delimiters for lists and vectors (‘()’ and ‘[]’) are classified as parenthesis
characters.
• ‘b’ means that c as a comment delimiter belongs to the alternative “b” comment style.
Emacs supports two comment styles simultaneously in any one syntax table. This is
for the sake of C++. Each style of comment syntax has its own comment-start sequence
and its own comment-end sequence. Each comment must stick to one style or the other;
thus, if it starts with the comment-start sequence of style “b,” it must also end with
the comment-end sequence of style “b.”
The two comment-start sequences must begin with the same character; only the sec-
ond character may differ. Mark the second character of the “b”-style comment-start
sequence with the ‘b’ flag.
A comment-end sequence (one or two characters) applies to the “b” style if its first
character has the ‘b’ flag set; otherwise, it applies to the “a” style.
The appropriate comment syntax settings for C++ are as follows:
‘/’ ‘124b’
‘*’ ‘23’
newline ‘>b’
This defines four comment-delimiting sequences:
‘/*’ This is a comment-start sequence for “a” style because the second charac-
ter, ‘*’, does not have the ‘b’ flag.
‘//’ This is a comment-start sequence for “b” style because the second charac-
ter, ‘/’, does have the ‘b’ flag.
‘*/’ This is a comment-end sequence for “a” style because the first character,
‘*’, does not have the ‘b’ flag.
newline This is a comment-end sequence for “b” style, because the newline charac-
ter has the ‘b’ flag.
• ‘n’ on a comment delimiter character specifies that this kind of comment can be nested.
For a two-character comment delimiter, ‘n’ on either character makes it nestable.
• ‘p’ identifies an additional “prefix character” for Lisp syntax. These characters are
treated as whitespace when they appear between expressions. When they appear within
an expression, they are handled according to their usual syntax classes.
The function backward-prefix-chars moves back over these characters, as well as
over characters whose primary syntax class is prefix (‘’’). See Section 35.5 [Motion
and Syntax], page 691.
the syntax of ‘/’ is punctuation. This does not show the fact that it is also part of
comment-start and -end sequences. The third example shows that open parenthesis
is in the class of open parentheses. This does not show the fact that it has a matching
character, ‘)’.
(string (char-syntax ?\s))
⇒ " "
backward-prefix-chars [Function]
This function moves point backward over any number of characters with expression
prefix syntax. This includes both characters in the expression prefix syntax class, and
characters with the ‘p’ flag.
To move forward over all comments and whitespace following point, use (forward-
comment (buffer-size)). (buffer-size) is a good argument to use, because the number
of comments in the buffer cannot exceed that many.
Major modes can make syntax-ppss run faster by specifying where it needs to start
parsing.
syntax-begin-function [Variable]
If this is non-nil, it should be a function that moves to an earlier buffer position
where the parser state is equivalent to nil—in other words, a position outside of
any comment, string, or parenthesis. syntax-ppss uses it to further optimize its
computations, when the cache gives no help.
8. The string or comment start position. While inside a comment, this is the position
where the comment began; while inside a string, this is the position where the string
began. When outside of strings and comments, this element is nil.
9. Internal data for continuing the parsing. The meaning of this data is subject to change;
it is used if you pass this list as the state argument to another call.
Elements 1, 2, and 6 are ignored in a state which you pass as an argument to continue
parsing, and elements 8 and 9 are used only in trivial cases. Those elements serve primarily
to convey information to the Lisp program which does the parsing.
One additional piece of useful information is available from a parser state using this
function:
We have provided this access function rather than document how the data is represented
in the state, because we plan to change the representation in the future.
standard-syntax-table [Function]
This function returns the standard syntax table, which is the syntax table used in
Fundamental mode.
text-mode-syntax-table [Variable]
The value of this variable is the syntax table used in Text mode.
c-mode-syntax-table [Variable]
The value of this variable is the syntax table for C-mode buffers.
emacs-lisp-mode-syntax-table [Variable]
The value of this variable is the syntax table used in Emacs Lisp mode by editing
commands. (It has no effect on the Lisp read function.)
35.9 Categories
Categories provide an alternate way of classifying characters syntactically. You can define
several categories as needed, then independently assign each character to one or more cat-
egories. Unlike syntax classes, categories are not mutually exclusive; it is normal for one
character to belong to several categories.
Each buffer has a category table which records which categories are defined and also
which characters belong to each category. Each category table defines its own categories,
but normally these are initialized by copying from the standard categories table, so that
the standard categories are available in all modes.
Each category has a name, which is an ASCII printing character in the range ‘ ’ to ‘~’.
You specify the name of a category when you define it with define-category.
The category table is actually a char-table (see Section 6.6 [Char-Tables], page 93). The
element of the category table at index c is a category set—a bool-vector—that indicates
which categories character c belongs to. In this category set, if the element at index cat is
t, that means category cat is a member of the set, and that character c belongs to category
cat.
For the next three functions, the optional argument table defaults to the current buffer’s
category table.
Chapter 35: Syntax Tables 697
(char-category-set ?a)
⇒ #&128"\0\0\0\0\0\0\0\0\0\0\0\0\2\20\0\0"
abbrev-mode [Variable]
A non-nil value of this variable turns on the automatic expansion of abbrevs when
their abbreviations are inserted into a buffer. If the value is nil, abbrevs may be
defined, but they are not expanded automatically.
This variable automatically becomes buffer-local when set in any fashion.
default-abbrev-mode [Variable]
This is the value of abbrev-mode for buffers that do not override it. This is the same
as (default-value ’abbrev-mode).
make-abbrev-table [Function]
This function creates and returns a new, empty abbrev table—an obarray containing
no symbols. It is a vector filled with zeros.
abbrev-table-name-list [Variable]
This is a list of symbols whose values are abbrev tables. define-abbrev-table adds
the new abbrev table name to this list.
The argument hook is a function or nil. If hook is non-nil, then it is called with no
arguments after the abbrev is replaced with expansion; point is located at the end of
expansion when hook is called.
If hook is a non-nil symbol whose no-self-insert property is non-nil, hook can
explicitly control whether to insert the self-inserting input character that triggered
the expansion. If hook returns non-nil in this case, that inhibits insertion of the
character. By contrast, if hook returns nil, expand-abbrev also returns nil, as if
expansion had not really occurred.
If system-flag is non-nil, that marks the abbrev as a “system” abbrev with the
system-type property. Unless system-flag has the value force, a “system” abbrev
will not overwrite an existing definition for a non-“system” abbrev of the same name.
Normally the function define-abbrev sets the variable abbrevs-changed to t, if
it actually changes the abbrev. (This is so that some commands will offer to save
the abbrevs.) It does not do this for a “system” abbrev, since those won’t be saved
anyway.
abbrevs-changed [Variable]
This variable is set non-nil by defining or altering any abbrevs (except “system”
abbrevs). This serves as a flag for various Emacs commands to offer to save your
abbrevs.
write-abbrev-file &optional filename [Command]
Save all abbrev definitions (except “system” abbrevs), for all abbrev tables listed in
abbrev-table-name-list, in the file filename, in the form of a Lisp program that
when loaded will define the same abbrevs. If filename is nil or omitted, abbrev-
file-name is used. This function returns nil.
abbrev-start-location [Variable]
The value of this variable is a buffer position (an integer or a marker) for expand-
abbrev to use as the start of the next abbrev to be expanded. The value can also be
nil, which means to use the word before point instead. abbrev-start-location is
set to nil each time expand-abbrev is called. This variable is also set by abbrev-
prefix-mark.
abbrev-start-location-buffer [Variable]
The value of this variable is the buffer for which abbrev-start-location has been
set. Trying to expand an abbrev in any other buffer clears abbrev-start-location.
This variable is set by abbrev-prefix-mark.
last-abbrev [Variable]
This is the abbrev-symbol of the most recent abbrev expanded. This information is
left by expand-abbrev for the sake of the unexpand-abbrev command (see section
“Expanding Abbrevs” in The GNU Emacs Manual).
last-abbrev-location [Variable]
This is the location of the most recent abbrev expanded. This contains information
left by expand-abbrev for the sake of the unexpand-abbrev command.
last-abbrev-text [Variable]
This is the exact expansion text of the most recent abbrev expanded, after case
conversion (if any). Its value is nil if the abbrev has already been unexpanded. This
contains information left by expand-abbrev for the sake of the unexpand-abbrev
command.
pre-abbrev-expand-hook [Variable]
This is a normal hook whose functions are executed, in sequence, just before any
expansion of an abbrev. See Section 23.1 [Hooks], page 382. Since it is a normal
hook, the hook functions receive no arguments. However, they can find the abbrev
to be expanded by looking in the buffer before point. Running the hook is the first
thing that expand-abbrev does, and so a hook function can be used to change the
current abbrev table before abbrev lookup happens. (Although you have to do this
carefully. See the example below.)
(add-hook ’foo-mode-hook
#’(lambda ()
(add-hook ’pre-abbrev-expand-hook
’foo-mode-pre-abbrev-expand
nil t)))
Note that foo-mode-pre-abbrev-expand just returns nil without doing anything for
lines not starting with ‘#’. Hence abbrevs expand normally using foo-mode-abbrev-table
as local abbrev table for such lines.
global-abbrev-table [Variable]
This is the abbrev table for mode-independent abbrevs. The abbrevs defined in it
apply to all buffers. Each buffer may also have a local abbrev table, whose abbrev
definitions take precedence over those in the global table.
local-abbrev-table [Variable]
The value of this buffer-local variable is the (mode-specific) abbreviation table of the
current buffer.
fundamental-mode-abbrev-table [Variable]
This is the local abbrev table used in Fundamental mode; in other words, it is the
local abbrev table in all buffers in Fundamental mode.
text-mode-abbrev-table [Variable]
This is the local abbrev table used in Text mode.
lisp-mode-abbrev-table [Variable]
This is the local abbrev table used in Lisp mode and Emacs Lisp mode.
Chapter 37: Processes 705
37 Processes
In the terminology of operating systems, a process is a space in which a program can execute.
Emacs runs in a process. Emacs Lisp programs can invoke other programs in processes of
their own. These are called subprocesses or child processes of the Emacs process, which is
their parent process.
A subprocess of Emacs may be synchronous or asynchronous, depending on how it is cre-
ated. When you create a synchronous subprocess, the Lisp program waits for the subprocess
to terminate before continuing execution. When you create an asynchronous subprocess, it
can run in parallel with the Lisp program. This kind of subprocess is represented within
Emacs by a Lisp object which is also called a “process.” Lisp programs can use this object
to communicate with the subprocess or to control it. For example, you can send signals,
obtain status information, receive output from the process, or send input to it.
exec-suffixes [Variable]
This variable is a list of suffixes (strings) to try adding to the specified program file
name. The list should include "" if you want the name to be tried exactly as specified.
The default value is system-dependent.
Please note: The argument program contains only the name of the program; it may not
contain any command-line arguments. You must use args to provide those.
Each of the subprocess-creating functions has a buffer-or-name argument which specifies
where the standard output from the program will go. It should be a buffer or a buffer name;
if it is a buffer name, that will create the buffer if it does not already exist. It can also be
Chapter 37: Processes 706
nil, which says to discard the output unless a filter function handles it. (See Section 37.9.2
[Filter Functions], page 718, and Chapter 19 [Read and Print], page 268.) Normally, you
should avoid having multiple processes send output to the same buffer because their output
would be intermixed randomly.
All three of the subprocess-creating functions have a &rest argument, args. The args
must all be strings, and they are supplied to program as separate command line arguments.
Wildcard characters and other shell constructs have no special meanings in these strings,
since the strings are passed directly to the specified program.
The subprocess gets its current directory from the value of default-directory (see
Section 25.8.4 [File Name Expansion], page 457).
The subprocess inherits its environment from Emacs, but you can specify overrides for
it with process-environment. See Section 39.3 [System Environment], page 819.
exec-directory [Variable]
The value of this variable is a string, the name of a directory that contains programs
that come with GNU Emacs, programs intended for Emacs to invoke. The program
movemail is an example of such a program; Rmail uses it to fetch new mail from an
inbox.
(real-destination error-destination )
Keep the standard output stream separate from the standard error
stream; deal with the ordinary output as specified by real-destination,
and dispose of the error output according to error-destination. If
error-destination is nil, that means to discard the error output, t means
mix it with the ordinary output, and a string specifies a file name to
redirect error output into.
You can’t directly specify a buffer to put the error output in; that is too
difficult to implement. But you can achieve this result by sending the
error output to a temporary file and then inserting the file into a buffer.
Here is a good example of the use of call-process, which used to be found in the
definition of insert-directory:
(call-process insert-directory-program nil t nil switches
(if full-directory-p
(concat (file-name-as-directory file) ".")
file))
Chapter 37: Processes 709
copies its standard input into its standard output. Since the argument destination is
t, this output is inserted in the current buffer.
---------- Buffer: foo ----------
input?
---------- Buffer: foo ----------
for the sake of uniqueness. It inserts the directory listing at the end of the buffer
‘foo’, before the first process finishes. Then it finishes, and a message to that effect
is inserted in the buffer. Much later, the first process finishes, and another message
is inserted in the buffer for it.
(start-process "my-process" "foo" "sleep" "100")
⇒ #<process my-process>
process-connection-type [Variable]
This variable controls the type of device used to communicate with asynchronous
subprocesses. If it is non-nil, then PTYs are used, when available. Otherwise, pipes
are used.
PTYs are usually preferable for processes visible to the user, as in Shell mode, because
they allow job control (C-c, C-z, etc.) to work between the process and its children,
whereas pipes do not. For subprocesses used for internal purposes by programs, it
is often better to use a pipe, because they are more efficient. In addition, the total
number of PTYs is limited on many systems and it is good not to waste them.
The value of process-connection-type takes effect when start-process is called.
So you can specify how to communicate with one subprocess by binding the variable
around the call to start-process.
(let ((process-connection-type nil)) ; Use a pipe.
(start-process ...))
To determine whether a given subprocess actually got a pipe or a PTY, use the
function process-tty-name (see Section 37.6 [Process Information], page 712).
Chapter 37: Processes 712
Sometimes the system is unable to accept input for that process, because the input buffer
is full. When this happens, the send functions wait a short while, accepting output from
subprocesses, and then try again. This gives the subprocess a chance to read more of its
pending input and make space in the buffer. It also allows filters, sentinels and timers to
run—so take account of that in writing your code.
In these functions, the process argument can be a process or the name of a process, or
a buffer or buffer name (which stands for a process via get-buffer-process). nil means
the current buffer’s process.
Each signal has a standard effect on the subprocess. Most signals kill the subprocess,
but some stop or resume execution instead. Most signals can optionally be handled by
programs; if the program handles the signal, then we can say nothing in general about its
effects.
You can send signals explicitly by calling the functions in this section. Emacs also
sends signals automatically at certain times: killing a buffer sends a SIGHUP signal to all
its associated processes; killing Emacs sends a SIGHUP signal to all remaining processes.
(SIGHUP is a signal that usually indicates that the user hung up the phone.)
Each of the signal-sending functions takes two optional arguments: process and current-
group.
The argument process must be either a process, a process name, a buffer, a buffer name,
or nil. A buffer or buffer name stands for a process through get-buffer-process. nil
stands for the process associated with the current buffer. An error is signaled if process
does not identify a process.
The argument current-group is a flag that makes a difference when you are running a
job-control shell as an Emacs subprocess. If it is non-nil, then the signal is sent to the
current process-group of the terminal that Emacs uses to communicate with the subprocess.
If the process is a job-control shell, this means the shell’s current subjob. If it is nil, the
signal is sent to the process group of the immediate subprocess of Emacs. If the subprocess
is a job-control shell, this is the shell itself.
The flag current-group has no effect when a pipe is used to communicate with the
subprocess, because the operating system does not support the distinction in the case of
pipes. For the same reason, job-control shells won’t work when a pipe is used. See process-
connection-type in Section 37.4 [Asynchronous Processes], page 710.
process-adaptive-read-buffering [Variable]
On some systems, when Emacs reads the output from a subprocess, the output data
is read in very small blocks, potentially resulting in very poor performance. This
behavior can be remedied to some extent by setting the variable process-adaptive-
read-buffering to a non-nil value (the default), as it will automatically delay reading
from such processes, thus allowing them to produce more output before Emacs tries
to read it.
It is impossible to separate the standard output and standard error streams of the
subprocess, because Emacs normally spawns the subprocess inside a pseudo-TTY, and a
pseudo-TTY has only one output channel. If you want to keep the output to those streams
separate, you should redirect one of them to a file—for example, by using an appropriate
shell command.
Unless the process has a filter function (see Section 37.9.2 [Filter Functions], page 718),
its output is inserted in the associated buffer. The position to insert the output is determined
by the process-mark, which is then updated to point to the end of the text just inserted.
Usually, but not always, the process-mark is at the end of the buffer.
A filter function must accept two arguments: the associated process and a string, which
is output just received from it. The function is then free to do whatever it chooses with the
output.
Quitting is normally inhibited within a filter function—otherwise, the effect of typing
C-g at command level or to quit a user command would be unpredictable. If you want to
permit quitting inside a filter function, bind inhibit-quit to nil. In most cases, the right
way to do this is with the macro with-local-quit. See Section 21.10 [Quitting], page 338.
If an error happens during execution of a filter function, it is caught automatically, so
that it doesn’t stop the execution of whatever program was running when the filter function
was started. However, if debug-on-error is non-nil, the error-catching is turned off. This
makes it possible to use the Lisp debugger to debug the filter function. See Section 18.1
[Debugger], page 237.
Many filter functions sometimes or always insert the text in the process’s buffer, mimick-
ing the actions of Emacs when there is no filter. Such filter functions need to use set-buffer
in order to be sure to insert in that buffer. To avoid setting the current buffer semiper-
manently, these filter functions must save and restore the current buffer. They should also
update the process marker, and in some cases update the value of point. Here is how to do
these things:
(defun ordinary-insertion-filter (proc string)
(with-current-buffer (process-buffer proc)
(let ((moving (= (point) (process-mark proc))))
(save-excursion
;; Insert the text, advancing the process marker.
(goto-char (process-mark proc))
(insert string)
(set-marker (process-mark proc) (point)))
(if moving (goto-char (process-mark proc))))))
The reason to use with-current-buffer, rather than using save-excursion to save and
restore the current buffer, is so as to preserve the change in point made by the second call
to goto-char.
To make the filter force the process buffer to be visible whenever new text arrives, insert
the following line just before the with-current-buffer construct:
(display-buffer (process-buffer proc))
To force point to the end of the new output, no matter where it was previously, eliminate
the variable moving and call goto-char unconditionally.
In earlier Emacs versions, every filter function that did regular expression searching
or matching had to explicitly save and restore the match data. Now Emacs does this
automatically for filter functions; they never need to do it explicitly. See Section 34.6
[Match Data], page 676.
A filter function that writes the output into the buffer of the process should check
whether the buffer is still alive. If it tries to insert into a dead buffer, it will get an error.
The expression (buffer-name (process-buffer process )) returns nil if the buffer is
dead.
The output to the function may come in chunks of any size. A program that produces
the same output twice in a row may send it as one batch of 200 characters one time, and five
batches of 40 characters the next. If the filter looks for certain text strings in the subprocess
Chapter 37: Processes 720
output, make sure to handle the case where one of these strings is split across two or more
batches of output.
produce a multibyte string, and passes that to the process. If the flag is nil, Emacs puts
the output into a unibyte string, with no decoding, and passes that.
When you create a process, the filter multibyte flag takes its initial value from default-
enable-multibyte-characters. If you want to change the flag later on, use set-process-
filter-multibyte.
• "finished\n".
• "exited abnormally with code exitcode \n".
• "name-of-signal \n".
• "name-of-signal (core dumped)\n".
A sentinel runs only while Emacs is waiting (e.g., for terminal input, or for time to
elapse, or for process output). This avoids the timing errors that could result from running
them at random places in the middle of other Lisp programs. A program can wait, so that
sentinels will run, by calling sit-for or sleep-for (see Section 21.9 [Waiting], page 337),
or accept-process-output (see Section 37.9.4 [Accepting Output], page 721). Emacs also
allows sentinels to run when the command loop is reading input. delete-process calls the
sentinel when it terminates a running process.
Emacs does not keep a queue of multiple reasons to call the sentinel of one process; it
records just the current status and the fact that there has been a change. Therefore two
changes in status, coming in quick succession, can call the sentinel just once. However,
process termination will always run the sentinel exactly once. This is because the process
status can’t change again after termination.
Emacs explicitly checks for output from the process before running the process sentinel.
Once the sentinel runs due to process termination, no further output can arrive from the
process.
A sentinel that writes the output into the buffer of the process should check whether the
buffer is still alive. If it tries to insert into a dead buffer, it will get an error. If the buffer
is dead, (buffer-name (process-buffer process )) returns nil.
Quitting is normally inhibited within a sentinel—otherwise, the effect of typing C-g at
command level or to quit a user command would be unpredictable. If you want to permit
quitting inside a sentinel, bind inhibit-quit to nil. In most cases, the right way to do
this is with the macro with-local-quit. See Section 21.10 [Quitting], page 338.
If an error happens during execution of a sentinel, it is caught automatically, so that it
doesn’t stop the execution of whatever programs was running when the sentinel was started.
However, if debug-on-error is non-nil, the error-catching is turned off. This makes it
possible to use the Lisp debugger to debug the sentinel. See Section 18.1 [Debugger],
page 237.
While a sentinel is running, the process sentinel is temporarily set to nil so that the
sentinel won’t run recursively. For this reason it is not possible for a sentinel to specify a
new sentinel.
In earlier Emacs versions, every sentinel that did regular expression searching or match-
ing had to explicitly save and restore the match data. Now Emacs does this automatically
for sentinels; they never need to do it explicitly. See Section 34.6 [Match Data], page 676.
set-process-sentinel process sentinel [Function]
This function associates sentinel with process. If sentinel is nil, then the process will
have no sentinel. The default behavior when there is no sentinel is to insert a message
in the process’s buffer when the process status changes.
Changes in process sentinel take effect immediately—if the sentinel is slated to be
run but has not been called yet, and you specify a new sentinel, the eventual call to
the sentinel will use the new one.
Chapter 37: Processes 723
waiting-for-user-input-p [Function]
While a sentinel or filter function is running, this function returns non-nil if Emacs
was waiting for keyboard input from the user at the time the sentinel or filter function
was called, nil if it was not.
Transaction queues are implemented by means of a filter function. See Section 37.9.2
[Filter Functions], page 718.
You can distinguish process objects representing network connections and servers from
those representing subprocesses with the process-status function. The possible status
values for network connections are open, closed, connect, and failed. For a network
server, the status is always listen. None of those values is possible for a real subprocess.
See Section 37.6 [Process Information], page 712.
You can stop and resume operation of a network process by calling stop-process and
continue-process. For a server process, being stopped means not accepting new connec-
tions. (Up to 5 connection requests will be queued for when you resume the server; you
can increase this limit, unless it is imposed by the operating system.) For a network stream
connection, being stopped means not processing input (any arriving input waits until you
resume the connection). For a datagram connection, some number of packets may be queued
but input may be lost. You can use the function process-command to determine whether
a network connection or server is stopped; a non-nil value means yes.
:local and :remote are included even if they were not specified explicitly in make-
network-process.
If key is a keyword, the function returns the value corresponding to that keyword.
For an ordinary child process, this function always returns t.
37.15 Datagrams
A datagram connection communicates with individual packets rather than streams of data.
Each call to process-send sends one datagram packet (see Section 37.7 [Input to Processes],
page 714), and each datagram received results in one call to the filter function.
The datagram connection doesn’t have to talk with the same remote peer all the time.
It has a remote peer address which specifies where to send datagrams to. Each time an
incoming datagram is passed to the filter function, the peer address is set to the address that
datagram came from; that way, if the filter function sends a datagram, it will go back to that
place. You can specify the remote peer address when you create the datagram connection
using the :remote keyword. You can change it later on by calling set-process-datagram-
address.
37.16.1 make-network-process
The basic function for creating network connections and network servers is make-network-
process. It can do either of those jobs, depending on the arguments you give it.
:local local-address
For a server process, local-address is the address to listen on. It overrides
family, host and service, and you may as well not specify them.
:remote remote-address
For a connection, remote-address is the address to connect to. It overrides
family, host and service, and you may as well not specify them.
For a datagram server, remote-address specifies the initial setting of the
remote datagram address.
The format of local-address or remote-address depends on the address
family:
- An IPv4 address is represented as a five-element vector of four 8-
bit integers and one 16-bit integer [a b c d p ] corresponding to
numeric IPv4 address a.b.c.d and port number p.
- An IPv6 address is represented as a nine-element vector of 16-bit in-
tegers [a b c d e f g h p ] corresponding to numeric IPv6 address
a:b:c:d:e:f :g:h and port number p.
- A local address is represented as a string which specifies the address
in the local address space.
- An “unsupported family” address is represented by a cons (f . av ),
where f is the family number and av is a vector specifying the socket
address using one element per address data byte. Do not rely on
this format in portable code, as it may depend on implementation
defined constants, data sizes, and data structure alignment.
:nowait bool
If bool is non-nil for a stream connection, return without waiting for
the connection to complete. When the connection succeeds or fails,
Emacs will call the sentinel function, with a second argument matching
"open" (if successful) or "failed". The default is to block, so that make-
network-process does not return until the connection has succeeded or
failed.
:stop stopped
Start the network connection or server in the ‘stopped’ state if stopped
is non-nil.
:buffer buffer
Use buffer as the process buffer.
:coding coding
Use coding as the coding system for this process. To specify different
coding systems for decoding data from the connection and for encoding
data sent to it, specify (decoding . encoding ) for coding.
If you don’t specify this keyword at all, the default is to determine the
coding systems from the data.
:noquery query-flag
Initialize the process query flag to query-flag. See Section 37.11 [Query
Before Exit], page 723.
Chapter 37: Processes 729
:filter filter
Initialize the process filter to filter.
:filter-multibyte bool
If bool is non-nil, strings given to the process filter are multibyte, oth-
erwise they are unibyte. If you don’t specify this keyword at all, the
default is that the strings are multibyte if default-enable-multibyte-
characters is non-nil.
:sentinel sentinel
Initialize the process sentinel to sentinel.
:log log Initialize the log function of a server process to log. The log function is
called each time the server accepts a network connection from a client.
The arguments passed to the log function are server, connection, and
message, where server is the server process, connection is the new process
for the connection, and message is a string describing what has happened.
:plist plist Initialize the process plist to plist.
The original argument list, modified with the actual connection information, is avail-
able via the process-contact function.
integer, it specifies the maximum time in seconds to wait for queued packets to
be sent before closing the connection. Default is nil which means to discard
unsent queued packets when the process is deleted.
:oobinline oobinline-flag
If oobinline-flag is non-nil for a stream connection, receive out-of-band data
in the normal data stream. Otherwise, ignore out-of-band data.
:priority priority
Set the priority for packets sent on this connection to the integer priority. The
interpretation of this number is protocol specific, such as setting the TOS (type
of service) field on IP packets sent on this connection. It may also have system
dependent effects, such as selecting a specific output queue on the network
interface.
:reuseaddr reuseaddr-flag
If reuseaddr-flag is non-nil (the default) for a stream server process, allow this
server to reuse a specific port number (see :service) unless another process on
this host is already listening on that port. If reuseaddr-flag is nil, there may
be a period of time after the last use of that port (by any process on the host),
where it is not possible to make a new server on that port.
:bindtodevice
:broadcast
:dontroute
:keepalive
:linger
:oobinline
:priority
:reuseaddr
That particular network option is supported by make-network-process and
set-network-process-option.
network-interface-list [Function]
This function returns a list describing the network interfaces of the machine you
are using. The value is an alist whose elements have the form (name . address ).
address has the same form as the local-address and remote-address arguments to
make-network-process.
(eval form )
form is a Lisp expression evaluated at the moment the field is unpacked or
packed. The result of the evaluation should be one of the above-listed type
specifications.
For a fixed-size field, the length len is given as an integer specifying the number of bytes
in the field.
When the length of a field is not fixed, it typically depends on the value of a preceding
field. In this case, the length len can be given either as a list (name ...) identifying a
field name in the format specified for bindat-get-field below, or by an expression (eval
form ) where form should evaluate to an integer, specifying the field length.
A field specification generally has the form ([name ] handler ). The square braces indi-
cate that name is optional. (Don’t use names that are symbols meaningful as type speci-
fications (above) or handler specifications (below), since that would be ambiguous.) name
can be a symbol or the expression (eval form ), in which case form should evaluate to a
symbol.
handler describes how to unpack or pack the field and can be one of the following:
type Unpack/pack this field according to the type specification type.
eval form
Evaluate form, a Lisp expression, for side-effect only. If the field name is spec-
ified, the value is bound to that field name.
fill len Skip len bytes. In packing, this leaves them unchanged, which normally means
they remain zero. In unpacking, this means they are ignored.
align len
Skip to the next multiple of len bytes.
struct spec-name
Process spec-name as a sub-specification. This describes a structure nested
within another structure.
union form (tag spec )...
Evaluate form, a Lisp expression, find the first tag that matches it, and process
its associated data layout specification spec. Matching can occur in one of three
ways:
• If a tag has the form (eval expr ), evaluate expr with the variable tag
dynamically bound to the value of form. A non-nil result indicates a
match.
• tag matches if it is equal to the value of form.
• tag matches unconditionally if it is t.
repeat count field-specs ...
Process the field-specs recursively, in order, then repeat starting from the first
one, processing all the specs count times overall. The count is given using the
same formats as a field length—if an eval form is used, it is evaluated just
once. For correct operation, each spec in field-specs must include a name.
Chapter 37: Processes 734
For the (eval form ) forms used in a bindat specification, the form can access and update
these dynamically bound variables during evaluation:
last Value of the last field processed.
bindat-raw
The data as a byte array.
bindat-idx
Current index (within bindat-raw) for unpacking or packing.
struct The alist containing the structured data that have been unpacked so far, or
the entire structure being packed. You can use bindat-get-field to access
specific fields of this structure.
count
index Inside a repeat block, these contain the maximum number of repetitions (as
specified by the count parameter), and the current repetition number (counting
from 0). Setting count to zero will terminate the inner-most repeat block after
the current repetition has completed.
Although packing and unpacking operations change the organization of data (in mem-
ory), they preserve the data’s total length, which is the sum of all the fields’ lengths, in
bytes. This value is not generally inherent in either the specification or alist alone; instead,
both pieces of information contribute to its calculation. Likewise, the length of a string
or array being unpacked may be longer than the data’s total length as described by the
specification.
bindat-ip-to-string ip [Function]
Convert the Internet address vector ip to a string in the usual dotted notation.
(bindat-ip-to-string [127 0 0 1])
⇒ "127.0.0.1"
(switch-to-buffer
(get-buffer-create
(format "*Fortune Cookie: %s*"
(file-name-nondirectory cookies))))
(erase-buffer)
(insert-file-contents-literally
cookies nil beg (- end 3))))
struct data {
unsigned char type;
unsigned char opcode;
unsigned short length; /* In network byte order */
unsigned char id[8]; /* null-terminated string */
unsigned char data[/* (length + 3) & ~3 */];
};
struct packet {
struct header header;
unsigned long counters[2]; /* In little endian order */
unsigned char items;
unsigned char filler[3];
struct data item[/* items */];
};
The corresponding data layout specification:
(setq header-spec
’((dest-ip ip)
(src-ip ip)
(dest-port u16)
(src-port u16)))
(setq data-spec
’((type u8)
(opcode u8)
(length u16) ;; network byte order
(id strz 8)
(data vec (length))
(align 4)))
(setq packet-spec
’((header struct header-spec)
(counters vec 2 u32r) ;; little endian order
(items u8)
(fill 3)
Chapter 37: Processes 738
38 Emacs Display
This chapter describes a number of features related to the display that Emacs presents to
the user.
redraw-display [Command]
This function clears and redisplays all visible frames.
This function calls for redisplay of certain windows, the next time redisplay is done, but
does not clear them first.
Processing user input takes absolute priority over redisplay. If you call these functions
when input is available, they do nothing immediately, but a full redisplay does happen
eventually—after all the input has been processed.
Normally, suspending and resuming Emacs also refreshes the screen. Some terminal
emulators record separate contents for display-oriented programs such as Emacs and for
ordinary sequential display. If you are using such a terminal, you might want to inhibit the
redisplay on resumption.
no-redraw-on-reenter [Variable]
This variable controls whether Emacs redraws the entire screen after it has been
suspended and resumed. Non-nil means there is no need to redraw, nil means
redrawing is needed. The default is nil.
redisplay-preemption-period [Variable]
This variable specifies how many seconds Emacs waits between checks for new input
during redisplay. (The default is 0.1 seconds.) If input has arrived when Emacs
Chapter 38: Emacs Display 740
checks, it pre-empts redisplay and processes the available input before trying again
to redisplay.
If this variable is nil, Emacs does not check for input during redisplay, and redisplay
cannot be preempted by input.
This variable is only obeyed on graphical terminals. For text terminals, see Sec-
tion 39.13 [Terminal Output], page 834.
redisplay-dont-pause [Variable]
If this variable is non-nil, pending input does not prevent or halt redisplay; redisplay
occurs, and finishes, regardless of whether input is available.
redisplay &optional force [Function]
This function performs an immediate redisplay provided there are no pending input
events. This is equivalent to (sit-for 0).
If the optional argument force is non-nil, it forces an immediate and complete redis-
play even if input is available.
Returns t if redisplay was performed, or nil otherwise.
38.3 Truncation
When a line of text extends beyond the right edge of a window, Emacs can continue the line
(make it “wrap” to the next screen line), or truncate the line (limit it to one screen line).
The additional screen lines used to display a long text line are called continuation lines.
Continuation is not the same as filling; continuation happens on the screen only, not in the
buffer contents, and it breaks a line precisely at the right margin, not at a word boundary.
See Section 32.11 [Filling], page 599.
On a graphical display, tiny arrow images in the window fringes indicate truncated
and continued lines (see Section 38.13 [Fringes], page 776). On a text terminal, a ‘$’ in
the rightmost column of the window indicates truncation; a ‘\’ on the rightmost column
indicates a line that “wraps.” (The display table can specify alternate characters to use for
this; see Section 38.21 [Display Tables], page 807).
truncate-lines [User Option]
This buffer-local variable controls how Emacs displays lines that extend beyond the
right edge of the window. The default is nil, which specifies continuation. If the
value is non-nil, then these lines are truncated.
If the variable truncate-partial-width-windows is non-nil, then truncation is al-
ways used for side-by-side windows (within one frame) regardless of the value of
truncate-lines.
default-truncate-lines [User Option]
This variable is the default value for truncate-lines, for buffers that do not have
buffer-local values for it.
truncate-partial-width-windows [User Option]
This variable controls display of lines that extend beyond the right edge of the window,
in side-by-side windows (see Section 28.2 [Splitting Windows], page 498). If it is non-
nil, these lines are truncated; otherwise, truncate-lines says what to do with
them.
Chapter 38: Emacs Display 741
When horizontal scrolling (see Section 28.13 [Horizontal Scrolling], page 518) is in use
in a window, that forces truncation.
If your buffer contains very long lines, and you use continuation to display them, just
thinking about them can make Emacs redisplay slow. The column computation and inden-
tation functions also become slow. Then you might find it advisable to set cache-long-
line-scans to t.
cache-long-line-scans [Variable]
If this variable is non-nil, various indentation and motion functions, and Emacs
redisplay, cache the results of scanning the buffer, and consult the cache to avoid
rescanning regions of the buffer unless they are modified.
Turning on the cache slows down processing of short lines somewhat.
This variable is automatically buffer-local in every buffer.
current-message [Function]
This function returns the message currently being displayed in the echo area, or nil
if there is none.
Chapter 38: Emacs Display 743
To make ‘*Messages*’ more convenient for the user, the logging facility combines suc-
cessive identical messages. It also combines successive related messages for the sake of two
cases: question followed by answer, and a series of progress messages.
Chapter 38: Emacs Display 745
A “question followed by an answer” means two messages like the ones produced by
y-or-n-p: the first is ‘question ’, and the second is ‘question...answer ’. The first mes-
sage conveys no additional information beyond what’s in the second, so logging the second
message discards the first from the log.
A “series of progress messages” means successive messages like those produced by make-
progress-reporter. They have the form ‘base...how-far ’, where base is the same each
time, while how-far varies. Logging each message in the series discards the previous one,
provided they are consecutive.
The functions make-progress-reporter and y-or-n-p don’t have to do anything spe-
cial to activate the message log combination feature. It operates whenever two consecutive
messages are logged that share a common prefix ending in ‘...’.
cursor-in-echo-area [Variable]
This variable controls where the cursor appears when a message is displayed in the
echo area. If it is non-nil, then the cursor appears at the end of the message.
Otherwise, the cursor appears at point—not in the echo area at all.
The value is normally nil; Lisp programs bind it to t for brief periods of time.
echo-area-clear-hook [Variable]
This normal hook is run whenever the echo area is cleared—either by (message nil)
or for any other reason.
echo-keystrokes [Variable]
This variable determines how much time should elapse before command characters
echo. Its value must be an integer or floating point number, which specifies the
number of seconds to wait before echoing. If the user types a prefix key (such as C-x)
and then delays this many seconds before continuing, the prefix key is echoed in the
echo area. (Once echoing begins in a key sequence, all subsequent characters in the
same key sequence are echoed immediately.)
If the value is zero, then command input is not echoed.
message-truncate-lines [Variable]
Normally, displaying a long message resizes the echo area to display the entire message.
But if the variable message-truncate-lines is non-nil, the echo area does not resize,
and the message is truncated to fit it, as in Emacs 20 and before.
The variable max-mini-window-height, which specifies the maximum height for resizing
minibuffer windows, also applies to the echo area (which is really a special use of the
minibuffer window. See Section 20.14 [Minibuffer Misc], page 302.
warning-levels [Variable]
This list defines the meaning and severity order of the warning severity levels. Each
element defines one severity level, and they are arranged in order of decreasing severity.
Each element has the form (level string function ), where level is the severity
level it defines. string specifies the textual description of this level. string should use
‘%s’ to specify where to put the warning type information, or it can omit the ‘%s’ so
as not to include that information.
The optional function, if non-nil, is a function to call with no arguments, to get the
user’s attention.
Normally you should not change the value of this variable.
warning-prefix-function [Variable]
If non-nil, the value is a function to generate prefix text for warnings. Programs can
bind the variable to a suitable function. display-warning calls this function with
the warnings buffer current, and the function can insert text in it. That text becomes
the beginning of the warning message.
The function is called with two arguments, the severity level and its entry in warning-
levels. It should return a list to use as the entry (this value need not be an actual
member of warning-levels). By constructing this value, the function can change
the severity of the warning, or specify different handling for a given severity level.
If the variable’s value is nil then there is no function to call.
warning-series [Variable]
Programs can bind this variable to t to say that the next warning should begin a
series. When several warnings form a series, that means to leave point on the first
warning of the series, rather than keep moving it for each warning so that it appears on
the last one. The series ends when the local binding is unbound and warning-series
becomes nil again.
The value can also be a symbol with a function definition. That is equivalent to t,
except that the next warning will also call the function with no arguments with the
warnings buffer current. The function can insert text which will serve as a header for
the series of warnings.
Once a series has begun, the value is a marker which points to the buffer position in
the warnings buffer of the start of the series.
The variable’s normal value is nil, which means to handle each warning separately.
warning-fill-prefix [Variable]
When this variable is non-nil, it specifies a fill prefix to use for filling each warning’s
text.
warning-type-format [Variable]
This variable specifies the format for displaying the warning type in the warning
message. The result of formatting the type this way gets included in the message
under the control of the string in the entry in warning-levels. The default value is
" (%s)". If you bind it to "" then the warning type won’t appear at all.
Chapter 38: Emacs Display 748
command moved point back into an invisible range, Emacs moves point back to the be-
ginning of that range, and then back one more character. If the command moved point
forward into an invisible range, Emacs moves point forward up to the first visible character
that follows the invisible text.
Incremental search can make invisible overlays visible temporarily and/or permanently
when a match includes invisible text. To enable this, the overlay should have a non-nil
isearch-open-invisible property. The property value should be a function to be called
with the overlay as an argument. This function should make the overlay visible permanently;
it is used when the match overlaps the overlay on exit from the search.
During the search, such overlays are made temporarily visible by temporarily modifying
their invisible and intangible properties. If you want this to be done differently for a certain
overlay, give it an isearch-open-invisible-temporary property which is a function. The
function is called with two arguments: the first is the overlay, and the second is nil to make
the overlay visible, or t to make it invisible again.
When some portion of a buffer is hidden, the vertical movement commands operate
as if that portion did not exist, allowing a single next-line command to skip any
number of hidden lines. However, character movement commands (such as forward-
char) do not skip the hidden portion, and it is possible (if tricky) to insert or delete
text in an hidden portion.
In the examples below, we show the display appearance of the buffer foo, which
changes with the value of selective-display. The contents of the buffer do not
change.
(setq selective-display nil)
⇒ nil
(setq selective-display 2)
⇒ 2
selective-display-ellipses [Variable]
If this buffer-local variable is non-nil, then Emacs displays ‘...’ at the end of a line
that is followed by hidden text. This example is a continuation of the previous one.
(setq selective-display-ellipses t)
⇒ t
(with-output-to-temp-buffer "foo"
(print 20)
(print standard-output))
⇒ #<buffer foo>
#<buffer foo>
temp-buffer-show-function [Variable]
If this variable is non-nil, with-output-to-temp-buffer calls it as a function to
do the job of displaying a help buffer. The function gets one argument, which is the
buffer it should display.
Chapter 38: Emacs Display 753
temp-buffer-setup-hook [Variable]
This normal hook is run by with-output-to-temp-buffer before evaluating body.
When the hook runs, the temporary buffer is current. This hook is normally set up
with a function to put the buffer in Help mode.
temp-buffer-show-hook [Variable]
This normal hook is run by with-output-to-temp-buffer after displaying the tem-
porary buffer. When the hook runs, the temporary buffer is current, and the window
it was displayed in is selected. This hook is normally set up with a function to make
the buffer read only, and find function names and variable names in it, provided the
major mode is Help mode.
(momentary-string-display
"**** Important Message! ****"
(point) ?\r
"Type RET when done reading")
⇒ t
Chapter 38: Emacs Display 754
38.9 Overlays
You can use overlays to alter the appearance of a buffer’s text on the screen, for the sake of
presentation features. An overlay is an object that belongs to a particular buffer, and has
a specified beginning and end. It also has properties that you can examine and set; these
affect the display of the text within the overlay.
An overlay uses markers to record its beginning and end; thus, editing the text of the
buffer adjusts the beginning and end of each overlay so that it stays with the text. When
you create the overlay, you can specify whether text inserted at the beginning should be
inside the overlay or outside, and likewise for the end of the overlay.
(overlay-start foo)
⇒ 5
(overlay-end foo)
⇒ 20
;; Delete the overlay.
(delete-overlay foo)
⇒ nil
;; Verify it is deleted.
foo
⇒ #<overlay in no buffer>
;; A deleted overlay has no position.
(overlay-start foo)
⇒ nil
(overlay-end foo)
⇒ nil
(overlay-buffer foo)
⇒ nil
;; Undelete the overlay.
(move-overlay foo 1 20)
⇒ #<overlay from 1 to 20 in display.texi>
;; Verify the results.
(overlay-start foo)
⇒ 1
(overlay-end foo)
⇒ 20
(overlay-buffer foo)
⇒ #<buffer display.texi>
;; Moving and deleting the overlay does not change its properties.
(overlay-get foo ’happy)
⇒ t
Emacs stores the overlays of each buffer in two lists, divided around an arbitrary “center
position.” One list extends backwards through the buffer from that center position, and
the other extends forwards from that center position. The center position can be anywhere
in the buffer.
A loop that scans the buffer forwards, creating overlays, can run faster if you do
(overlay-recenter (point-max)) first.
Text properties are considered a part of the text; overlays and their properties are
specifically considered not to be part of the text. Thus, copying text between various buffers
and strings preserves text properties, but does not try to preserve overlays. Changing a
buffer’s text properties marks the buffer as modified, while moving an overlay or changing
its properties does not. Unlike text property changes, overlay property changes are not
recorded in the buffer’s undo list.
These functions read and set the properties of an overlay:
overlay-get overlay prop [Function]
This function returns the value of property prop recorded in overlay, if any. If overlay
does not record any value for that property, but it does have a category property
which is a symbol, that symbol’s prop property is used. Otherwise, the value is nil.
overlay-put overlay prop value [Function]
This function sets the value of property prop recorded in overlay to value. It returns
value.
overlay-properties overlay [Function]
This returns a copy of the property list of overlay.
See also the function get-char-property which checks both overlay properties and text
properties for a given character. See Section 32.19.1 [Examining Properties], page 615.
Many overlay properties have special meanings; here is a table of them:
priority This property’s value (which should be a nonnegative integer number) deter-
mines the priority of the overlay. The priority matters when two or more
overlays cover the same character and both specify the same property; the one
whose priority value is larger takes priority over the other. For the face prop-
erty, the higher priority value does not completely replace the other; instead, its
face attributes override the face attributes of the lower priority face property.
Currently, all overlays take priority over text properties. Please avoid using
negative priority values, as we have not yet decided just what they should
mean.
window If the window property is non-nil, then the overlay applies only on that window.
category If an overlay has a category property, we call it the category of the overlay.
It should be a symbol. The properties of the symbol serve as defaults for the
properties of the overlay.
face This property controls the way text is displayed—for example, which font and
which colors. See Section 38.12 [Faces], page 762, for more information.
In the simplest case, the value is a face name. It can also be a list; then each
element can be any of these possibilities:
• A face name (a symbol or string).
• A property list of face attributes. This has the form (keyword value . . . ),
where each keyword is a face attribute name and value is a meaningful
value for that attribute. With this feature, you do not need to create a
face each time you want to specify a particular attribute for certain text.
See Section 38.12.2 [Face Attributes], page 765.
Chapter 38: Emacs Display 758
invisible
The invisible property can make the text in the overlay invisible, which
means that it does not appear on the screen. See Section 38.6 [Invisible Text],
page 748, for details.
intangible
The intangible property on an overlay works just like the intangible text
property. See Section 32.19.4 [Special Properties], page 620, for details.
isearch-open-invisible
This property tells incremental search how to make an invisible overlay visible,
permanently, if the final match overlaps it. See Section 38.6 [Invisible Text],
page 748.
isearch-open-invisible-temporary
This property tells incremental search how to make an invisible overlay visible,
temporarily, during the search. See Section 38.6 [Invisible Text], page 748.
before-string
This property’s value is a string to add to the display at the beginning of the
overlay. The string does not appear in the buffer in any sense—only on the
screen.
after-string
This property’s value is a string to add to the display at the end of the overlay.
The string does not appear in the buffer in any sense—only on the screen.
evaporate
If this property is non-nil, the overlay is deleted automatically if it becomes
empty (i.e., if its length becomes zero). If you give an empty overlay a non-nil
evaporate property, that deletes it immediately.
local-map
If this property is non-nil, it specifies a keymap for a portion of the text. The
property’s value replaces the buffer’s local map, when the character after point
is within the overlay. See Section 22.7 [Active Keymaps], page 353.
keymap The keymap property is similar to local-map but overrides the buffer’s local
map (and the map specified by the local-map property) rather than replacing
it.
(while overlays
(let ((overlay (car overlays)))
(if (overlay-get overlay prop)
(setq found (cons overlay found))))
(setq overlays (cdr overlays)))
found))
38.10 Width
Since not all characters have the same width, these functions let you check the width of
a character. See Section 32.17.1 [Primitive Indent], page 610, and Section 30.2.5 [Screen
Lines], page 564, for related functions.
char-width char [Function]
This function returns the width in columns of the character char, if it were displayed
in the current buffer and the selected window.
string-width string [Function]
This function returns the width in columns of the string string, if it were displayed
in the current buffer and the selected window.
truncate-string-to-width string width &optional start-column [Function]
padding ellipsis
This function returns the part of string that fits within width columns, as a new
string.
Chapter 38: Emacs Display 761
If string does not reach width, then the result ends where string ends. If one multi-
column character in string extends across the column width, that character is not
included in the result. Thus, the result can fall short of width but cannot go beyond
it.
The optional argument start-column specifies the starting column. If this is non-
nil, then the first start-column columns of the string are omitted from the value. If
one multi-column character in string extends across the column start-column, that
character is not included.
The optional argument padding, if non-nil, is a padding character added at the
beginning and end of the result string, to extend it to exactly width columns. The
padding character is used at the end of the result if it falls short of width. It is also
used at the beginning of the result if one multi-column character in string extends
across the column start-column.
If ellipsis is non-nil, it should be a string which will replace the end of str (including
any padding) if it extends beyond end-column, unless the display width of str is equal
to or less than the display width of ellipsis. If ellipsis is non-nil and not a string, it
stands for "...".
(truncate-string-to-width "\tab\t" 12 4)
⇒ "ab"
(truncate-string-to-width "\tab\t" 12 4 ?\s)
⇒ " ab "
integer If the height spec is a positive integer, the height value is that integer.
float If the height spec is a float, float, the numeric height value is float times the
frame’s default line height.
(face . ratio )
If the height spec is a cons of the format shown, the numeric height is ratio
times the height of face face. ratio can be any type of number, or nil which
means a ratio of 1. If face is t, it refers to the current face.
(nil . ratio )
If the height spec is a cons of the format shown, the numeric height is ratio
times the height of the contents of the line.
Thus, any valid height spec determines the height in pixels, one way or another. If the
line contents’ height is less than that, Emacs adds extra vertical space above the line to
achieve the specified total height.
If you don’t specify the line-height property, the line’s height consists of the contents’
height plus the line spacing. There are several ways to specify the line spacing for different
parts of Emacs text.
You can specify the line spacing for all lines in a frame with the line-spacing frame
parameter (see Section 29.3.3.4 [Layout Parameters], page 534). However, if the variable
default-line-spacing is non-nil, it overrides the frame’s line-spacing parameter. An
integer value specifies the number of pixels put below lines on graphical displays. A floating
point number specifies the spacing relative to the frame’s default line height.
You can specify the line spacing for all lines in a buffer via the buffer-local line-spacing
variable. An integer value specifies the number of pixels put below lines on graphical
displays. A floating point number specifies the spacing relative to the default frame line
height. This overrides line spacings specified for the frame.
Finally, a newline can have a line-spacing text or overlay property that overrides the
default frame line spacing and the buffer local line-spacing variable, for the display line
ending in that newline.
One way or another, these mechanisms specify a Lisp value for the spacing of each line.
The value is a height spec, and it translates into a Lisp value as described above. However,
in this case the numeric height value specifies the line spacing, rather than the line height.
38.12 Faces
A face is a named collection of graphical attributes: font family, foreground color, back-
ground color, optional underlining, and many others. Faces are used in Emacs to control the
style of display of particular parts of the text or the frame. See section “Standard Faces”
in The GNU Emacs Manual, for the list of faces Emacs normally comes with.
Each face has its own face number, which distinguishes faces at low levels within Emacs.
However, for most purposes, you refer to faces in Lisp programs by the symbols that name
them.
facep object [Function]
This function returns t if object is a face name string or symbol (or if it is a vector
of the kind used internally to record face data). It returns nil otherwise.
Chapter 38: Emacs Display 763
Each face name is meaningful for all frames, and by default it has the same meaning in
all frames. But you can arrange to give a particular face name a special meaning in one
frame if you wish.
regardless of their actual background colors. If it is light, then Emacs treats all
frames as if they had a light background.
:inverse-video
Whether or not characters should be displayed in inverse video. The value
should be t (yes) or nil (no).
:stipple The background stipple, a bitmap.
The value can be a string; that should be the name of a file containing external-
format X bitmap data. The file is found in the directories listed in the variable
x-bitmap-file-path.
Alternatively, the value can specify the bitmap directly, with a list of the form
(width height data ). Here, width and height specify the size in pixels, and
data is a string containing the raw bits of the bitmap, row by row. Each row
occupies (width+7)/8 consecutive bytes in the string (which should be a unibyte
string for best results). This means that each row always occupies at least one
whole byte.
If the value is nil, that means use no stipple pattern.
Normally you do not need to set the stipple attribute, because it is used auto-
matically to handle certain shades of gray.
:underline
Whether or not characters should be underlined, and in what color. If the value
is t, underlining uses the foreground color of the face. If the value is a string,
underlining uses that color. The value nil means do not underline.
:overline
Whether or not characters should be overlined, and in what color. The value
is used like that of :underline.
:strike-through
Whether or not characters should be strike-through, and in what color. The
value is used like that of :underline.
:inherit The name of a face from which to inherit attributes, or a list of face names.
Attributes from inherited faces are merged into the face like an underlying face
would be, with higher priority than underlying faces. If a list of faces is used,
attributes from faces earlier in the list override those from later faces.
:box Whether or not a box should be drawn around characters, its color, the width
of the box lines, and 3D appearance.
Here are the possible values of the :box attribute, and what they mean:
nil Don’t draw a box.
t Draw a box with lines of width 1, in the foreground color.
color Draw a box with lines of width 1, in color color.
(:line-width width :color color :style style )
This way you can explicitly specify all aspects of the box. The value width
specifies the width of the lines to draw; it defaults to 1.
The value color specifies the color to draw with. The default is the foreground
color of the face for simple boxes, and the background color of the face for 3D
boxes.
Chapter 38: Emacs Display 767
x-bitmap-file-path [Variable]
This variable specifies a list of directories for searching for bitmap files, for the
:stipple attribute.
:underline "red")
sets the attributes :width, :weight and :underline to the corresponding values.
If frame is t, this function sets the default attributes for new frames. Default attribute
values specified this way override the defface for newly created frames.
If frame is nil, this function sets the attributes for all existing frames, and the default
for new frames.
face-attribute face attribute &optional frame inherit [Function]
This returns the value of the attribute attribute of face face on frame. If frame is
nil, that means the selected frame (see Section 29.9 [Input Focus], page 543).
If frame is t, this returns whatever new-frames default value you previously specified
with set-face-attribute for the attribute attribute of face. If you have not specified
one, it returns nil.
If inherit is nil, only attributes directly defined by face are considered, so the return
value may be unspecified, or a relative value. If inherit is non-nil, face’s definition
of attribute is merged with the faces specified by its :inherit attribute; however the
return value may still be unspecified or relative. If inherit is a face or a list of faces,
then the result is further merged with that face (or faces), until it becomes specified
and absolute.
To ensure that the return value is always specified and absolute, use a value of default
for inherit; this will resolve any unspecified or relative values by merging with the
default face (which is always completely specified).
For example,
(face-attribute ’bold :weight)
⇒ bold
When multiple overlays cover one character, an overlay with higher priority overrides
those with lower priority. See Section 38.9 [Overlays], page 754.
face-font-selection-order [Variable]
This variable specifies the order of importance of the face attributes :width, :height,
:weight, and :slant. The value should be a list containing those four symbols, in
order of decreasing importance.
Font selection first finds the best available matches for the first attribute listed; then,
among the fonts which are best in that way, it searches for the best matches in the
second attribute, and so on.
The attributes :weight and :width have symbolic values in a range centered around
normal. Matches that are more extreme (farther from normal) are somewhat pre-
ferred to matches that are less extreme (closer to normal); this is designed to ensure
that non-normal faces contrast with normal ones, whenever possible.
The default is (:width :height :weight :slant), which means first find the fonts
closest to the specified :width, then—among the fonts with that width—find a best
match for the specified font height, and so on.
One example of a case where this variable makes a difference is when the default font
has no italic equivalent. With the default ordering, the italic face will use a non-
italic font that is similar to the default one. But if you put :slant before :height,
the italic face will use an italic font, even if its height is not quite right.
face-font-family-alternatives [Variable]
This variable lets you specify alternative font families to try, if a given family is
specified and doesn’t exist. Each element should have this form:
(family alternate-families ...)
If family is specified but not available, Emacs will try the other families given in
alternate-families, one by one, until it finds a family that does exist.
face-font-registry-alternatives [Variable]
This variable lets you specify alternative font registries to try, if a given registry is
specified and doesn’t exist. Each element should have this form:
Chapter 38: Emacs Display 772
Emacs can make use of scalable fonts, but by default it does not use them, since the use
of too many or too big scalable fonts can crash XFree86 servers.
scalable-fonts-allowed [Variable]
This variable controls which scalable fonts to use. A value of nil, the default, means
do not use scalable fonts. t means to use any scalable font that seems appropriate
for the text.
Otherwise, the value must be a list of regular expressions. Then a scalable font is
enabled for use if its name matches any regular expression in the list. For example,
(setq scalable-fonts-allowed ’("muleindian-2$"))
allows the use of scalable fonts with registry muleindian-2.
face-font-rescale-alist [Variable]
This variable specifies scaling for certain faces. Its value should be a list of elements
of the form
(fontname-regexp . scale-factor )
If fontname-regexp matches the font name that is about to be used, this says to choose
a larger similar font according to the factor scale-factor. You would use this feature
to normalize the font size if certain fonts are bigger or smaller than their nominal
heights and widths would suggest.
face-list [Function]
This function returns a list of all defined face names.
A face alias provides an equivalent name for a face. You can define a face alias by
giving the alias symbol the face-alias property, with a value of the target face name. The
following example makes modeline an alias for the mode-line face.
(put ’modeline ’face-alias ’mode-line)
fontification-functions [Variable]
This variable holds a list of functions that are called by Emacs redisplay as needed
to assign faces automatically to text in the buffer.
The functions are called in the order listed, with one argument, a buffer position pos.
Each function should attempt to assign faces to the text in the current buffer starting
at pos.
Each function should record the faces they assign by setting the face property. It
should also add a non-nil fontified property for all the text it has assigned faces
to. That property tells redisplay that faces have been assigned to that text already.
It is probably a good idea for each function to do nothing if the character after pos
already has a non-nil fontified property, but this is not required. If one function
overrides the assignments made by a previous one, the properties as they are after
the last function finishes are the ones that really matter.
For efficiency, we recommend writing these functions so that they usually assign faces
to around 400 to 600 characters at each call.
The optional argument maximum sets a limit on how many fonts to return. If this is
non-nil, then the return value is truncated after the first maximum matching fonts.
Specifying a small value for maximum can make this function much faster, in cases
where many fonts match the pattern.
font-list-limit [Variable]
This variable specifies maximum number of fonts to consider in font matching. The
function x-family-fonts will not return more than that many fonts, and font se-
lection will consider only that many fonts when searching a matching font for face
attributes. The default is currently 100.
38.12.9 Fontsets
A fontset is a list of fonts, each assigned to a range of character codes. An individual
font cannot display the whole range of characters that Emacs supports, but a fontset can.
Fontsets have names, just as fonts do, and you can use a fontset name in place of a font
name when you specify the “font” for a frame or a face. Here is information about defining
a fontset under Lisp program control.
Chapter 38: Emacs Display 775
The construct ‘charset :font ’ specifies which font to use (in this fontset) for one par-
ticular character set. Here, charset is the name of a character set, and font is the font to use
for that character set. You can use this construct any number of times in the specification
string.
For the remaining character sets, those that you don’t specify explicitly, Emacs chooses
a font based on fontpattern: it replaces ‘fontset-alias ’ with a value that names one
character set. For the ASCII character set, ‘fontset-alias ’ is replaced with ‘ISO8859-1’.
In addition, when several consecutive fields are wildcards, Emacs collapses them into a
single wildcard. This is to prevent use of auto-scaled fonts. Fonts made by scaling larger
fonts are not usable for editing, and scaling a smaller font is not useful because it is better
to use the smaller font in its own size, which Emacs does.
Thus if fontpattern is this,
-*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24
the font specification for ASCII characters would be this:
-*-fixed-medium-r-normal-*-24-*-ISO8859-1
and the font specification for Chinese GB2312 characters would be this:
-*-fixed-medium-r-normal-*-24-*-gb2312*-*
You may not have any Chinese font matching the above font specification. Most X
distributions include only Chinese fonts that have ‘song ti’ or ‘fangsong ti’ in the family
field. In such a case, ‘Fontset-n ’ can be specified as below:
Emacs.Fontset-0: -*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24,\
chinese-gb2312:-*-*-medium-r-normal-*-24-*-gb2312*-*
Then, the font specifications for all but Chinese GB2312 characters have ‘fixed’ in the
family field, and the font specification for Chinese GB2312 characters has a wild card ‘*’
in the family field.
Chapter 38: Emacs Display 776
38.13 Fringes
The fringes of a window are thin vertical strips down the sides that are used for displaying
bitmaps that indicate truncation, continuation, horizontal scrolling, and the overlay arrow.
fringes-outside-margins [Variable]
The fringes normally appear between the display margins and the window text. If
the value is non-nil, they appear outside the display margins. See Section 38.15.4
[Display Margins], page 786.
left-fringe-width [Variable]
This variable, if non-nil, specifies the width of the left fringe in pixels. A value of
nil means to use the left fringe width from the window’s frame.
right-fringe-width [Variable]
This variable, if non-nil, specifies the width of the right fringe in pixels. A value of
nil means to use the right fringe width from the window’s frame.
The values of these variables take effect when you display the buffer in a window. If you
change them while the buffer is visible, you can call set-window-buffer to display it once
again in the same window, to make the changes take effect.
Chapter 38: Emacs Display 777
indicate-buffer-boundaries [Variable]
This buffer-local variable controls how the buffer boundaries and window scrolling are
indicated in the window fringes.
Emacs can indicate the buffer boundaries—that is, the first and last line in the
buffer—with angle icons when they appear on the screen. In addition, Emacs can
display an up-arrow in the fringe to show that there is text above the screen, and a
down-arrow to show there is text below the screen.
There are three kinds of basic values:
nil Don’t display any of these fringe icons.
left Display the angle icons and arrows in the left fringe.
right Display the angle icons and arrows in the right fringe.
any non-alist
Display the angle icons in the left fringe and don’t display the arrows.
Otherwise the value should be an alist that specifies which fringe indicators to display
and where. Each element of the alist should have the form (indicator . position ).
Here, indicator is one of top, bottom, up, down, and t (which covers all the icons not
yet specified), while position is one of left, right and nil.
For example, ((top . left) (t . right)) places the top angle bitmap in left fringe,
and the bottom angle bitmap as well as both arrow bitmaps in right fringe. To
show the angle bitmaps in the left fringe, and no arrow bitmaps, use ((top . left)
(bottom . left)).
Chapter 38: Emacs Display 778
default-indicate-buffer-boundaries [Variable]
The value of this variable is the default value for indicate-buffer-boundaries in
buffers that do not override it.
fringe-indicator-alist [Variable]
This buffer-local variable specifies the mapping from logical fringe indicators to the
actual bitmaps displayed in the window fringes.
These symbols identify the logical fringe indicators:
Truncation and continuation line indicators:
truncation, continuation.
Buffer position indicators:
up, down, top, bottom, top-bottom.
Empty line indicator:
empty-line.
Overlay arrow indicator:
overlay-arrow.
Unknown bitmap indicator:
unknown.
The value is an alist where each element (indicator . bitmaps ) specifies the fringe
bitmaps used to display a specific logical fringe indicator.
Here, indicator specifies the logical indicator type, and bitmaps is list of symbols
(left right [left1 right1 ]) which specifies the actual bitmap shown in the left
or right fringe for the logical indicator.
The left and right symbols specify the bitmaps shown in the left and/or right fringe for
the specific indicator. The left1 or right1 bitmaps are used only for the ‘bottom’ and
‘top-bottom indicators when the last (only) line in has no final newline. Alternatively,
bitmaps may be a single symbol which is used in both left and right fringes.
When fringe-indicator-alist has a buffer-local value, and there is no bitmap
defined for a logical indicator, or the bitmap is t, the corresponding value from the
(non-local) default-fringe-indicator-alist is used.
To completely hide a specific indicator, set the bitmap to nil.
default-fringe-indicator-alist [Variable]
The value of this variable is the default value for fringe-indicator-alist in buffers
that do not override it.
filled-square hollow-square
vertical-bar horizontal-bar
empty-line question-mark
overflow-newline-into-fringe [Variable]
If this is non-nil, lines exactly as wide as the window (not counting the final newline
character) are not continued. Instead, when point is at the end of the line, the cursor
appears in the right fringe.
fringe-cursor-alist [Variable]
This variable specifies the mapping from logical cursor type to the actual fringe bit-
maps displayed in the right fringe. The value is an alist where each element (cursor
. bitmap ) specifies the fringe bitmaps used to display a specific logical cursor type
in the fringe. Here, cursor specifies the logical cursor type and bitmap is a symbol
specifying the fringe bitmap to be displayed for that logical cursor type.
When fringe-cursor-alist has a buffer-local value, and there is no bitmap defined
for a cursor type, the corresponding value from the (non-local) default-fringes-
indicator-alist is used.
default-fringes-cursor-alist [Variable]
The value of this variable is the default value for fringe-cursor-alist in buffers
that do not override it.
should be used for displaying the bitmap, instead of the default fringe face. face is auto-
matically merged with the fringe face, so normally face need only specify the foreground
color for the bitmap.
fringe-bitmaps-at-pos &optional pos window [Function]
This function returns the fringe bitmaps of the display line containing position pos in
window window. The return value has the form (left right ov ), where left is the
symbol for the fringe bitmap in the left fringe (or nil if no bitmap), right is similar
for the right fringe, and ov is non-nil if there is an overlay arrow in the left fringe.
The value is nil if pos is not visible in window. If window is nil, that stands for the
selected window. If pos is nil, that stands for the value of point in window.
overlay-arrow-string [Variable]
This variable holds the string to display to call attention to a particular line, or nil
if the arrow feature is not in use. On a graphical display the contents of the string
are ignored; instead a glyph is displayed in the fringe area to the left of the display
area.
overlay-arrow-position [Variable]
This variable holds a marker that indicates where to display the overlay arrow. It
should point at the beginning of a line. On a non-graphical display the arrow text
appears at the beginning of that line, overlaying any text that would otherwise appear.
Since the arrow is usually short, and the line usually begins with indentation, normally
nothing significant is overwritten.
The overlay-arrow string is displayed in any given buffer if the value of overlay-
arrow-position in that buffer points into that buffer. Thus, it works to can display
multiple overlay arrow strings by creating buffer-local bindings of overlay-arrow-
position. However, it is usually cleaner to use overlay-arrow-variable-list to
achieve this result.
You can do a similar job by creating an overlay with a before-string property. See
Section 38.9.2 [Overlay Properties], page 756.
You can define multiple overlay arrows via the variable overlay-arrow-variable-list.
overlay-arrow-variable-list [Variable]
This variable’s value is a list of variables, each of which specifies the position of
an overlay arrow. The variable overlay-arrow-position has its normal meaning
because it is on this list.
Each variable on this list can have properties overlay-arrow-string and overlay-
arrow-bitmap that specify an overlay arrow string (for text-only terminals) or fringe bitmap
(for graphical terminals) to display at the corresponding overlay arrow position. If either
property is not set, the default overlay-arrow-string or overlay-arrow fringe indicator
is used.
You can enable or disable scroll bars for a particular buffer, by setting the variable
vertical-scroll-bar. This variable automatically becomes buffer-local when set. The
Chapter 38: Emacs Display 782
possible values are left, right, t, which means to use the frame’s default, and nil for no
scroll bar.
You can also control this for individual windows. Call the function set-window-scroll-
bars to specify what to do for a specific window:
If you don’t specify these values for a window with set-window-scroll-bars, the buffer-
local variables scroll-bar-mode and scroll-bar-width in the buffer being displayed con-
trol the window’s vertical scroll bars. The function set-window-buffer examines these
variables. If you change them in a buffer that is already visible in a window, you can make
the window take note of the new values by calling set-window-buffer specifying the same
buffer that is already displayed.
scroll-bar-mode [Variable]
This variable, always local in all buffers, controls whether and where to put scroll
bars in windows displaying the buffer. The possible values are nil for no scroll bar,
left to put a scroll bar on the left, and right to put a scroll bar on the right.
scroll-bar-width [Variable]
This variable, always local in all buffers, specifies the width of the buffer’s scroll bars,
measured in pixels. A value of nil means to use the value specified by the frame.
Chapter 38: Emacs Display 783
It gives each of the first ten characters in the buffer string "A" as the display property,
but they don’t all get the same string. The first two characters get the same string, so they
together are replaced with one ‘A’. The next two characters get a second string, so they
together are replaced with one ‘A’. Likewise for each following pair of characters. Thus, the
ten characters appear as five A’s. This function would have the same results:
(defun foo ()
(goto-char (point-min))
(dotimes (i 5)
(let ((string (concat "A")))
(put-text-property (point) (2+ (point)) ’display string)
(put-text-property (point) (1+ (point)) ’display string)
(forward-char 2))))
This illustrates that what matters is the property value for each character. If two consecutive
characters have the same object as the display property value, it’s irrelevant whether they
got this property from a single call to put-text-property or from two different calls.
The rest of this section describes several kinds of display specifications and what they
mean.
:width width
If width is an integer or floating point number, it specifies that the space width
should be width times the normal character width. width can also be a pixel
width specification (see Section 38.15.2 [Pixel Specification], page 784).
Chapter 38: Emacs Display 784
:relative-width factor
Specifies that the width of the stretch should be computed from the first charac-
ter in the group of consecutive characters that have the same display property.
The space width is the width of that character, multiplied by factor.
:align-to hpos
Specifies that the space should be wide enough to reach hpos. If hpos is a
number, it is measured in units of the normal character width. hpos can also be
a pixel width specification (see Section 38.15.2 [Pixel Specification], page 784).
You should use one and only one of the above properties. You can also specify the height
of the space, with these properties:
:height height
Specifies the height of the space. If height is an integer or floating point number,
it specifies that the space height should be height times the normal character
height. The height may also be a pixel height specification (see Section 38.15.2
[Pixel Specification], page 784).
:relative-height factor
Specifies the height of the space, multiplying the ordinary height of the text
having this display specification by factor.
:ascent ascent
If the value of ascent is a non-negative number no greater than 100, it specifies
that ascent percent of the height of the space should be considered as the
ascent of the space—that is, the part above the baseline. The ascent may also
be specified in pixel units with a pixel ascent specification (see Section 38.15.2
[Pixel Specification], page 784).
Don’t use both :height and :relative-height together.
The :width and :align-to properties are supported on non-graphic terminals, but the
other space properties in this section are not.
The in, mm, and cm units specify the number of pixels per inch, millimeter, and centime-
ter, respectively. The width and height units correspond to the default width and height
of the current face. An image specification image corresponds to the width or height of the
image.
The left-fringe, right-fringe, left-margin, right-margin, scroll-bar, and text
elements specify to the width of the corresponding area of the window.
The left, center, and right positions can be used with :align-to to specify a position
relative to the left edge, center, or right edge of the text area.
Any of the above window elements (except text) can also be used with :align-to to
specify that the position is relative to the left edge of the given area. Once the base offset
for a relative position has been set (by the first occurrence of one of these symbols), further
occurrences of these symbols are interpreted as the width of the specified area. For example,
to align to the center of the left-margin, use
:align-to (+ left-margin (0.5 . left-margin))
If no specific base offset is set for alignment, it is always relative to the left edge of the
text area. For example, ‘:align-to 0’ in a header-line aligns with the first text column in
the text area.
A value of the form (num . expr ) stands for the product of the values of num and expr.
For example, (2 . in) specifies a width of 2 inches, while (0.5 . image ) specifies half the
width (or height) of the specified image.
The form (+ expr ...) adds up the value of the expressions. The form (- expr ...)
negates or subtracts the value of the expressions.
(space-width factor )
This display specification affects all the space characters within the text that has
the specification. It displays all of these spaces factor times as wide as normal.
The element factor should be an integer or float. Characters other than spaces
are not affected at all; in particular, this has no effect on tab characters.
(height height )
This display specification makes the text taller or shorter. Here are the possi-
bilities for height:
(+ n ) This means to use a font that is n steps larger. A “step” is defined
by the set of available fonts—specifically, those that match what
was otherwise specified for this text, in all attributes except height.
Each size for which a suitable font is available counts as another
step. n should be an integer.
(- n ) This means to use a font that is n steps smaller.
a number, factor
A number, factor, means to use a font that is factor times as tall
as the default font.
a symbol, function
A symbol is a function to compute the height. It is called with the
current height as argument, and should return the new height to
use.
anything else, form
If the height value doesn’t fit the previous possibilities, it is a form.
Emacs evaluates it to get the new height, with the symbol height
bound to the current specified font height.
(raise factor )
This kind of display specification raises or lowers the text it applies to, relative
to the baseline of the line.
factor must be a number, which is interpreted as a multiple of the height of the
affected text. If it is positive, that means to display the characters raised. If it
is negative, that means to display them lower down.
If the text also has a height display specification, that does not affect the
amount of raising or lowering, which is based on the faces used for the text.
You can make any display specification conditional. To do that, package it in another
list of the form (when condition . spec ). Then the specification spec applies only when
condition evaluates to a non-nil value. During the evaluation, object is bound to the string
or buffer having the conditional display property. position and buffer-position are
bound to the position within object and the buffer position where the display property
was found, respectively. Both positions can be different when object is a string.
To put text in the left or right display margin of the window, use a display specification
of the form (margin right-margin) or (margin left-margin) on it. To put an image
in a display margin, use that display specification along with the display specification for
the image. Unfortunately, there is currently no way to make text or images in the margin
mouse-sensitive.
If you put such a display specification directly on text in the buffer, the specified margin
display appears instead of that buffer text itself. To put something in the margin in
association with certain buffer text without preventing or altering the display of that text,
put a before-string property on the text and put the display specification on the contents
of the before-string.
Before the display margins can display anything, you must give them a nonzero width.
The usual way to do that is to set these variables:
left-margin-width [Variable]
This variable specifies the width of the left margin. It is buffer-local in all buffers.
right-margin-width [Variable]
This variable specifies the width of the right margin. It is buffer-local in all buffers.
Setting these variables does not immediately affect the window. These variables are
checked when a new buffer is displayed in the window. Thus, you can make changes take
effect by calling set-window-buffer.
You can also set the margin widths immediately.
38.16 Images
To display an image in an Emacs buffer, you must first create an image descriptor, then use
it as a display specifier in the display property of text that is displayed (see Section 38.15
[Display Property], page 783).
Emacs is usually able to display images when it is run on a graphical terminal. Images
cannot be displayed in a text terminal, on certain graphical terminals that lack the support
for this, or if Emacs is compiled without image support. You can use the function display-
images-p to determine if images can in principle be displayed (see Section 29.23 [Display
Feature Testing], page 555).
Emacs can display a number of different image formats; some of them are supported only
if particular support libraries are installed on your machine. In some environments, Emacs
can load image libraries on demand; if so, the variable image-library-alist can be used
to modify the set of known names for these dynamic libraries (though it is not possible to
add new image formats).
Chapter 38: Emacs Display 788
The supported image formats include XBM, XPM (this requires the libraries libXpm
version 3.4k and libz), GIF (requiring libungif 4.1.0), PostScript, PBM, JPEG (requiring
the libjpeg library version v6a), TIFF (requiring libtiff v3.4), and PNG (requiring
libpng 1.0.2).
You specify one of these formats with an image type symbol. The image type symbols
are xbm, xpm, gif, postscript, pbm, jpeg, tiff, and png.
image-types [Variable]
This variable contains a list of those image type symbols that are potentially sup-
ported in the current configuration. Potentially here means that Emacs knows about
the image types, not necessarily that they can be loaded (they could depend on un-
available dynamic libraries, for example).
To know which image types are really available, use image-type-available-p.
image-library-alist [Variable]
This in an alist of image types vs external libraries needed to display them.
Each element is a list (image-type library...), where the car is a supported image
format from image-types, and the rest are strings giving alternate filenames for the
corresponding external libraries to load.
Emacs tries to load the libraries in the order they appear on the list; if none is loaded,
the running session of Emacs won’t support the image type. pbm and xbm don’t need
to be listed; they’re always supported.
This variable is ignored if the image libraries are statically linked into Emacs.
:data data
The :data property says the actual contents of the image. Each image must
use either :data or :file, but not both. For most image types, the value of the
:data property should be a string containing the image data; we recommend
using a unibyte string.
Before using :data, look for further information in the section below describing
the specific image format. For some image types, :data may not be supported;
for some, it allows other data types; for some, :data alone is not enough, so
you need to use other image properties along with :data.
:margin margin
The :margin property specifies how many pixels to add as an extra margin
around the image. The value, margin, must be a non-negative number, or a
pair (x . y ) of such numbers. If it is a pair, x specifies how many pixels to
add horizontally, and y specifies how many pixels to add vertically. If :margin
is not specified, the default is zero.
:ascent ascent
The :ascent property specifies the amount of the image’s height to use for
its ascent—that is, the part above the baseline. The value, ascent, must be a
number in the range 0 to 100, or the symbol center.
If ascent is a number, that percentage of the image’s height is used for its ascent.
If ascent is center, the image is vertically centered around a centerline which
would be the vertical centerline of text drawn at the position of the image,
in the manner specified by the text properties and overlays that apply to the
image.
If this property is omitted, it defaults to 50.
:relief relief
The :relief property, if non-nil, adds a shadow rectangle around the image.
The value, relief, specifies the width of the shadow lines, in pixels. If relief is
negative, shadows are drawn so that the image appears as a pressed button;
otherwise, it appears as an unpressed button.
:conversion algorithm
The :conversion property, if non-nil, specifies a conversion algorithm that
should be applied to the image before it is displayed; the value, algorithm,
specifies which algorithm.
laplace
emboss Specifies the Laplace edge detection algorithm, which blurs out
small differences in color while highlighting larger differences. Peo-
ple sometimes consider this useful for displaying the image for a
“disabled” button.
(edge-detection :matrix matrix :color-adjust adjust )
Specifies a general edge-detection algorithm. matrix must be either
a nine-element list or a nine-element vector of numbers. A pixel at
position x/y in the transformed image is computed from original
Chapter 38: Emacs Display 790
pixels around that position. matrix specifies, for each pixel in the
neighborhood of x/y, a factor with which that pixel will influence
the transformed pixel; element 0 specifies the factor for the pixel
at x − 1/y − 1, element 1 the factor for the pixel at x/y − 1 etc., as
shown below:
x − 1/y − 1 x/y − 1 x + 1/y − 1
x − 1/y x/y x + 1/y
x − 1/y + 1 x/y + 1 x + 1/y + 1
The resulting pixel is computed from the color intensity of the color
resulting from summing up the RGB values of surrounding pixels,
multiplied by the specified factors, and dividing that sum by the
sum of the factors’ absolute values.
Laplace edge-detection currently uses a matrix of
1 0 0
0 0 0
9 9 −1
2 −1 0
−1 0 1
0 1 −2
both to indicate that the string contains just the bits rather than a whole
XBM file, and to specify the size of the image.
:width width
The value, width, specifies the width of the image, in pixels.
:height height
The value, height, specifies the height of the image, in pixels.
:foreground foreground
The value, foreground, should be a string specifying the image foreground color,
or nil for the default color. This color is used for each pixel in the XBM that
is 1. The default is the frame’s foreground color.
:background background
The value, background, should be a string specifying the image background
color, or nil for the default color. This color is used for each pixel in the XBM
that is 0. The default is the frame’s background color.
For JPEG images, specify image type jpeg.
For TIFF images, specify image type tiff.
For PNG images, specify image type png.
image-load-path [Variable]
This variable’s value is a list of locations in which to search for image files. If an
element is a string or a variable symbol whose value is a string, the string is taken to
be the name of a directory to search. If an element is a variable symbol whose value
is a list, that is taken to be a list of directory names to search.
The default is to search in the ‘images’ subdirectory of the directory specified by
data-directory, then the directory specified by data-directory, and finally in the
directories in load-path. Subdirectories are not automatically included in the search,
so if you put an image file in a subdirectory, you have to supply the subdirectory
name explicitly. For example, to find the image ‘images/foo/bar.xpm’ within data-
directory, you should specify the image as follows:
(defimage foo-image ’((:type xpm :file "foo/bar.xpm")))
image-load-path))))
(mh-tool-bar-folder-buttons-init))
max-image-size [Variable]
This variable is used to define the maximum size of image that Emacs will load.
Emacs will refuse to load (and display) any image that is larger than this limit.
If the value is an integer, it directly specifies the maximum image height and width,
measured in pixels. If it is a floating point number, it specifies the maximum image
height and width as a ratio to the frame height and width. If the value is non-numeric,
there is no explicit limit on the size of images.
The purpose of this variable is to prevent unreasonably large images from accidentally
being loaded into Emacs. It only takes effect the first time an image is loaded. Once
an image is placed in the image cache, it can always be displayed, even if the value of
max-image-size is subsequently changed (see Section 38.16.9 [Image Cache], page 796).
image-cache-eviction-delay [Variable]
This variable specifies the number of seconds an image can remain in the cache without
being displayed. When an image is not displayed for this length of time, Emacs
removes it from the image cache.
If the value is nil, Emacs does not remove images from the cache except when you
explicitly clear it. This mode can be useful for debugging.
38.17 Buttons
The button package defines functions for inserting and manipulating clickable (with the
mouse, or via keyboard commands) buttons in Emacs buffers, such as might be used for
help hyper-links, etc. Emacs uses buttons for the hyper-links in help text and the like.
A button is essentially a set of properties attached (via text properties or overlays) to a
region of text in an Emacs buffer. These properties are called button properties.
Chapter 38: Emacs Display 797
One of these properties (action) is a function, which will be called when the user invokes
it using the keyboard or the mouse. The invoked function may then examine the button
and use its other properties as desired.
In some ways the Emacs button package duplicates functionality offered by the widget
package (see section “Introduction” in The Emacs Widget Library), but the button package
has the advantage that it is much faster, much smaller, and much simpler to use (for elisp
programmers—for users, the result is about the same). The extra speed and space savings
are useful mainly if you need to create many buttons in a buffer (for instance an *Apropos*
buffer uses buttons to make entries clickable, and may contain many thousands of entries).
An ewoc is a structure that organizes information required to construct buffer text that
represents certain Lisp data. The buffer text of the ewoc has three parts, in order: first,
fixed header text; next, textual descriptions of a series of data elements (Lisp objects that
you specify); and last, fixed footer text. Specifically, an ewoc contains information on:
• The buffer which its text is generated in.
• The text’s start position in the buffer.
• The header and footer strings.
• A doubly-linked chain of nodes, each of which contains:
• A data element, a single Lisp object.
• Links to the preceding and following nodes in the chain.
• A pretty-printer function which is responsible for inserting the textual representation
of a data element value into the current buffer.
Typically, you define an ewoc with ewoc-create, and then pass the resulting ewoc
structure to other functions in the Ewoc package to build nodes within it, and display it in
the buffer. Once it is displayed in the buffer, other functions determine the correspondance
between buffer positions and nodes, move point from one node’s textual representation to
another, and so forth. See Section 38.18.1 [Abstract Display Functions], page 801.
A node encapsulates a data element much the way a variable holds a value. Normally,
encapsulation occurs as a part of adding a node to the ewoc. You can retrieve the data
element value and place a new value in its place, like so:
(ewoc-data node )
⇒ value
Normally, a newline is automatically inserted after the header, the footer and every
node’s textual description. If nosep is non-nil, no newline is inserted. This may be
useful for displaying an entire ewoc on a single line, for example, or for making nodes
“invisible” by arranging for pretty-printer to do nothing for those nodes.
An ewoc maintains its text in the buffer that is current when you create it, so switch
to the intended buffer before calling ewoc-create.
(ewoc-invalidate
colorcomp-ewoc
(ewoc-nth colorcomp-ewoc index)
(ewoc-nth colorcomp-ewoc -1))))
(defun colorcomp-copy-as-kill-and-exit ()
"Copy the color components into the kill ring and kill the buffer.
The string is formatted #RRGGBB (hash followed by six hex digits)."
(interactive)
(kill-new (format "#%02X%02X%02X"
(aref colorcomp-data 0)
(aref colorcomp-data 1)
(aref colorcomp-data 2)))
(kill-buffer nil))
(setq colorcomp-mode-map
(let ((m (make-sparse-keymap)))
(suppress-keymap m)
(define-key m "i" ’colorcomp-R-less)
(define-key m "o" ’colorcomp-R-more)
(define-key m "k" ’colorcomp-G-less)
(define-key m "l" ’colorcomp-G-more)
(define-key m "," ’colorcomp-B-less)
(define-key m "." ’colorcomp-B-more)
(define-key m " " ’colorcomp-copy-as-kill-and-exit)
m))
Note that we never modify the data in each node, which is fixed when the ewoc is created
to be either nil or an index into the vector colorcomp-data, the actual color components.
blink-paren-function [Variable]
The value of this variable should be a function (of no arguments) to be called whenever
a character with close parenthesis syntax is inserted. The value of blink-paren-
function may be nil, in which case nothing is done.
These display rules apply to carriage return (character code 13), when it appears in
the buffer. But that character may not appear in the buffer where you expect it, if it was
eliminated as part of end-of-line conversion (see Section 33.10.1 [Coding System Basics],
page 648).
These variables affect the way certain characters are displayed on the screen. Since
they change the number of columns the characters occupy, they also affect the indentation
functions. These variables also affect how the mode line is displayed; if you want to force
redisplay of the mode line using the new values, call the function force-mode-line-update
(see Section 23.4 [Mode Line Format], page 402).
default-ctl-arrow [Variable]
The value of this variable is the default value for ctl-arrow in buffers that do not
override it. See Section 11.10.3 [Default Value], page 152.
make-display-table [Function]
This creates and returns a display table. The table initially has nil in all elements.
The ordinary elements of the display table are indexed by character codes; the element
at index c says how to display the character code c. The value should be nil or a vector
of the glyphs to be output (see Section 38.21.3 [Glyphs], page 809). nil says to display the
Chapter 38: Emacs Display 808
character c according to the usual display conventions (see Section 38.20 [Usual Display],
page 806).
Warning: if you use the display table to change the display of newline characters, the
whole buffer will be displayed as one long “line.”
The display table also has six “extra slots” which serve special purposes. Here is a table
of their meanings; nil in any slot means to use the default for that slot, as stated below.
0 The glyph for the end of a truncated screen line (the default for this is ‘$’). See
Section 38.21.3 [Glyphs], page 809. On graphical terminals, Emacs uses arrows
in the fringes to indicate truncation, so the display table has no effect.
1 The glyph for the end of a continued line (the default is ‘\’). On graphical
terminals, Emacs uses curved arrows in the fringes to indicate continuation, so
the display table has no effect.
2 The glyph for indicating a character displayed as an octal character code (the
default is ‘\’).
3 The glyph for indicating a control character (the default is ‘^’).
4 A vector of glyphs for indicating the presence of invisible lines (the default is
‘...’). See Section 38.7 [Selective Display], page 750.
5 The glyph used to draw the border between side-by-side windows (the default
is ‘|’). See Section 28.2 [Splitting Windows], page 498. This takes effect only
when there are no scroll bars; if scroll bars are supported and in use, a scroll
bar separates the two windows.
For example, here is how to construct a display table that mimics the effect of setting
ctl-arrow to a non-nil value:
(setq disptab (make-display-table))
(let ((i 0))
(while (< i 32)
(or (= i ?\t) (= i ?\n)
(aset disptab i (vector ?^ (+ i 64))))
(setq i (1+ i)))
(aset disptab 127 (vector ?^ ??)))
display-table-slot display-table slot [Function]
This function returns the value of the extra slot slot of display-table. The argument
slot may be a number from 0 to 5 inclusive, or a slot name (symbol). Valid symbols are
truncation, wrap, escape, control, selective-display, and vertical-border.
set-display-table-slot display-table slot value [Function]
This function stores value in the extra slot slot of display-table. The argument slot
may be a number from 0 to 5 inclusive, or a slot name (symbol). Valid symbols are
truncation, wrap, escape, control, selective-display, and vertical-border.
describe-display-table display-table [Function]
This function displays a description of the display table display-table in a help buffer.
describe-current-display-table [Command]
This command displays a description of the current display table in a help buffer.
Chapter 38: Emacs Display 809
38.21.3 Glyphs
A glyph is a generalization of a character; it stands for an image that takes up a single
character position on the screen. Normally glyphs come from vectors in the display table
(see Section 38.21 [Display Tables], page 807).
A glyph is represented in Lisp as a glyph code. A glyph code can be simple or it can be
defined by the glyph table. A simple glyph code is just a way of specifying a character and
a face to output it in. See Section 38.12 [Faces], page 762.
The following functions are used to manipulate simple glyph codes:
make-glyph-code char &optional face [Function]
This function returns a simple glyph code representing char char with face face.
glyph-char glyph [Function]
This function returns the character of simple glyph code glyph.
glyph-face glyph [Function]
This function returns face of simple glyph code glyph, or nil if glyph has the default
face (face-id 0).
Chapter 38: Emacs Display 810
On character terminals, you can set up a glyph table to define the meaning of glyph
codes (represented as small integers).
glyph-table [Variable]
The value of this variable is the current glyph table. It should be nil or a vector
whose gth element defines glyph code g.
If a glyph code is greater than or equal to the length of the glyph table, that code is
automatically simple. If glyph-table is nil then all glyph codes are simple.
The glyph table is used only on character terminals. On graphical displays, all glyph
codes are simple.
38.22 Beeping
This section describes how to make Emacs ring the bell (or blink the screen) to attract
the user’s attention. Be conservative about how often you do this; frequent bells can
become irritating. Also be careful not to use just beeping when signaling an error is more
appropriate. (See Section 10.5.3 [Errors], page 127.)
ring-bell-function [Variable]
If this is non-nil, it specifies how Emacs should “ring the bell.” Its value should be
a function of no arguments. If this is non-nil, it takes precedence over the visible-
bell variable.
Chapter 38: Emacs Display 811
window-system [Variable]
This variable tells Lisp programs what window system Emacs is running under. The
possible values are
x Emacs is displaying using X.
pc Emacs is displaying using MS-DOS.
w32 Emacs is displaying using Windows.
mac Emacs is displaying using a Macintosh.
nil Emacs is using a character-based terminal.
window-setup-hook [Variable]
This variable is a normal hook which Emacs runs after handling the initialization
files. Emacs runs this hook after it has completed loading your init file, the default
initialization file (if any), and the terminal-specific Lisp code, and running the hook
term-setup-hook.
This hook is used for internal purposes: setting up communication with the window
system, and creating the initial window. Users should not interfere with it.
Chapter 39: Operating System Interface 812
own personal init file, if any, is loaded first; if it sets inhibit-default-init to a non-nil
value, then Emacs does not subsequently load the ‘default.el’ file.
Another file for site-customization is ‘site-start.el’. Emacs loads this before the user’s
init file. You can inhibit the loading of this file with the option ‘--no-site-file’.
site-run-file [Variable]
This variable specifies the site-customization file to load before the user’s init file. Its
normal value is "site-start". The only way you can change it with real effect is to
do so before dumping Emacs.
See section “Init File Examples” in The GNU Emacs Manual, for examples of how to
make various commonly desired customizations in your ‘.emacs’ file.
before-init-hook [Variable]
This normal hook is run, once, just before loading all the init files (the user’s init file,
‘default.el’, and/or ‘site-start.el’). (The only way to change it with real effect
is before dumping Emacs.)
after-init-hook [Variable]
This normal hook is run, once, just after loading all the init files (the user’s init file,
‘default.el’, and/or ‘site-start.el’), before loading the terminal-specific library
and processing the command-line action arguments.
emacs-startup-hook [Variable]
This normal hook is run, once, just after handling the command line arguments, just
before term-setup-hook.
user-init-file [Variable]
This variable holds the absolute file name of the user’s init file. If the actual init file
loaded is a compiled file, such as ‘.emacs.elc’, the value refers to the corresponding
source file.
When the name of the terminal type contains a hyphen, and no library is found whose
name is identical to the terminal’s name, Emacs strips from the terminal’s name the last
hyphen and everything that follows it, and tries again. This process is repeated until Emacs
finds a matching library or until there are no more hyphens in the name (the latter means
the terminal doesn’t have any library specific to it). Thus, for example, if there are no
‘aaa-48’ and ‘aaa-30’ libraries, Emacs will try the same library ‘term/aaa.el’ for terminal
types ‘aaa-48’ and ‘aaa-30-rv’. If necessary, the library can evaluate (getenv "TERM") to
find the full name of the terminal type.
Your init file can prevent the loading of the terminal-specific library by setting the
variable term-file-prefix to nil. This feature is useful when experimenting with your
own peculiar customizations.
You can also arrange to override some of the actions of the terminal-specific library by
setting the variable term-setup-hook. This is a normal hook which Emacs runs using
run-hooks at the end of Emacs initialization, after loading both your init file and any
terminal-specific libraries. You can use this variable to define initializations for terminals
that do not have their own libraries. See Section 23.1 [Hooks], page 382.
term-file-prefix [Variable]
If the term-file-prefix variable is non-nil, Emacs loads a terminal-specific initial-
ization file as follows:
(load (concat term-file-prefix (getenv "TERM")))
You may set the term-file-prefix variable to nil in your init file if you do not
wish to load the terminal-initialization file. To do this, put the following in your init
file: (setq term-file-prefix nil).
On MS-DOS, if the environment variable TERM is not set, Emacs uses ‘internal’ as
the terminal type.
term-setup-hook [Variable]
This variable is a normal hook that Emacs runs after loading your init file, the default
initialization file (if any) and the terminal-specific Lisp file.
You can use term-setup-hook to override the definitions made by a terminal-specific
file.
See window-setup-hook in Section 38.23 [Window Systems], page 811, for a related
feature.
command-line [Function]
This function parses the command line that Emacs was called with, processes it, loads
the user’s init file and displays the startup messages.
command-line-processed [Variable]
The value of this variable is t once the command line has been processed.
If you redump Emacs by calling dump-emacs, you may wish to set this variable to
nil first in order to cause the new dumped Emacs to process its new command-line
arguments.
command-switch-alist [Variable]
The value of this variable is an alist of user-defined command-line options and asso-
ciated handler functions. This variable exists so you can add elements to it.
A command-line option is an argument on the command line, which has the form:
-option
The elements of the command-switch-alist look like this:
(option . handler-function )
The car, option, is a string, the name of a command-line option (not including the
initial hyphen). The handler-function is called to handle option, and receives the
option name as its sole argument.
In some cases, the option is followed in the command line by an argument. In these
cases, the handler-function can find all the remaining command-line arguments in the
variable command-line-args-left. (The entire list of command-line arguments is in
command-line-args.)
The command-line arguments are parsed by the command-line-1 function in the
‘startup.el’ file. See also section “Command Line Arguments for Emacs Invocation”
in The GNU Emacs Manual.
command-line-args [Variable]
The value of this variable is the list of command-line arguments passed to Emacs.
command-line-functions [Variable]
This variable’s value is a list of functions for handling an unrecognized command-line
argument. Each time the next argument to be processed has no special meaning, the
functions in this list are called, in order of appearance, until one of them returns a
non-nil value.
These functions are called with no arguments. They can access the command-line
argument under consideration through the variable argi, which is bound temporarily
at this point. The remaining arguments (not including the current one) are in the
variable command-line-args-left.
When a function recognizes and processes the argument in argi, it should return a
non-nil value to say it has dealt with that argument. If it has also dealt with some of
the following arguments, it can indicate that by deleting them from command-line-
args-left.
If all of these functions return nil, then the argument is used as a file name to visit.
Chapter 39: Operating System Interface 817
All the information in the Emacs process, aside from files that have been saved, is lost
when the Emacs process is killed. Because killing Emacs inadvertently can lose a lot of
work, Emacs queries for confirmation before actually terminating if you have buffers that
need saving or subprocesses that are running. This is done in the function save-buffers-
kill-emacs, the higher level function from which kill-emacs is usually called.
kill-emacs-query-functions [Variable]
After asking the standard questions, save-buffers-kill-emacs calls the functions
in the list kill-emacs-query-functions, in order of appearance, with no arguments.
These functions can ask for additional confirmation from the user. If any of them
returns nil, save-buffers-kill-emacs does not kill Emacs, and does not run the
remaining functions in this hook. Calling kill-emacs directly does not run this hook.
kill-emacs-hook [Variable]
This variable is a normal hook; once save-buffers-kill-emacs is finished with all
file saving and confirmation, it calls kill-emacs which runs the functions in this
hook. kill-emacs does not run this hook in batch mode.
kill-emacs may be invoked directly (that is not via save-buffers-kill-emacs) if
the terminal is disconnected, or in similar situations where interaction with the user
is not possible. Thus, if your hook needs to interact with the user, put it on kill-
emacs-query-functions; if it needs to run regardless of how Emacs is killed, put it
on kill-emacs-hook.
Some operating systems do not support suspension of jobs; on these systems, “suspen-
sion” actually creates a new shell temporarily as a subprocess of Emacs. Then you would
exit the shell to return to Emacs.
Suspension is not useful with window systems, because the Emacs job may not have a
parent that can resume it again, and in any case you can give input to some other job such
as a shell merely by moving to a different window. Therefore, suspending is not allowed
when Emacs is using a window system (X, MS Windows, or Mac).
(add-hook ’suspend-hook
(function (lambda ()
(or (y-or-n-p
"Really suspend? ")
(error "Suspend canceled")))))
⇒ (lambda nil
(or (y-or-n-p "Really suspend? ")
(error "Suspend canceled")))
(add-hook ’suspend-resume-hook
(function (lambda () (message "Resumed!"))))
⇒ (lambda nil (message "Resumed!"))
(suspend-emacs "pwd")
⇒ nil
---------- Buffer: Minibuffer ----------
Really suspend? y
---------- Buffer: Minibuffer ----------
suspend-hook [Variable]
This variable is a normal hook that Emacs runs before suspending.
Chapter 39: Operating System Interface 819
suspend-resume-hook [Variable]
This variable is a normal hook that Emacs runs on resuming after a suspension.
system-configuration [Variable]
This variable holds the standard GNU configuration name for the hardware/software
configuration of your system, as a string. The convenient way to test parts of this
string is with string-match.
system-type [Variable]
The value of this variable is a symbol indicating the type of operating system Emacs
is operating on. Here is a table of the possible values:
alpha-vms
VMS on the Alpha.
aix-v3 AIX.
berkeley-unix
Berkeley BSD.
cygwin Cygwin.
dgux Data General DGUX operating system.
gnu the GNU system (using the GNU kernel, which consists of the HURD
and Mach).
gnu/linux
A GNU/Linux system—that is, a variant GNU system, using the Linux
kernel. (These systems are the ones people often call “Linux,” but actu-
ally Linux is just the kernel, not the whole system.)
hpux Hewlett-Packard HPUX operating system.
irix Silicon Graphics Irix system.
ms-dos Microsoft MS-DOS “operating system.” Emacs compiled with DJGPP
for MS-DOS binds system-type to ms-dos even when you run it on MS-
Windows.
next-mach
NeXT Mach-based system.
rtu Masscomp RTU, UCB universe.
unisoft-unix
UniSoft UniPlus.
usg-unix-v
AT&T System V.
Chapter 39: Operating System Interface 820
The symbol system-name is a variable as well as a function. In fact, the function returns
whatever value the variable system-name currently holds. Thus, you can set the variable
system-name in case Emacs is confused about the name of your system. The variable is
also useful for constructing frame titles (see Section 29.4 [Frame Titles], page 540).
mail-host-address [Variable]
If this variable is non-nil, it is used instead of system-name for purposes of generating
email addresses. For example, it is used when constructing the default value of user-
mail-address. See Section 39.4 [User Identification], page 822. (Since this is done
when Emacs starts up, the value actually used is the one saved when Emacs was
dumped. See Section E.1 [Building Emacs], page 870.)
getenv var [Command]
This function returns the value of the environment variable var, as a string. var
should be a string. If var is undefined in the environment, getenv returns nil. If
returns ‘""’ if var is set but null. Within Emacs, the environment variable values are
kept in the Lisp variable process-environment.
(getenv "USER")
⇒ "lewis"
lewis@slug[10] % printenv
PATH=.:/user/lewis/bin:/usr/bin:/usr/local/bin
USER=lewis
TERM=ibmapa16
SHELL=/bin/csh
HOME=/user/lewis
setenv variable &optional value [Command]
This command sets the value of the environment variable named variable to value.
variable should be a string. Internally, Emacs Lisp can handle any string. However,
normally variable should be a valid shell identifier, that is, a sequence of letters, digits
and underscores, starting with a letter or underscore. Otherwise, errors may occur if
Chapter 39: Operating System Interface 821
subprocesses of Emacs try to access the value of variable. If value is omitted or nil,
setenv removes variable from the environment. Otherwise, value should be a string.
setenv works by modifying process-environment; binding that variable with let
is also reasonable practice.
setenv returns the new value of variable, or nil if it removed variable from the
environment.
process-environment [Variable]
This variable is a list of strings, each describing one environment variable. The
functions getenv and setenv work by means of this variable.
process-environment
⇒ ("l=/usr/stanford/lib/gnuemacs/lisp"
"PATH=.:/user/lewis/bin:/usr/class:/nfsusr/local/bin"
"USER=lewis"
"TERM=ibmapa16"
"SHELL=/bin/csh"
"HOME=/user/lewis")
If process-environment contains “duplicate” elements that specify the same en-
vironment variable, the first of these elements specifies the variable, and the other
“duplicates” are ignored.
path-separator [Variable]
This variable holds a string which says which character separates directories in a
search path (as found in an environment variable). Its value is ":" for Unix and
GNU systems, and ";" for MS-DOS and MS-Windows.
invocation-name [Variable]
This variable holds the program name under which Emacs was invoked. The value is
a string, and does not include a directory name.
invocation-directory [Variable]
This variable holds the directory from which the Emacs executable was invoked, or
perhaps nil if that directory cannot be determined.
installation-directory [Variable]
If non-nil, this is a directory within which to look for the ‘lib-src’ and ‘etc’ subdi-
rectories. This is non-nil when Emacs can’t find those directories in their standard
installed locations, but can find them in a directory related somehow to the one
containing the Emacs executable.
Chapter 39: Operating System Interface 822
lewis@rocky[5] % uptime
11:55am up 1 day, 19:37, 3 users,
load average: 1.69, 0.48, 0.36
emacs-pid [Function]
This function returns the process ID of the Emacs process, as an integer.
tty-erase-char [Variable]
This variable holds the erase character that was selected in the system’s terminal
driver, before Emacs was started. The value is nil if Emacs is running under a
window system.
setprv privilege-name &optional setp getprv [Function]
This function sets or resets a VMS privilege. (It does not exist on other systems.)
The first argument is the privilege name, as a string. The second argument, setp, is
t or nil, indicating whether the privilege is to be turned on or off. Its default is nil.
The function returns t if successful, nil otherwise.
If the third argument, getprv, is non-nil, setprv does not change the privilege, but
returns t or nil indicating whether the privilege is currently enabled.
user-mail-address [Variable]
This holds the nominal email address of the user who is using Emacs. Emacs normally
sets this variable to a default value after reading your init files, but not if you have
already set it. So you can set the variable to some other value in your init file if you
do not want to use the default value.
user-real-login-name [Function]
This function returns the user name corresponding to Emacs’s real UID. This ignores
the effective UID and ignores the environment variables LOGNAME and USER.
user-real-uid [Function]
This function returns the real UID of the user. The value may be a floating point
number.
(user-real-uid)
⇒ 19
user-uid [Function]
This function returns the effective UID of the user. The value may be a floating point
number.
Chapter 39: Operating System Interface 824
current-time [Function]
This function returns the system’s time value as a list of three integers: (high low
microsec ). The integers high and low combine to give the number of seconds since
0:00 January 1, 1970 UTC (Coordinated Universal Time), which is high ∗ 216 + low.
The third element, microsec, gives the microseconds since the start of the current
second (or 0 for systems that return time with the resolution of only one second).
The first two elements can be compared with file time values such as you get with
the function file-attributes. See [Definition of file-attributes], page 448.
set-time-zone-rule tz [Function]
This function specifies the local time zone according to tz. If tz is nil, that means
to use an implementation-defined default time zone. If tz is t, that means to use
Universal Time. Otherwise, tz should be a string specifying a time zone rule.
Chapter 39: Operating System Interface 825
encode-time seconds minutes hour day month year &optional zone [Function]
This function is the inverse of decode-time. It converts seven items of calendrical
data into a time value. For the meanings of the arguments, see the table above under
decode-time.
Year numbers less than 100 are not treated specially. If you want them to stand for
years above 1900, or years above 2000, you must alter them yourself before you call
encode-time.
The optional argument zone defaults to the current time zone and its daylight saving
time rules. If specified, it can be either a list (as you would get from current-time-
zone), a string as in the TZ environment variable, t for Universal Time, or an integer
(as you would get from decode-time). The specified zone is used without any further
alteration for daylight saving time.
If you pass more than seven arguments to encode-time, the first six are used as
seconds through year, the last argument is used as zone, and the arguments in between
are ignored. This feature makes it possible to use the elements of a list returned by
decode-time as the arguments to encode-time, like this:
(apply ’encode-time (decode-time ...))
You can perform simple date arithmetic by using out-of-range values for the sec-
onds, minutes, hour, day, and month arguments; for example, day 0 means the day
preceding the given month.
The operating system puts limits on the range of possible time values; if you try to
encode a time that is out of range, an error results. For instance, years before 1970
do not work on some systems; on others, years as early as 1901 do work.
For example, ‘%S’ specifies the number of seconds since the minute; ‘%03S’ means to
pad this with zeros to 3 positions, ‘%_3S’ to pad with spaces to 3 positions. Plain
‘%3S’ pads with zeros, because that is how ‘%S’ normally pads to two positions.
The characters ‘E’ and ‘O’ act as modifiers when used between ‘%’ and one of the
letters in the table above. ‘E’ specifies using the current locale’s “alternative” version
of the date and time. In a Japanese locale, for example, %Ex might yield a date format
based on the Japanese Emperors’ reigns. ‘E’ is allowed in ‘%Ec’, ‘%EC’, ‘%Ex’, ‘%EX’,
‘%Ey’, and ‘%EY’.
‘O’ means to use the current locale’s “alternative” representation of numbers, instead
of the ordinary decimal digits. This is allowed with most letters, all the ones that
output numbers.
If universal is non-nil, that means to describe the time as Universal Time; nil means
describe it using what Emacs believes is the local time zone (see current-time-zone).
This function uses the C library function strftime (see section “Formatting Calendar
Time” in The GNU C Library Reference Manual) to do most of the work. In order
to communicate with that function, it first encodes its argument using the coding
system specified by locale-coding-system (see Section 33.12 [Locales], page 660);
after strftime returns the resulting string, format-time-string decodes the string
using that same coding system.
time-less-p t1 t2 [Function]
This returns t if time value t1 is less than time value t2.
time-subtract t1 t2 [Function]
This returns the time difference t1 − t2 between two time values, in the same format
as a time value.
Chapter 39: Operating System Interface 829
time-add t1 t2 [Function]
This returns the sum of two time values, one of which ought to represent a time
difference rather than a point in time. Here is how to add a number of seconds to a
time value:
(time-add time (seconds-to-time seconds ))
Since timers can run within a Lisp program only when the program calls a primitive
that can wait, with-timeout cannot stop executing body while it is in the midst of a
computation—only when it calls one of those primitives. So use with-timeout only
with a body that waits for input, not one that does a long computation.
Emacs becomes “idle” when it starts waiting for user input, and it remains idle until the
user provides some input. If a timer is set for five seconds of idleness, it runs approximately
five seconds after Emacs first becomes idle. Even if repeat is non-nil, this timer will not
run again as long as Emacs remains idle, because the duration of idleness will continue to
increase and will not go down to five seconds again.
Emacs can do various things while idle: garbage collect, autosave or handle data from a
subprocess. But these interludes during idleness do not interfere with idle timers, because
they do not reset the clock of idleness to zero. An idle timer set for 600 seconds will run
when ten minutes have elapsed since the last user command was finished, even if subprocess
output has been accepted thousands of times within those ten minutes, and even if there
have been garbage collections and autosaves.
When the user supplies input, Emacs becomes non-idle while executing the input. Then
it becomes idle again, and all the idle timers that are set up to repeat will subsequently run
another time, one by one.
current-idle-time [Function]
This function returns the length of time Emacs has been idle, as a list of three integers:
(high low microsec ). The integers high and low combine to give the number of
seconds of idleness, which is high ∗ 216 + low.
Chapter 39: Operating System Interface 832
The third element, microsec, gives the microseconds since the start of the current
second (or 0 for systems that return time with the resolution of only one second).
The main use of this function is when an idle timer function wants to “take a break”
for a while. It can set up another idle timer to call the same function again, after a
few seconds more idleness. Here’s an example:
(defvar resume-timer nil
"Timer that ‘timer-function’ used to reschedule itself, or nil.")
(defun timer-function ()
;; If the user types a command while resume-timer
;; is active, the next time this function is called from
;; its main idle timer, deactivate resume-timer.
(when resume-timer
(cancel-timer resume-timer))
...do the work for a while...
(when taking-a-break
(setq resume-timer
(run-with-idle-timer
;; Compute an idle time break-length
;; more than the current value.
(time-add (current-idle-time)
(seconds-to-time break-length ))
nil
’timer-function))))
Some idle timer functions in user Lisp packages have a loop that does a certain amount
of processing each time around, and exits when (input-pending-p) is non-nil. That
approach seems very natural but has two problems:
• It blocks out all process output (since Emacs accepts process output only while waiting).
• It blocks out any idle timers that ought to run during that time.
To avoid these problems, don’t use that technique. Instead, write such idle timers to
reschedule themselves after a brief pause, using the method in the timer-function example
above.
The argument meta controls support for input character codes above 127. If meta is
t, Emacs converts characters with the 8th bit set into Meta characters. If meta is
nil, Emacs disregards the 8th bit; this is necessary when the terminal uses it as a
parity bit. If meta is neither t nor nil, Emacs uses all 8 bits of input unchanged.
This is good for terminals that use 8-bit character sets.
If quit-char is non-nil, it specifies the character to use for quitting. Normally this
character is C-g. See Section 21.10 [Quitting], page 338.
The current-input-mode function returns the input mode settings Emacs is currently
using.
current-input-mode [Function]
This function returns the current mode for reading keyboard input. It returns a list,
corresponding to the arguments of set-input-mode, of the form (interrupt flow
meta quit ) in which:
interrupt is non-nil when Emacs is using interrupt-driven input. If nil, Emacs is
using cbreak mode.
flow is non-nil if Emacs uses xon/xoff (C-q, C-s) flow control for output to
the terminal. This value is meaningful only when interrupt is nil.
meta is t if Emacs treats the eighth bit of input characters as the meta bit;
nil means Emacs clears the eighth bit of every input character; any other
value means Emacs uses all eight bits as the basic character code.
quit is the character Emacs currently uses for quitting, usually C-g.
baud-rate [Variable]
This variable’s value is the output speed of the terminal, as far as Emacs knows.
Setting this variable does not change the speed of actual data transmission, but the
value is used for calculations such as padding.
It also affects decisions about whether to scroll part of the screen or repaint on text
terminals. See Section 38.2 [Forcing Redisplay], page 739, for the corresponding
functionality on graphical terminals.
The value is measured in baud.
If you are running across a network, and different parts of the network work at different
baud rates, the value returned by Emacs may be different from the value used by your local
terminal. Some network protocols communicate the local terminal speed to the remote
machine, so that Emacs and other programs can get the proper value, but others do not.
If Emacs has the wrong value, it makes decisions that are less than optimal. To fix the
problem, set baud-rate.
baud-rate [Function]
This obsolete function returns the value of the variable baud-rate.
play-sound-functions [Variable]
A list of functions to be called before playing a sound. Each function is called with
one argument, a property list that describes the sound.
system-key-alist [Variable]
This variable’s value should be an alist with one element for each system-specific
keysym. Each element has the form (code . symbol ), where code is the numeric
Chapter 39: Operating System Interface 836
keysym code (not including the “vendor specific” bit, −228 ), and symbol is the name
for the function key.
For example (168 . mute-acute) defines a system-specific key (used by HP X servers)
whose numeric code is −228 + 168.
It is not crucial to exclude from the alist the keysyms of other X servers; those do no
harm, as long as they don’t conflict with the ones used by the X server actually in
use.
The variable is always local to the current terminal, and cannot be buffer-local. See
Section 29.2 [Multiple Displays], page 530.
You can specify which keysyms Emacs should use for the Meta, Alt, Hyper, and Super
modifiers by setting these variables:
x-alt-keysym [Variable]
x-meta-keysym [Variable]
x-hyper-keysym [Variable]
x-super-keysym [Variable]
The name of the keysym that should stand for the Alt modifier (respectively, for Meta,
Hyper, and Super). For example, here is how to swap the Meta and Alt modifiers
within Emacs:
(setq x-alt-keysym ’meta)
(setq x-meta-keysym ’alt)
When the session manager restarts a suspended session, it directs these applications to
individually reload their saved state. It does this by specifying a special command-line
argument that says what saved session to restore. For Emacs, this argument is ‘--smid
session ’.
emacs-save-session-functions [Variable]
Emacs supports saving state by using a hook called emacs-save-session-functions.
Each function in this hook is called when the session manager tells Emacs that the
window system is shutting down. The functions are called with no arguments and
with the current buffer set to a temporary buffer. Each function can use insert to
add Lisp code to this buffer. At the end, Emacs saves the buffer in a file that a
subsequent Emacs invocation will load in order to restart the saved session.
If a function in emacs-save-session-functions returns non-nil, Emacs tells the
session manager to cancel the shutdown.
Here is an example that just inserts some text into ‘*scratch*’ when Emacs is restarted
by the session manager.
(add-hook ’emacs-save-session-functions ’save-yourself-test)
(defun save-yourself-test ()
(insert "(save-excursion
(switch-to-buffer \"*scratch*\")
(insert \"I am restored\"))")
nil)
Appendix A: Emacs 21 Antinews 838
− The priority of faces in a list supplied by the :inherit face attribute has been
reversed. We like to make changes like this once in a while, to keep Emacs Lisp
programmers on their toes.
− The min-colors face attribute, used for tailoring faces to limited-color displays,
does not exist. If in doubt, use colors like “white” and “black,” which ought to be
defined everywhere.
− The tty-color-mode frame parameter does not exist. You should just trust the
terminal capabilities database.
• Several simplifications have been made to mouse support:
− Clicking mouse-1 won’t follow links, as that is alien to the spirit of Emacs. There-
fore, the follow-link property doesn’t has any special meaning, and the function
mouse-on-link-p has been removed.
− The variable void-text-area-pointer has been removed, so the mouse pointer
shape remains unchanged when moving between valid text areas and void text
areas. The pointer image and text properties are no longer supported.
− Mouse events will no longer specify the timestamp, the object clicked, equivalent
buffer positions (for marginal or fringe areas), glyph coordinates, or relative pixel
coordinates.
• Simplifications have also been made to the way Emacs handles keymaps and key se-
quences:
− The kbd macro is now obsolete and is no longer documented. It isn’t that difficult
to write key sequences using the string and vector representations, and we want
to encourage users to learn.
− Emacs no longer supports key remapping. You can do pretty much the same thing
with substitute-key-definition, or by advising the relevant command.
− The keymap text and overlay property is now overridden by minor mode keymaps,
and will not work at the ends of text properties and overlays.
− The functions map-keymap, keymap-prompt, and current-active-maps have been
removed.
• Process support has been pared down to a functional minimum. The functions call-
process-shell-command and process-file have been deleted. Processes no longer
maintain property lists, and they won’t ask any questions when the user tries to exit
Emacs (which would simply be rude.) The function signal-process won’t accept a
process object, only the process id; determining the process id from a process object is
left as an exercise to the programmer.
• Networking has also been simplified: make-network-process and its various associated
function have all been replaced with a single easy-to-use function, open-network-
stream, which can’t use UDP, can’t act as a server, and can’t set up non-blocking
connections. Also, deleting a network process with delete-process won’t call the
sentinel.
• Many programming shortcuts have been deleted, to provide you with the enjoyment
of “rolling your own.” The macros while-no-input, with-local-quit, and with-
selected-window, along with dynamic-completion-table and lazy-completion-
Appendix A: Emacs 21 Antinews 840
table no longer exist. Also, there are no built-in progress reporters; with Emacs,
you can take progress for granted.
• Variable aliases are no longer supported. Aliases are for functions, not for variables.
• The variables most-positive-fixnum and most-negative-fixnum do not exist. On
32 bit machines, the most positive integer is probably 134217727, and the most negative
integer is probably -134217728.
• The functions eql and macroexpand-all are no longer available. However, you can
find similar functions in the cl package.
• The list returned by split-string won’t include null substrings for separators at the
beginning or end of a string. If you want to check for such separators, do it separately.
• The function assoc-string has been removed. Use assoc-ignore-case or assoc-
ignore-representation (which are no longer obsolete.)
• The escape sequence ‘\s’ is always interpreted as a super modifier, never a space.
• The variable buffer-save-without-query has been removed, to prevent Emacs from
sneakily saving buffers. Also, the hook before-save-hook has been removed, so if you
want something to be done before saving, advise or redefine basic-save-buffer.
• The variable buffer-auto-save-file-format has been renamed to auto-save-file-
format, and is no longer a permanent local.
• The function visited-file-modtime now returns a cons, instead of a list of two inte-
gers. The primitive set-file-times has been eliminated.
• The function file-remote-p is no longer available.
• When determining the filename extension, a leading dot in a filename is no longer
ignored. Thus, ‘.emacs’ is considered to have extension ‘emacs’, rather than being
extensionless.
• Emacs looks for special file handlers in a more efficient manner: it will choose the
first matching handler in file-name-handler-alist, rather than trying to figure out
which provides the closest match.
• The predicate argument for read-file-name has been removed, and so have the vari-
ables read-file-name-function and read-file-name-completion-ignore-case.
The function read-directory-name has also been removed.
• The functions all-completions and try-completion will no longer accept lists of
strings or hash tables (it will still accept alists, obarrays, and functions.) In addition,
the function test-completion is no longer available.
• The ‘G’ interactive code character is no longer supported. Use ‘F’ instead.
• Arbitrary Lisp functions can no longer be recorded into buffer-undo-list. As a
consequence, yank-undo-function is obsolete, and has been removed.
• Emacs will never complain about commands that accumulate too much undo informa-
tion, so you no longer have to worry about binding buffer-undo-list to t for such
commands (though you may want to do that anyway, to avoid taking up unnecessary
memory space.)
• Atomic change groups are no longer supported.
• The list returned by (match-data t) no longer records the buffer as a final element.
Appendix A: Emacs 21 Antinews 841
• The function looking-back has been removed, so we no longer have the benefit of
hindsight.
• The variable search-spaces-regexp does not exist. Spaces always stand for them-
selves in regular expression searches.
• The functions skip-chars-forward and skip-chars-backward no longer accepts char-
acter classes such as ‘[:alpha:]’. All characters are created equal.
• The yank-handler text property no longer has any meaning. Also, yank-excluded-
properties, insert-for-yank, and insert-buffer-substring-as-yank have all
been removed.
• The variable char-property-alias-alist has been deleted. Aliases are for functions,
not for properties.
• The function get-char-property-and-overlay has been deleted. If you want the
properties at a point, find the text properties at the point; then, find the overlays at
the point, and find the properties on those overlays.
• Font Lock mode only manages face properties; you can’t use font-lock keywords to
specify arbitrary text properties for it to manage. After all, it is called Font Lock mode,
not Arbitrary Properties Lock mode.
• The arguments to remove-overlays are no longer optional.
• In replace-match, the replacement text now inherits properties from the surrounding
text.
• The variable mode-line-format no longer supports the :propertize, %i, and %I con-
structs. The function format-mode-line has been removed.
• The functions window-inside-edges and window-body-height have been removed.
You should do the relevant calculations yourself, starting with window-width and
window-height.
• The functions window-pixel-edges and window-inside-pixel-edges have been re-
moved. We prefer to think in terms of lines and columns, not pixel coordinates. (Some-
time in the distant past, we will do away with graphical terminals entirely, in favor of
text terminals.) For similar reasons, the functions posn-at-point, posn-at-x-y, and
window-line-height have been removed, and pos-visible-in-window-p no longer
worries about partially visible rows.
• The macro save-selected-window only saves the selected window of the selected
frame, so don’t try selecting windows in other frames.
• The function minibufferp is no longer available.
• The function modify-all-frames-parameters has been removed (we always suspected
the name was ungrammatical, anyway.)
• The line-spacing variable no longer accepts float values.
• The function tool-bar-local-item-from-menu has been deleted. If you need to make
an entry in the tool bar, you can still use tool-bar-add-item-from-menu, but that
modifies the binding in the source keymap instead of copying it into the local keymap.
• When determining the major mode, the file name takes precedence over the interpreter
magic line. The variable magic-mode-alist, which associates certain buffer beginnings
with major modes, has been eliminated.
Appendix A: Emacs 21 Antinews 842
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and
useful document “free” in the sense of freedom: to assure everyone the effective freedom
to copy and redistribute it, with or without modifying it, either commercially or non-
commercially. Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible for modifications
made by others.
This License is a kind of “copyleft,” which means that derivative works of the document
must themselves be free in the same sense. It complements the GNU General Public
License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because
free software needs free documentation: a free program should come with manuals
providing the same freedoms that the software does. But this License is not limited to
software manuals; it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License principally for
works whose purpose is instruction or reference.
The “Invariant Sections” are certain Secondary Sections whose titles are designated, as
being those of Invariant Sections, in the notice that says that the Document is released
under this License. If a section does not fit the above definition of Secondary then it is
not allowed to be designated as Invariant. The Document may contain zero Invariant
Sections. If the Document does not identify any Invariant Sections then there are none.
The “Cover Texts” are certain short passages of text that are listed, as Front-Cover
Texts or Back-Cover Texts, in the notice that says that the Document is released under
this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may
be at most 25 words.
A “Transparent” copy of the Document means a machine-readable copy, represented
in a format whose specification is available to the general public, that is suitable for
revising the document straightforwardly with generic text editors or (for images com-
posed of pixels) generic paint programs or (for drawings) some widely available drawing
editor, and that is suitable for input to text formatters or for automatic translation to
a variety of formats suitable for input to text formatters. A copy made in an otherwise
Transparent file format whose markup, or absence of markup, has been arranged to
thwart or discourage subsequent modification by readers is not Transparent. An image
format is not Transparent if used for any substantial amount of text. A copy that is
not “Transparent” is called “Opaque.”
Examples of suitable formats for Transparent copies include plain ASCII without
markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly
available DTD, and standard-conforming simple HTML, PostScript or PDF designed
for human modification. Examples of transparent image formats include PNG, XCF
and JPG. Opaque formats include proprietary formats that can be read and edited
only by proprietary word processors, SGML or XML for which the DTD and/or pro-
cessing tools are not generally available, and the machine-generated HTML, PostScript
or PDF produced by some word processors for output purposes only.
The “Title Page” means, for a printed book, the title page itself, plus such following
pages as are needed to hold, legibly, the material this License requires to appear in the
title page. For works in formats which do not have any title page as such, “Title Page”
means the text near the most prominent appearance of the work’s title, preceding the
beginning of the body of the text.
A section “Entitled XYZ” means a named subunit of the Document whose title either
is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in
another language. (Here XYZ stands for a specific section name mentioned below, such
as “Acknowledgements,” “Dedications,” “Endorsements,” or “History.”) To “Preserve
the Title” of such a section when you modify the Document means that it remains a
section “Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that
this License applies to the Document. These Warranty Disclaimers are considered to
be included by reference in this License, but only as regards disclaiming warranties:
any other implication that these Warranty Disclaimers may have is void and has no
effect on the meaning of this License.
2. VERBATIM COPYING
Appendix B: GNU Free Documentation License 845
You may copy and distribute the Document in any medium, either commercially or
noncommercially, provided that this License, the copyright notices, and the license
notice saying this License applies to the Document are reproduced in all copies, and
that you add no other conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further copying of the copies
you make or distribute. However, you may accept compensation in exchange for copies.
If you distribute a large enough number of copies you must also follow the conditions
in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly
display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of
the Document, numbering more than 100, and the Document’s license notice requires
Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all
these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify you as the publisher
of these copies. The front cover must present the full title with all words of the title
equally prominent and visible. You may add other material on the covers in addition.
Copying with changes limited to the covers, as long as they preserve the title of the
Document and satisfy these conditions, can be treated as verbatim copying in other
respects.
If the required texts for either cover are too voluminous to fit legibly, you should put
the first ones listed (as many as fit reasonably) on the actual cover, and continue the
rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100,
you must either include a machine-readable Transparent copy along with each Opaque
copy, or state in or with each Opaque copy a computer-network location from which
the general network-using public has access to download using public-standard network
protocols a complete Transparent copy of the Document, free of added material. If
you use the latter option, you must take reasonably prudent steps, when you begin
distribution of Opaque copies in quantity, to ensure that this Transparent copy will
remain thus accessible at the stated location until at least one year after the last time
you distribute an Opaque copy (directly or through your agents or retailers) of that
edition to the public.
It is requested, but not required, that you contact the authors of the Document well
before redistributing any large number of copies, to give them a chance to provide you
with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions
of sections 2 and 3 above, provided that you release the Modified Version under precisely
this License, with the Modified Version filling the role of the Document, thus licensing
distribution and modification of the Modified Version to whoever possesses a copy of
it. In addition, you must do these things in the Modified Version:
Appendix B: GNU Free Documentation License 846
A. Use in the Title Page (and on the covers, if any) a title distinct from that of the
Document, and from those of previous versions (which should, if there were any, be
listed in the History section of the Document). You may use the same title as a previous
version if the original publisher of that version gives permission.
B. List on the Title Page, as authors, one or more persons or entities responsible for
authorship of the modifications in the Modified Version, together with at least five of
the principal authors of the Document (all of its principal authors, if it has fewer than
five), unless they release you from this requirement.
C. State on the Title page the name of the publisher of the Modified Version, as the
publisher.
D. Preserve all the copyright notices of the Document.
E. Add an appropriate copyright notice for your modifications adjacent to the other
copyright notices.
F. Include, immediately after the copyright notices, a license notice giving the public
permission to use the Modified Version under the terms of this License, in the form
shown in the Addendum below.
G. Preserve in that license notice the full lists of Invariant Sections and required Cover
Texts given in the Document’s license notice.
H. Include an unaltered copy of this License.
I. Preserve the section Entitled “History,” Preserve its Title, and add to it an item
stating at least the title, year, new authors, and publisher of the Modified Version as
given on the Title Page. If there is no section Entitled “History” in the Document,
create one stating the title, year, authors, and publisher of the Document as given
on its Title Page, then add an item describing the Modified Version as stated in the
previous sentence.
J. Preserve the network location, if any, given in the Document for public access to
a Transparent copy of the Document, and likewise the network locations given in the
Document for previous versions it was based on. These may be placed in the “History”
section. You may omit a network location for a work that was published at least four
years before the Document itself, or if the original publisher of the version it refers to
gives permission.
K. For any section Entitled “Acknowledgements” or “Dedications,” Preserve the Title
of the section, and preserve in the section all the substance and tone of each of the
contributor acknowledgements and/or dedications given therein.
L. Preserve all the Invariant Sections of the Document, unaltered in their text and in
their titles. Section numbers or the equivalent are not considered part of the section
titles.
M. Delete any section Entitled “Endorsements.” Such a section may not be included
in the Modified Version.
N. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in
title with any Invariant Section.
O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or appendices that qualify
as Secondary Sections and contain no material copied from the Document, you may at
Appendix B: GNU Free Documentation License 847
your option designate some or all of these sections as invariant. To do this, add their
titles to the list of Invariant Sections in the Modified Version’s license notice. These
titles must be distinct from any other section titles.
You may add a section Entitled “Endorsements,” provided it contains nothing but
endorsements of your Modified Version by various parties–for example, statements of
peer review or that the text has been approved by an organization as the authoritative
definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up
to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified
Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be
added by (or through arrangements made by) any one entity. If the Document already
includes a cover text for the same cover, previously added by you or by arrangement
made by the same entity you are acting on behalf of, you may not add another; but
you may replace the old one, on explicit permission from the previous publisher that
added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission
to use their names for publicity for or to assert or imply endorsement of any Modified
Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License,
under the terms defined in section 4 above for modified versions, provided that you
include in the combination all of the Invariant Sections of all of the original documents,
unmodified, and list them all as Invariant Sections of your combined work in its license
notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical
Invariant Sections may be replaced with a single copy. If there are multiple Invariant
Sections with the same name but different contents, make the title of each such section
unique by adding at the end of it, in parentheses, the name of the original author or
publisher of that section if known, or else a unique number. Make the same adjustment
to the section titles in the list of Invariant Sections in the license notice of the combined
work.
In the combination, you must combine any sections Entitled “History” in the vari-
ous original documents, forming one section Entitled “History”; likewise combine any
sections Entitled “Acknowledgements,” and any sections Entitled “Dedications.” You
must delete all sections Entitled “Endorsements.”
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released
under this License, and replace the individual copies of this License in the various
documents with a single copy that is included in the collection, provided that you
follow the rules of this License for verbatim copying of each of the documents in all
other respects.
You may extract a single document from such a collection, and distribute it individu-
ally under this License, provided you insert a copy of this License into the extracted
Appendix B: GNU Free Documentation License 848
document, and follow this License in all other respects regarding verbatim copying of
that document.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations
of the Document under the terms of section 4. Replacing Invariant Sections with
translations requires special permission from their copyright holders, but you may
include translations of some or all Invariant Sections in addition to the original versions
of these Invariant Sections. You may include a translation of this License, and all the
license notices in the Document, and any Warranty Disclaimers, provided that you
also include the original English version of this License and the original versions of
those notices and disclaimers. In case of a disagreement between the translation and
the original version of this License or a notice or disclaimer, the original version will
prevail.
If a section in the Document is Entitled “Acknowledgements,” “Dedications,” or “His-
tory,” the requirement (section 4) to Preserve its Title (section 1) will typically require
changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly
provided for under this License. Any other attempt to copy, modify, sublicense or
distribute the Document is void, and will automatically terminate your rights under
this License. However, parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such parties remain in full
compliance.
Each version of the License is given a distinguishing version number. If the Document
specifies that a particular numbered version of this License “or any later version”
applies to it, you have the option of following the terms and conditions either of that
specified version or of any later version that has been published (not as a draft) by
the Free Software Foundation. If the Document does not specify a version number of
this License, you may choose any version ever published (not as a draft) by the Free
Software Foundation.
Preamble
The licenses for most software are designed to take away your freedom to share and change
it. By contrast, the GNU General Public License is intended to guarantee your freedom
to share and change free software—to make sure the software is free for all its users. This
General Public License applies to most of the Free Software Foundation’s software and to
any other program whose authors commit to using it. (Some other Free Software Foundation
software is covered by the GNU Lesser General Public License instead.) You can apply it
to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute copies
of free software (and charge for this service if you wish), that you receive source code or
can get it if you want it, that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you
these rights or to ask you to surrender the rights. These restrictions translate to certain
responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you
must give the recipients all the rights that you have. You must make sure that they, too,
receive or can get the source code. And you must show them these terms so they know
their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this
license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author’s protection and ours, we want to make certain that everyone
understands that there is no warranty for this free software. If the software is modified by
someone else and passed on, we want its recipients to know that what they have is not the
original, so that any problems introduced by others will not reflect on the original authors’
reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid
the danger that redistributors of a free program will individually obtain patent licenses, in
effect making the program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone’s free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
Appendix C: GNU General Public License 851
Thus, it is not the intent of this section to claim rights or contest your rights to
work written entirely by you; rather, the intent is to exercise the right to control the
distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the
Program (or with a work based on the Program) on a volume of a storage or distribution
medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2)
in object code or executable form under the terms of Sections 1 and 2 above provided
that you also do one of the following:
a. Accompany it with the complete corresponding machine-readable source code,
which must be distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
b. Accompany it with a written offer, valid for at least three years, to give any third
party, for a charge no more than your cost of physically performing source distri-
bution, a complete machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium customarily
used for software interchange; or,
c. Accompany it with the information you received as to the offer to distribute cor-
responding source code. (This alternative is allowed only for noncommercial dis-
tribution and only if you received the program in object code or executable form
with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifi-
cations to it. For an executable work, complete source code means all the source code
for all modules it contains, plus any associated interface definition files, plus the scripts
used to control compilation and installation of the executable. However, as a spe-
cial exception, the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major components (compiler,
kernel, and so on) of the operating system on which the executable runs, unless that
component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from
a designated place, then offering equivalent access to copy the source code from the
same place counts as distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly
provided under this License. Any attempt otherwise to copy, modify, sublicense or
distribute the Program is void, and will automatically terminate your rights under this
License. However, parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such parties remain in full
compliance.
5. You are not required to accept this License, since you have not signed it. However,
nothing else grants you permission to modify or distribute the Program or its derivative
works. These actions are prohibited by law if you do not accept this License. Therefore,
by modifying or distributing the Program (or any work based on the Program), you
indicate your acceptance of this License to do so, and all its terms and conditions for
copying, distributing or modifying the Program or works based on it.
Appendix C: GNU General Public License 853
6. Each time you redistribute the Program (or any work based on the Program), the
recipient automatically receives a license from the original licensor to copy, distribute
or modify the Program subject to these terms and conditions. You may not impose
any further restrictions on the recipients’ exercise of the rights granted herein. You are
not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any
other reason (not limited to patent issues), conditions are imposed on you (whether by
court order, agreement or otherwise) that contradict the conditions of this License, they
do not excuse you from the conditions of this License. If you cannot distribute so as
to satisfy simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not distribute the Program at all. For
example, if a patent license would not permit royalty-free redistribution of the Program
by all those who receive copies directly or indirectly through you, then the only way
you could satisfy both it and this License would be to refrain entirely from distribution
of the Program.
If any portion of this section is held invalid or unenforceable under any particular
circumstance, the balance of the section is intended to apply and the section as a
whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other
property right claims or to contest validity of any such claims; this section has the
sole purpose of protecting the integrity of the free software distribution system, which
is implemented by public license practices. Many people have made generous contri-
butions to the wide range of software distributed through that system in reliance on
consistent application of that system; it is up to the author/donor to decide if he or
she is willing to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence
of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either
by patents or by copyrighted interfaces, the original copyright holder who places the
Program under this License may add an explicit geographical distribution limitation
excluding those countries, so that distribution is permitted only in or among countries
not thus excluded. In such case, this License incorporates the limitation as if written
in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General
Public License from time to time. Such new versions will be similar in spirit to the
present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a
version number of this License which applies to it and “any later version”, you have
the option of following the terms and conditions either of that version or of any later
version published by the Free Software Foundation. If the Program does not specify a
version number of this License, you may choose any version ever published by the Free
Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distri-
bution conditions are different, write to the author to ask for permission. For software
Appendix C: GNU General Public License 854
which is copyrighted by the Free Software Foundation, write to the Free Software Foun-
dation; we sometimes make exceptions for this. Our decision will be guided by the two
goals of preserving the free status of all derivatives of our free software and of promoting
the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY AP-
PLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
“AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IM-
PLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE EN-
TIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO
MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED
ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT
LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an
interactive mode:
Gnomovision version 69, Copyright (C) yyyy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’.
This is free software, and you are welcome to redistribute it
under certain conditions; type ‘show c’ for details.
The hypothetical commands ‘show w’ and ‘show c’ should show the appropriate parts of
the General Public License. Of course, the commands you use may be called something
other than ‘show w’ and ‘show c’; they could even be mouse-clicks or menu items—whatever
suits your program.
You should also get your employer (if you work as a programmer) or your school, if any,
to sign a “copyright disclaimer” for the program, if necessary. Here is a sample; alter the
names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program ‘Gnomovision’
(which makes passes at compilers) written
by James Hacker.
• If one file foo uses a macro defined in another file bar, foo should contain this expression
before the first use of the macro:
(eval-when-compile (require ’bar ))
(And the library bar should contain (provide ’bar ), to make the require work.) This
will cause bar to be loaded when you byte-compile foo. Otherwise, you risk compiling
foo without the necessary macro loaded, and that would produce compiled code that
won’t work right. See Section 13.3 [Compiling Macros], page 177.
Using eval-when-compile avoids loading bar when the compiled version of foo is used.
• Please don’t require the cl package of Common Lisp extensions at run time. Use of
this package is optional, and it is not part of the standard Emacs namespace. If your
package loads cl at run time, that could cause name clashes for users who don’t use
that package.
However, there is no problem with using the cl package at compile time, with (eval-
when-compile (require ’cl)). That’s sufficient for using the macros in the cl pack-
age, because the compiler expands them before generating the byte-code.
• When defining a major mode, please follow the major mode conventions. See Sec-
tion 23.2.2 [Major Mode Conventions], page 385.
• When defining a minor mode, please follow the minor mode conventions. See Sec-
tion 23.3.1 [Minor Mode Conventions], page 397.
• If the purpose of a function is to tell you whether a certain condition is true or false,
give the function a name that ends in ‘p’. If the name is one word, add just ‘p’; if the
name is multiple words, add ‘-p’. Examples are framep and frame-live-p.
• If a user option variable records a true-or-false condition, give it a name that ends in
‘-flag’.
• If the purpose of a variable is to store a single function, give it a name that ends in
‘-function’. If the purpose of a variable is to store a list of functions (i.e., the variable
is a hook), please follow the naming conventions for hooks. See Section 23.1 [Hooks],
page 382.
• If loading the file adds functions to hooks, define a function feature -unload-hook,
where feature is the name of the feature the package provides, and make it undo any
such changes. Using unload-feature to unload the file will run this function. See
Section 15.9 [Unloading], page 211.
• It is a bad idea to define aliases for the Emacs primitives. Normally you should use the
standard names instead. The case where an alias may be useful is where it facilitates
backwards compatibility or portability.
• If a package needs to define an alias or a new function for compatibility with some
other version of Emacs, name it with the package prefix, not with the raw name with
which it occurs in the other version. Here is an example from Gnus, which provides
many examples of such compatibility issues.
(defalias ’gnus-point-at-bol
(if (fboundp ’point-at-bol)
’point-at-bol
’line-beginning-position))
Appendix D: Tips and Conventions 858
• Redefining (or advising) an Emacs primitive is a bad idea. It may do the right thing
for a particular program, but there is no telling what other programs might break as a
result. In any case, it is a problem for debugging, because the advised function doesn’t
do what its source code says it does. If the programmer investigating the problem is
unaware that there is advice on the function, the experience can be very frustrating.
We hope to remove all the places in Emacs that advise primitives. In the mean time,
please don’t add any more.
• It is likewise a bad idea for one Lisp package to advise a function in another Lisp
package.
• Likewise, avoid using eval-after-load (see Section 15.10 [Hooks for Loading],
page 212) in libraries and packages. This feature is meant for personal customizations;
using it in a Lisp program is unclean, because it modifies the behavior of another Lisp
file in a way that’s not visible in that file. This is an obstacle for debugging, much
like advising a function in the other package.
• If a file does replace any of the functions or library programs of standard Emacs, promi-
nent comments at the beginning of the file should say which functions are replaced,
and how the behavior of the replacements differs from that of the originals.
• Constructs that define a function or variable should be macros, not functions, and their
names should start with ‘def’.
• A macro that defines a function or variable should have a name that starts with
‘define-’. The macro should receive the name to be defined as the first argument.
That will help various tools find the definition automatically. Avoid constructing the
names in the macro itself, since that would confuse these tools.
• Please keep the names of your Emacs Lisp source files to 13 characters or less. This
way, if the files are compiled, the compiled files’ names will be 14 characters or less,
which is short enough to fit on all kinds of Unix systems.
• In some other systems there is a convention of choosing variable names that begin and
end with ‘*’. We don’t use that convention in Emacs Lisp, so please don’t use it in
your programs. (Emacs uses such names only for special-purpose buffers.) The users
will find Emacs more coherent if all libraries use the same conventions.
• If your program contains non-ASCII characters in string or character constants, you
should make sure Emacs always decodes these characters the same way, regardless of
the user’s settings. There are two ways to do that:
- Use coding system emacs-mule, and specify that for coding in the ‘-*-’ line or
the local variables list.
;; XXX.el -*- coding: emacs-mule; -*-
- Use one of the coding systems based on ISO 2022 (such as iso-8859-n and iso-2022-
7bit), and specify it with ‘!’ at the end for coding. (The ‘!’ turns off any possible
character translation.)
;; XXX.el -*- coding: iso-latin-2!; -*-
• Indent each function with C-M-q (indent-sexp) using the default indentation param-
eters.
• Don’t make a habit of putting close-parentheses on lines by themselves; Lisp pro-
grammers find this disconcerting. Once in a while, when there is a sequence of many
Appendix D: Tips and Conventions 859
consecutive close-parentheses, it may make sense to split the sequence in one or two
significant places.
• Please put a copyright notice and copying permission notice on the file if you distribute
copies. Use a notice like this one:
;; Copyright (C) year name
• Do not bind C-h following any prefix character (including C-c). If you don’t bind C-h,
it is automatically available as a help character for listing the subcommands of the
prefix character.
• Do not bind a key sequence ending in ESC except following another ESC. (That is, it
is OK to bind a sequence ending in ESC ESC.)
The reason for this rule is that a non-prefix binding for ESC in any context prevents
recognition of escape sequences as function keys in that context.
• Anything which acts like a temporary mode or state which the user can enter and leave
should define ESC ESC or ESC ESC ESC as a way to escape.
For a state which accepts ordinary Emacs commands, or more generally any kind of
state in which ESC followed by a function key or arrow key is potentially meaningful,
then you must not define ESC ESC, since that would preclude recognizing an escape
sequence after ESC. In these states, you should define ESC ESC ESC as the way to
escape. Otherwise, define ESC ESC instead.
• An error message should start with a capital letter but should not end with a period.
• A question asked in the minibuffer with y-or-n-p or yes-or-no-p should start with a
capital letter and end with ‘? ’.
• When you mention a default value in a minibuffer prompt, put it and the word
‘default’ inside parentheses. It should look like this:
Enter the answer (default 42):
• In interactive, if you use a Lisp expression to produce a list of arguments, don’t
try to provide the “correct” default values for region or position arguments. Instead,
provide nil for those arguments if they were not specified, and have the function body
compute the default value when the argument is nil. For instance, write this:
(defun foo (pos)
(interactive
(list (if specified specified-pos )))
(unless pos (setq pos default-pos ))
...)
rather than this:
(defun foo (pos)
(interactive
(list (if specified specified-pos
default-pos )))
...)
This is so that repetition of the command will recompute these defaults based on the
current circumstances.
You do not need to take such precautions when you use interactive specs ‘d’, ‘m’ and
‘r’, because they make special arrangements to recompute the argument values on
repetition of the command.
• Many commands that take a long time to execute display a message that says something
like ‘Operating...’ when they start, and change it to ‘Operating...done’ when they
finish. Please keep the style of these messages uniform: no space around the ellipsis,
and no period after ‘done’.
• Try to avoid using recursive edits. Instead, do what the Rmail e command does: use a
new local keymap that contains one command defined to switch back to the old local
keymap. Or do what the edit-options command does: switch to another buffer and
let the user switch back at will. See Section 21.12 [Recursive Editing], page 342.
• Using the primitive list-searching functions memq, member, assq, or assoc is even faster
than explicit iteration. It can be worth rearranging a data structure so that one of
these primitive search functions can be used.
• Certain built-in functions are handled specially in byte-compiled code, avoiding the
need for an ordinary function call. It is a good idea to use these functions rather than
alternatives. To see whether a function is handled specially by the compiler, examine
its byte-compile property. If the property is non-nil, then the function is handled
specially.
For example, the following input will show you that aref is compiled specially (see
Section 6.3 [Array Functions], page 90):
(get ’aref ’byte-compile)
⇒ byte-compile-two-args
• If calling a small function accounts for a substantial part of your program’s running
time, make the function inline. This eliminates the function call overhead. Since
making a function inline reduces the flexibility of changing the program, don’t do it
unless it gives a noticeable speedup in something slow enough that users care about
the speed. See Section 12.10 [Inline Functions], page 173.
If this puts a lower-case letter at the beginning of a sentence and that annoys you,
rewrite the sentence so that the symbol is not at the start of it.
• Do not start or end a documentation string with whitespace.
• Do not indent subsequent lines of a documentation string so that the text is lined up
in the source code with the text of the first line. This looks nice in the source code,
but looks bizarre when users view the documentation. Remember that the indentation
before the starting double-quote is not part of the string!
• When a documentation string refers to a Lisp symbol, write it as it would be printed
(which usually means in lower case), with single-quotes around it. For example:
‘‘lambda’’. There are two exceptions: write t and nil without single-quotes.
Help mode automatically creates a hyperlink when a documentation string uses a sym-
bol name inside single quotes, if the symbol has either a function or a variable definition.
You do not need to do anything special to make use of this feature. However, when a
symbol has both a function definition and a variable definition, and you want to refer
to just one of them, you can specify which one by writing one of the words ‘variable’,
‘option’, ‘function’, or ‘command’, immediately before the symbol name. (Case makes
no difference in recognizing these indicator words.) For example, if you write
This function sets the variable ‘buffer-file-name’.
then the hyperlink will refer only to the variable documentation of buffer-file-name,
and not to its function documentation.
If a symbol has a function definition and/or a variable definition, but those are irrelevant
to the use of the symbol that you are documenting, you can write the words ‘symbol’
or ‘program’ before the symbol name to prevent making any hyperlink. For example,
If the argument KIND-OF-RESULT is the symbol ‘list’,
this function returns a list of all the objects
that satisfy the criterion.
does not make a hyperlink to the documentation, irrelevant here, of the function list.
Normally, no hyperlink is made for a variable without variable documentation. You can
force a hyperlink for such variables by preceding them with one of the words ‘variable’
or ‘option’.
Hyperlinks for faces are only made if the face name is preceded or followed by the word
‘face’. In that case, only the face documentation will be shown, even if the symbol is
also defined as a variable or as a function.
To make a hyperlink to Info documentation, write the name of the Info node (or anchor)
in single quotes, preceded by ‘info node’, ‘Info node’, ‘info anchor’ or ‘Info anchor’.
The Info file name defaults to ‘emacs’. For example,
See Info node ‘Font Lock’ and Info node ‘(elisp)Font Lock Basics’.
Finally, to create a hyperlink to URLs, write the URL in single quotes, preceded by
‘URL’. For example,
The home page for the GNU project has more information (see URL
‘http://www.gnu.org/’).
• Don’t write key sequences directly in documentation strings. Instead, use the ‘\\[...]’
construct to stand for them. For example, instead of writing ‘C-f’, write the construct
‘\\[forward-char]’. When Emacs displays the documentation string, it substitutes
Appendix D: Tips and Conventions 865
whatever key is currently bound to forward-char. (This is normally ‘C-f’, but it may
be some other character if the user has moved key bindings.) See Section 24.3 [Keys
in Documentation], page 428.
• In documentation strings for a major mode, you will want to refer to the key bindings of
that mode’s local map, rather than global ones. Therefore, use the construct ‘\\<...>’
once in the documentation string to specify which key map to use. Do this before the
first use of ‘\\[...]’. The text inside the ‘\\<...>’ should be the name of the variable
containing the local keymap for the major mode.
It is not practical to use ‘\\[...]’ very many times, because display of the documen-
tation string will become slow. So use this to describe the most important commands
in your major mode, and then use ‘\\{...}’ to display the rest of the mode’s keymap.
• For consistency, phrase the verb in the first sentence of a function’s documentation
string as an imperative—for instance, use “Return the cons of A and B.” in preference
to “Returns the cons of A and B.” Usually it looks good to do likewise for the rest
of the first paragraph. Subsequent paragraphs usually look better if each sentence is
indicative and has a proper subject.
• The documentation string for a function that is a yes-or-no predicate should start with
words such as “Return t if,” to indicate explicitly what constitutes “truth.” The word
“return” avoids starting the sentence with lower-case “t,” which could be somewhat
distracting.
• If a line in a documentation string begins with an open-parenthesis, write a backslash
before the open-parenthesis, like this:
The argument FOO can be either a number
\(a buffer position) or a string (a file name).
This prevents the open-parenthesis from being treated as the start of a defun (see
section “Defuns” in The GNU Emacs Manual).
• Write documentation strings in the active voice, not the passive, and in the present
tense, not the future. For instance, use “Return a list containing A and B.” instead of
“A list containing A and B will be returned.”
• Avoid using the word “cause” (or its equivalents) unnecessarily. Instead of, “Cause
Emacs to display text in boldface,” write just “Display text in boldface.”
• When a command is meaningful only in a certain mode or situation, do mention that
in the documentation string. For example, the documentation of dired-find-file is:
In Dired, visit the file or directory named on this line.
• When you define a variable that users ought to set interactively, you normally should
use defcustom. However, if for some reason you use defvar instead, start the doc
string with a ‘*’. See Section 11.5 [Defining Variables], page 139.
• The documentation string for a variable that is a yes-or-no flag should start with words
such as “Non-nil means,” to make it clear that all non-nil values are equivalent and
indicate explicitly what nil and non-nil mean.
‘;’ Comments that start with a single semicolon, ‘;’, should all be aligned to the
same column on the right of the source code. Such comments usually explain
how the code on the same line does its job. In Lisp mode and related modes,
the M-; (indent-for-comment) command automatically inserts such a ‘;’ in
the right place, or aligns such a comment if it is already present.
This and following examples are taken from the Emacs sources.
(setq base-version-list ; there was a base
(assoc (substring fn 0 start-vn) ; version to which
file-version-assoc-list)) ; this looks like
; a subversion
‘;;’ Comments that start with two semicolons, ‘;;’, should be aligned to the same
level of indentation as the code. Such comments usually describe the purpose
of the following lines or the state of the program at that point. For example:
(prog1 (setq auto-fill-function
...
...
;; update mode line
(force-mode-line-update)))
We also normally use two semicolons for comments outside functions.
;; This Lisp code is run in Emacs
;; when it is to operate as a server
;; for other processes.
Every function that has no documentation string (presumably one that is used
only internally within the package it belongs to), should instead have a two-
semicolon comment right before the function, explaining what the function does
and how to call it properly. Explain precisely what each argument means and
how the function interprets its possible values.
‘;;;’ Comments that start with three semicolons, ‘;;;’, should start at the left mar-
gin. These are used, occasionally, for comments within functions that should
start at the margin. We also use them sometimes for comments that are be-
tween functions—whether to use two or three semicolons depends on whether
the comment should be considered a “heading” by Outline minor mode. By
default, comments starting with at least three semicolons (followed by a sin-
gle space and a non-whitespace character) are considered headings, comments
starting with two or less are not.
Another use for triple-semicolon comments is for commenting out lines within a
function. We use three semicolons for this precisely so that they remain at the
left margin. By default, Outline minor mode does not consider a comment to
be a heading (even if it starts with at least three semicolons) if the semicolons
are followed by at least two spaces. Thus, if you add an introductory comment
to the commented out code, make sure to indent it by at least two spaces after
the three semicolons.
(defun foo (a)
;;; This is no longer necessary.
;;; (force-mode-line-update)
(message "Finished with %s" a))
When commenting out entire functions, use two semicolons.
Appendix D: Tips and Conventions 867
‘;;;;’ Comments that start with four semicolons, ‘;;;;’, should be aligned to the left
margin and are used for headings of major sections of a program. For example:
;;;; The kill ring
The indentation commands of the Lisp modes in Emacs, such as M-; (indent-for-comment)
and TAB (lisp-indent-line), automatically indent comments according to these conven-
tions, depending on the number of semicolons. See section “Manipulating Comments” in
The GNU Emacs Manual.
‘Maintainer’
This line should contain a single name/address as in the Author line, or an
address only, or the string ‘FSF’. If there is no maintainer line, the person(s)
in the Author field are presumed to be the maintainers. The example above is
mildly bogus because the maintainer line is redundant.
The idea behind the ‘Author’ and ‘Maintainer’ lines is to make possible a Lisp
function to “send mail to the maintainer” without having to mine the name out
by hand.
Be sure to surround the network address with ‘<...>’ if you include the person’s
full name as well as the network address.
‘Created’ This optional line gives the original creation date of the file. For historical
interest only.
‘Version’ If you wish to record version numbers for the individual Lisp program, put them
in this line.
‘Adapted-By’
In this header line, place the name of the person who adapted the library for
installation (to make it fit the style conventions, for example).
‘Keywords’
This line lists keywords for the finder-by-keyword help command. Please use
that command to see a list of the meaningful keywords.
This field is important; it’s how people will find your package when they’re
looking for things by topic area. To separate the keywords, you can use spaces,
commas, or both.
Just about every Lisp library ought to have the ‘Author’ and ‘Keywords’ header comment
lines. Use the others if they are appropriate. You can also put in header lines with other
header names—they have no standard meanings, so they can’t do any harm.
We use additional stylized comments to subdivide the contents of the library file. These
should be separated by blank lines from anything else. Here is a table of them:
‘;;; Commentary:’
This begins introductory comments that explain how the library works. It
should come right after the copying permissions, terminated by a ‘Change Log’,
‘History’ or ‘Code’ comment line. This text is used by the Finder package, so
it should make sense in that context.
‘;;; Documentation:’
This was used in some files in place of ‘;;; Commentary:’, but it is deprecated.
‘;;; Change Log:’
This begins change log information stored in the library file (if you store the
change history there). For Lisp files distributed with Emacs, the change history
is kept in the file ‘ChangeLog’ and not in the source file at all; these files generally
do not have a ‘;;; Change Log:’ line. ‘History’ is an alternative to ‘Change
Log’.
‘;;; Code:’
This begins the actual code of the program.
Appendix D: Tips and Conventions 869
• Arrange to scan these files when producing the ‘etc/DOC’ file, and load them with
‘site-load.el’.
• Load the files with ‘site-init.el’, then copy the files into the installation directory
for Lisp files when you install Emacs.
• Specify a non-nil value for byte-compile-dynamic-docstrings as a local variable in
each of these files, and load them with either ‘site-load.el’ or ‘site-init.el’. (This
method has the drawback that the documentation strings take up space in Emacs all
the time.)
It is not advisable to put anything in ‘site-load.el’ or ‘site-init.el’ that would
alter any of the features that users expect in an ordinary unmodified Emacs. If you feel
you must override normal features for your site, do it with ‘default.el’, so that users can
override your changes if they wish. See Section 39.1.1 [Startup Summary], page 812.
In a package that can be preloaded, it is sometimes useful to specify a computation to
be done when Emacs subsequently starts up. For this, use eval-at-startup:
pure-bytes-used [Variable]
The value of this variable is the number of bytes of pure storage allocated so far.
Typically, in a dumped Emacs, this number is very close to the total amount of pure
storage available—if it were not, we would preallocate less.
purify-flag [Variable]
This variable determines whether defun should make a copy of the function definition
in pure storage. If it is non-nil, then the function definition is copied into pure
storage.
This flag is t while loading all of the basic functions for building Emacs initially
(allowing those functions to be sharable and non-collectible). Dumping Emacs as an
executable always writes nil in this variable, regardless of the value it actually has
before and after dumping.
You should not change this flag in a running Emacs.
The sweep phase puts unused cons cells onto a free list for future allocation; likewise for
symbols and markers. It compacts the accessible strings so they occupy fewer 8k blocks;
then it frees the other 8k blocks. Vectors, buffers, windows, and other large objects are
individually allocated and freed using malloc and free.
Common Lisp note: Unlike other Lisps, GNU Emacs Lisp does not call the
garbage collector when the free list is empty. Instead, it simply requests the
operating system to allocate more storage, and processing continues until gc-
cons-threshold bytes have been used.
This means that you can make sure that the garbage collector will not run
during a certain portion of a Lisp program by calling the garbage collector
explicitly just before it (provided that portion of the program does not use so
much space as to force a second garbage collection).
garbage-collect [Command]
This command runs a garbage collection, and returns information on the amount of
space in use. (Garbage collection can also occur spontaneously if you use more than
gc-cons-threshold bytes of Lisp data since the previous garbage collection.)
garbage-collect returns a list containing the following information:
((used-conses . free-conses )
(used-syms . free-syms )
(used-miscs . free-miscs )
used-string-chars
used-vector-slots
(used-floats . free-floats )
(used-intervals . free-intervals )
(used-strings . free-strings ))
Here is an example:
(garbage-collect)
⇒ ((106886 . 13184) (9769 . 0)
(7731 . 4651) 347543 121628
(31 . 94) (1273 . 168)
(25474 . 3569))
Here is a table explaining each element:
used-conses
The number of cons cells in use.
free-conses
The number of cons cells for which space has been obtained from the
operating system, but that are not currently being used.
used-syms The number of symbols in use.
free-syms The number of symbols for which space has been obtained from the op-
erating system, but that are not currently being used.
used-miscs
The number of miscellaneous objects in use. These include markers and
overlays, plus certain objects not visible to users.
Appendix E: GNU Emacs Internals 874
free-miscs The number of miscellaneous objects for which space has been obtained
from the operating system, but that are not currently being used.
used-string-chars
The total size of all strings, in characters.
used-vector-slots
The total number of elements of existing vectors.
used-floats
The number of floats in use.
free-floats The number of floats for which space has been obtained from the operat-
ing system, but that are not currently being used.
used-intervals
The number of intervals in use. Intervals are an internal data structure
used for representing text properties.
free-intervals
The number of intervals for which space has been obtained from the
operating system, but that are not currently being used.
used-strings
The number of strings in use.
free-strings
The number of string headers for which the space was obtained from the
operating system, but which are currently not in use. (A string object
consists of a header and the storage for the string text itself; the latter is
only allocated when the string is created.)
If there was overflow in pure space (see the previous section), garbage-collect
returns nil, because a real garbage collection can not be done in this situation.
post-gc-hook [Variable]
This is a normal hook that is run at the end of garbage collection. Garbage collection
is inhibited while the hook functions run, so be careful writing them.
increases total memory use. You may want to do this when running a program that
creates lots of Lisp data.
You can make collections more frequent by specifying a smaller value, down to 10,000.
A value less than 10,000 will remain in effect only until the subsequent garbage col-
lection, at which time garbage-collect will set the threshold back to 10,000.
The value returned by garbage-collect describes the amount of memory used by Lisp
data, broken down by data type. By contrast, the function memory-limit provides infor-
mation on the total amount of memory Emacs is currently using.
memory-limit [Function]
This function returns the address of the last byte Emacs has allocated, divided by
1024. We divide the value by 1024 to make sure it fits in a Lisp integer.
You can use this to get a general idea of how your actions affect the memory usage.
memory-full [Variable]
This variable is t if Emacs is close to out of memory for Lisp objects, and nil
otherwise.
memory-use-counts [Function]
This returns a list of numbers that count the number of objects created in this Emacs
session. Each of these counters increments for a certain kind of object. See the
documentation string for details.
gcs-done [Variable]
This variable contains the total number of garbage collections done so far in this
Emacs session.
gc-elapsed [Variable]
This variable contains the total number of seconds of elapsed time during garbage
collection so far in this Emacs session, as a floating point number.
cons-cells-consed [Variable]
The total number of cons cells that have been allocated so far in this Emacs session.
Appendix E: GNU Emacs Internals 876
floats-consed [Variable]
The total number of floats that have been allocated so far in this Emacs session.
vector-cells-consed [Variable]
The total number of vector cells that have been allocated so far in this Emacs session.
symbols-consed [Variable]
The total number of symbols that have been allocated so far in this Emacs session.
string-chars-consed [Variable]
The total number of string characters that have been allocated so far in this Emacs
session.
misc-objects-consed [Variable]
The total number of miscellaneous objects that have been allocated so far in this
Emacs session. These include markers and overlays, plus certain objects not visible
to users.
intervals-consed [Variable]
The total number of intervals that have been allocated so far in this Emacs session.
strings-consed [Variable]
The total number of strings that have been allocated so far in this Emacs session.
GCPRO1 (args);
UNGCPRO;
return val;
}
Let’s start with a precise explanation of the arguments to the DEFUN macro. Here is a
template for them:
DEFUN (lname, fname, sname, min, max, interactive, doc )
lname This is the name of the Lisp symbol to define as the function name; in the
example above, it is or.
fname This is the C function name for this function. This is the name that is used in
C code for calling the function. The name is, by convention, ‘F’ prepended to
the Lisp name, with all dashes (‘-’) in the Lisp name changed to underscores.
Thus, to call this function from C code, call For. Remember that the arguments
must be of type Lisp_Object; various macros and functions for creating values
of type Lisp_Object are declared in the file ‘lisp.h’.
sname This is a C variable name to use for a structure that holds the data for the subr
object that represents the function in Lisp. This structure conveys the Lisp
symbol name to the initialization routine that will create the symbol and store
the subr object as its definition. By convention, this name is always fname with
‘F’ replaced with ‘S’.
min This is the minimum number of arguments that the function requires. The
function or allows a minimum of zero arguments.
max This is the maximum number of arguments that the function accepts, if there is
a fixed maximum. Alternatively, it can be UNEVALLED, indicating a special form
that receives unevaluated arguments, or MANY, indicating an unlimited number
of evaluated arguments (the equivalent of &rest). Both UNEVALLED and MANY
are macros. If max is a number, it may not be less than min and it may not be
greater than eight.
interactive
This is an interactive specification, a string such as might be used as the ar-
gument of interactive in a Lisp function. In the case of or, it is 0 (a null
pointer), indicating that or cannot be called interactively. A value of "" indi-
cates a function that should receive no arguments when called interactively.
doc This is the documentation string. It uses C comment syntax rather than C
string syntax because comment syntax requires nothing special to include mul-
tiple lines. The ‘doc:’ identifies the comment that follows as the documentation
string. The ‘/*’ and ‘*/’ delimiters that begin and end the comment are not
part of the documentation string.
If the last line of the documentation string begins with the keyword ‘usage:’,
the rest of the line is treated as the argument list for documentation purposes.
This way, you can use different argument names in the documentation string
from the ones used in the C code. ‘usage:’ is required if the function has an
unlimited number of arguments.
All the usual rules for documentation strings in Lisp code (see Section D.6
[Documentation Tips], page 862) apply to C code documentation strings too.
Appendix E: GNU Emacs Internals 878
After the call to the DEFUN macro, you must write the argument name list that every C
function must have, followed by ordinary C declarations for the arguments. For a function
with a fixed maximum number of arguments, declare a C argument for each Lisp argument,
and give them all type Lisp_Object. When a Lisp function has no upper limit on the
number of arguments, its implementation in C actually receives exactly two arguments: the
first is the number of Lisp arguments, and the second is the address of a block containing
their values. They have types int and Lisp_Object *.
Within the function For itself, note the use of the macros GCPRO1 and UNGCPRO. GCPRO1
is used to “protect” a variable from garbage collection—to inform the garbage collector that
it must look in that variable and regard its contents as an accessible object. GC protection
is necessary whenever you call Feval or anything that can directly or indirectly call Feval.
At such a time, any Lisp object that this function may refer to again must be protected
somehow.
It suffices to ensure that at least one pointer to each object is GC-protected; that way,
the object cannot be recycled, so all pointers to it remain valid. Thus, a particular local
variable can do without protection if it is certain that the object it points to will be preserved
by some other pointer (such as another local variable which has a GCPRO)1 . Otherwise, the
local variable needs a GCPRO.
The macro GCPRO1 protects just one local variable. If you want to protect two variables,
use GCPRO2 instead; repeating GCPRO1 will not work. Macros GCPRO3, GCPRO4, GCPRO5, and
GCPRO6 also exist. All these macros implicitly use local variables such as gcpro1; you must
declare these explicitly, with type struct gcpro. Thus, if you use GCPRO2, you must declare
gcpro1 and gcpro2. Alas, we can’t explain all the tricky details here.
UNGCPRO cancels the protection of the variables that are protected in the current function.
It is necessary to do this explicitly.
Built-in functions that take a variable number of arguments actually accept two argu-
ments at the C level: the number of Lisp arguments, and a Lisp_Object * pointer to a C
vector containing those Lisp arguments. This C vector may be part of a Lisp vector, but
it need not be. The responsibility for using GCPRO to protect the Lisp arguments from GC
if necessary rests with the caller in this case, since the caller allocated or found the storage
for them.
You must not use C initializers for static or global variables unless the variables are never
written once Emacs is dumped. These variables with initializers are allocated in an area
of memory that becomes read-only (on certain operating systems) as a result of dumping
Emacs. See Section E.2 [Pure Storage], page 871.
Do not use static variables within functions—place all static variables at top level in the
file. This is necessary because Emacs on some operating systems defines the keyword static
as a null macro. (This definition is used because those systems put all variables declared
static in a place that becomes read-only after dumping, whether they have initializers or
not.)
Defining the C function is not enough to make a Lisp primitive available; you must also
create the Lisp symbol for the primitive and store a suitable subr object in its function cell.
The code looks like this:
1
Formerly, strings were a special exception; in older Emacs versions, every local variable that might point
to a string needed a GCPRO.
Appendix E: GNU Emacs Internals 879
defsubr (&subr-structure-name );
Here subr-structure-name is the name you used as the third argument to DEFUN.
If you add a new primitive to a file that already has Lisp primitives defined in it, find
the function (near the end of the file) named syms_of_something , and add the call to
defsubr there. If the file doesn’t have this function, or if you create a new file, add to it a
syms_of_filename (e.g., syms_of_myfile). Then find the spot in ‘emacs.c’ where all of
these functions are called, and add a call to syms_of_filename there.
The function syms_of_filename is also the place to define any C variables that are to
be visible as Lisp variables. DEFVAR_LISP makes a C variable of type Lisp_Object visible
in Lisp. DEFVAR_INT makes a C variable of type int visible in Lisp with a value that is
always an integer. DEFVAR_BOOL makes a C variable of type int visible in Lisp with a value
that is either t or nil. Note that variables defined with DEFVAR_BOOL are automatically
added to the list byte-boolean-vars used by the byte compiler.
If you define a file-scope C variable of type Lisp_Object, you must protect it from
garbage-collection by calling staticpro in syms_of_filename , like this:
staticpro (&variable );
Here is another example function, with more complicated arguments. This comes from
the code in ‘window.c’, and it demonstrates the use of macros and functions to manipulate
Lisp objects.
DEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p,
Scoordinates_in_window_p, 2, 2,
"xSpecify coordinate pair: \nXExpression which evals to window: ",
"Return non-nil if COORDINATES is in WINDOW.\n\
COORDINATES is a cons of the form (X . Y), X and Y being distances\n\
...
If they are on the border between WINDOW and its right sibling,\n\
‘vertical-line’ is returned.")
(coordinates, window)
register Lisp_Object coordinates, window;
{
int x, y;
default:
abort ();
}
}
Note that C code cannot call functions by name unless they are defined in C. The way
to call a function written in Lisp is to use Ffuncall, which embodies the Lisp function
funcall. Since the Lisp function funcall accepts an unlimited number of arguments, in C
it takes two: the number of Lisp-level arguments, and a one-dimensional array containing
their values. The first Lisp-level argument is the Lisp function to call, and the rest are the
arguments to pass to it. Since Ffuncall can call the evaluator, you must protect pointers
from garbage collection around the call to Ffuncall.
The C functions call0, call1, call2, and so on, provide handy ways to call a Lisp
function conveniently with a fixed number of arguments. They work by calling Ffuncall.
‘eval.c’ is a very good file to look through for examples; ‘lisp.h’ contains the definitions
for some important macros and functions.
If you define a function which is side-effect free, update the code in ‘byte-opt.el’
which binds side-effect-free-fns and side-effect-and-error-free-fns so that the
compiler optimizer knows about it.
z This field contains the character position of the end of the buffer text.
gpt_byte Contains the byte position of the gap.
z_byte Holds the byte position of the end of the buffer text.
gap_size Contains the size of buffer’s gap. See Section 27.12 [Buffer Gap], page 495.
modiff This field counts buffer-modification events for this buffer. It is incremented
for each such event, and never otherwise changed.
save_modiff
Contains the previous value of modiff, as of the last time a buffer was visited
or saved in a file.
overlay_modiff
Counts modifications to overlays analogous to modiff.
beg_unchanged
Holds the number of characters at the start of the text that are known to be
unchanged since the last redisplay that finished.
end_unchanged
Holds the number of characters at the end of the text that are known to be
unchanged since the last redisplay that finished.
unchanged_modified
Contains the value of modiff at the time of the last redisplay that finished.
If this value matches modiff, beg_unchanged and end_unchanged contain no
useful information.
overlay_unchanged_modified
Contains the value of overlay_modiff at the time of the last redisplay that
finished. If this value matches overlay_modiff, beg_unchanged and end_
unchanged contain no useful information.
markers The markers that refer to this buffer. This is actually a single marker, and
successive elements in its marker chain are the other markers referring to this
buffer text.
intervals
Contains the interval tree which records the text properties of this buffer.
The fields of struct buffer are:
next Points to the next buffer, in the chain of all buffers including killed buffers.
This chain is used only for garbage collection, in order to collect killed buffers
properly. Note that vectors, and most kinds of objects allocated as vectors, are
all on one chain, but buffers are on a separate chain of their own.
own_text This is a struct buffer_text structure. In an ordinary buffer, it holds the
buffer contents. In indirect buffers, this field is not used.
text This points to the buffer_text structure that is used for this buffer. In an
ordinary buffer, this is the own_text field above. In an indirect buffer, this is
the own_text field of the base buffer.
Appendix E: GNU Emacs Internals 882
fill_column
The value of fill-column in this buffer.
left_margin
The value of left-margin in this buffer.
auto_fill_function
The value of auto-fill-function in this buffer.
downcase_table
This field contains the conversion table for converting text to lower case. See
Section 4.9 [Case Tables], page 60.
upcase_table
This field contains the conversion table for converting text to upper case. See
Section 4.9 [Case Tables], page 60.
case_canon_table
This field contains the conversion table for canonicalizing text for case-folding
search. See Section 4.9 [Case Tables], page 60.
case_eqv_table
This field contains the equivalence table for case-folding search. See Section 4.9
[Case Tables], page 60.
truncate_lines
The value of truncate-lines in this buffer.
ctl_arrow
The value of ctl-arrow in this buffer.
selective_display
The value of selective-display in this buffer.
selective_display_ellipsis
The value of selective-display-ellipsis in this buffer.
minor_modes
An alist of the minor modes of this buffer.
overwrite_mode
The value of overwrite_mode in this buffer.
abbrev_mode
The value of abbrev-mode in this buffer.
display_table
This field contains the buffer’s display table, or nil if it doesn’t have one. See
Section 38.21 [Display Tables], page 807.
save_modified
This field contains the time when the buffer was last saved, as an integer. See
Section 27.5 [Buffer Modification], page 487.
mark_active
This field is non-nil if the buffer’s mark is active.
Appendix E: GNU Emacs Internals 885
overlays_before
This field holds a list of the overlays in this buffer that end at or before the
current overlay center position. They are sorted in order of decreasing end
position.
overlays_after
This field holds a list of the overlays in this buffer that end after the current
overlay center position. They are sorted in order of increasing beginning posi-
tion.
overlay_center
This field holds the current overlay center position. See Section 38.9 [Overlays],
page 754.
enable_multibyte_characters
This field holds the buffer’s local value of enable-multibyte-characters—
either t or nil.
buffer_file_coding_system
The value of buffer-file-coding-system in this buffer.
file_format
The value of buffer-file-format in this buffer.
auto_save_file_format
The value of buffer-auto-save-file-format in this buffer.
pt_marker
In an indirect buffer, or a buffer that is the base of an indirect buffer, this holds
a marker that records point for this buffer when the buffer is not current.
begv_marker
In an indirect buffer, or a buffer that is the base of an indirect buffer, this holds
a marker that records begv for this buffer when the buffer is not current.
zv_marker
In an indirect buffer, or a buffer that is the base of an indirect buffer, this holds
a marker that records zv for this buffer when the buffer is not current.
file_truename
The truename of the visited file, or nil.
invisibility_spec
The value of buffer-invisibility-spec in this buffer.
last_selected_window
This is the last window that was selected with this buffer in it, or nil if that
window no longer displays this buffer.
display_count
This field is incremented each time the buffer is displayed in a window.
left_margin_width
The value of left-margin-width in this buffer.
Appendix E: GNU Emacs Internals 886
right_margin_width
The value of right-margin-width in this buffer.
indicate_empty_lines
Non-nil means indicate empty lines (lines with no text) with a small bitmap
in the fringe, when using a window system that can do it.
display_time
This holds a time stamp that is updated each time this buffer is displayed in a
window.
scroll_up_aggressively
The value of scroll-up-aggressively in this buffer.
scroll_down_aggressively
The value of scroll-down-aggressively in this buffer.
buffer The buffer that the window is displaying. This may change often during the
life of the window.
start The position in the buffer that is the first character to be displayed in the
window.
pointm This is the value of point in the current buffer when this window is selected;
when it is not selected, it retains its previous value.
force_start
If this flag is non-nil, it says that the window has been scrolled explicitly by
the Lisp program. This affects what the next redisplay does if point is off the
screen: instead of scrolling the window to show the text around point, it moves
point to a location that is on the screen.
frozen_window_start_p
This field is set temporarily to 1 to indicate to redisplay that start of this
window should not be changed, even if point gets invisible.
start_at_line_beg
Non-nil means current value of start was the beginning of a line when it was
chosen.
too_small_ok
Non-nil means don’t delete this window for becoming “too small.”
height_fixed_p
This field is temporarily set to 1 to fix the height of the selected window when
the echo area is resized.
use_time This is the last time that the window was selected. The function get-lru-
window uses this field.
sequence_number
A unique number assigned to this window when it was created.
last_modified
The modiff field of the window’s buffer, as of the last time a redisplay completed
in this window.
last_overlay_modified
The overlay_modiff field of the window’s buffer, as of the last time a redisplay
completed in this window.
last_point
The buffer’s value of point, as of the last time a redisplay completed in this
window.
last_had_star
A non-nil value means the window’s buffer was “modified” when the window
was last updated.
vertical_scroll_bar
This window’s vertical scroll bar.
Appendix E: GNU Emacs Internals 888
left_margin_width
The width of the left margin in this window, or nil not to specify it (in which
case the buffer’s value of left-margin-width is used.
right_margin_width
Likewise for the right margin.
window_end_pos
This is computed as z minus the buffer position of the last glyph in the current
matrix of the window. The value is only valid if window_end_valid is not nil.
window_end_bytepos
The byte position corresponding to window_end_pos.
window_end_vpos
The window-relative vertical position of the line containing window_end_pos.
window_end_valid
This field is set to a non-nil value if window_end_pos is truly valid. This
is nil if nontrivial redisplay is preempted since in that case the display that
window_end_pos was computed for did not get onto the screen.
redisplay_end_trigger
If redisplay in this window goes beyond this buffer position, it runs the
redisplay-end-trigger-hook.
cursor A structure describing where the cursor is in this window.
last_cursor
The value of cursor as of the last redisplay that finished.
phys_cursor
A structure describing where the cursor of this window physically is.
phys_cursor_type
The type of cursor that was last displayed on this window.
phys_cursor_on_p
This field is non-zero if the cursor is physically on.
cursor_off_p
Non-zero means the cursor in this window is logically on.
last_cursor_off_p
This field contains the value of cursor_off_p as of the time of the last redisplay.
must_be_updated_p
This is set to 1 during redisplay when this window must be updated.
hscroll This is the number of columns that the display in the window is scrolled hori-
zontally to the left. Normally, this is 0.
vscroll Vertical scroll amount, in pixels. Normally, this is 0.
dedicated
Non-nil if this window is dedicated to its buffer.
Appendix E: GNU Emacs Internals 889
display_table
The window’s display table, or nil if none is specified for it.
update_mode_line
Non-nil means this window’s mode line needs to be updated.
base_line_number
The line number of a certain position in the buffer, or nil. This is used for
displaying the line number of point in the mode line.
base_line_pos
The position in the buffer for which the line number is known, or nil meaning
none is known.
region_showing
If the region (or part of it) is highlighted in this window, this field holds the
mark position that made one end of that region. Otherwise, this field is nil.
column_number_displayed
The column number currently displayed in this window’s mode line, or nil if
column numbers are not being displayed.
current_matrix
A glyph matrix describing the current display of this window.
desired_matrix
A glyph matrix describing the desired display of this window.
cyclic-variable-indirection
"Symbol’s chain of variable indirections\
contains a loop"
See Section 11.14 [Variable Aliases], page 157.
end-of-buffer
"End of buffer"
See Section 30.2.1 [Character Motion], page 560.
end-of-file
"End of file during parsing"
Note that this is not a subcategory of file-error, because it pertains to the
Lisp reader, not to file I/O.
See Section 19.3 [Input Functions], page 271.
file-already-exists
This is a subcategory of file-error.
See Section 25.4 [Writing to Files], page 441.
file-date-error
This is a subcategory of file-error. It occurs when copy-file tries and fails
to set the last-modification time of the output file.
See Section 25.7 [Changing Files], page 450.
file-error
We do not list the error-strings of this error and its subcategories, because the
error message is normally constructed from the data items alone when the error
condition file-error is present. Thus, the error-strings are not very relevant.
However, these error symbols do have error-message properties, and if no data
is provided, the error-message property is used.
See Chapter 25 [Files], page 434.
file-locked
This is a subcategory of file-error.
See Section 25.5 [File Locks], page 442.
file-supersession
This is a subcategory of file-error.
See Section 27.6 [Modification Time], page 488.
ftp-error
This is a subcategory of file-error, which results from problems in accessing
a remote file using ftp.
See section “Remote Files” in The GNU Emacs Manual.
invalid-function
"Invalid function"
See Section 9.1.4 [Function Indirection], page 112.
invalid-read-syntax
"Invalid read syntax"
See Section 2.1 [Printed Representation], page 8.
Appendix F: Standard Errors 893
invalid-regexp
"Invalid regexp"
See Section 34.3 [Regular Expressions], page 663.
mark-inactive
"The mark is not active now"
See Section 31.7 [The Mark], page 577.
no-catch "No catch for tag"
See Section 10.5.1 [Catch and Throw], page 125.
scan-error
"Scan error"
This happens when certain syntax-parsing functions find invalid syntax or mis-
matched parentheses.
See Section 30.2.6 [List Motion], page 566, and Section 35.6 [Parsing Expres-
sions], page 691.
search-failed
"Search failed"
See Chapter 34 [Searching and Matching], page 661.
setting-constant
"Attempt to set a constant symbol"
The values of the symbols nil and t, and any symbols that start with ‘:’, may
not be changed.
See Section 11.2 [Variables that Never Change], page 135.
text-read-only
"Text is read-only"
This is a subcategory of buffer-read-only.
See Section 32.19.4 [Special Properties], page 620.
undefined-color
"Undefined color"
See Section 29.20 [Color Names], page 552.
void-function
"Symbol’s function definition is void"
See Section 12.8 [Function Cells], page 171.
void-variable
"Symbol’s value as variable is void"
See Section 11.7 [Accessing Variables], page 143.
wrong-number-of-arguments
"Wrong number of arguments"
See Section 9.1.3 [Classifying Lists], page 112.
wrong-type-argument
"Wrong type argument"
See Section 2.6 [Type Predicates], page 27.
Appendix F: Standard Errors 894
These kinds of error, which are classified as special cases of arith-error, can occur on
certain systems for invalid use of mathematical functions.
domain-error
"Arithmetic domain error"
See Section 3.9 [Math Functions], page 44.
overflow-error
"Arithmetic overflow error"
This is a subcategory of domain-error.
See Section 3.9 [Math Functions], page 44.
range-error
"Arithmetic range error"
See Section 3.9 [Math Functions], page 44.
singularity-error
"Arithmetic singularity error"
This is a subcategory of domain-error.
See Section 3.9 [Math Functions], page 44.
underflow-error
"Arithmetic underflow error"
This is a subcategory of domain-error.
See Section 3.9 [Math Functions], page 44.
Appendix G: Buffer-Local Variables 895
buffer-save-without-query
See Section 27.10 [Killing Buffers], page 493.
buffer-read-only
See Section 27.7 [Read Only Buffers], page 489.
buffer-saved-size
See Section 26.2 [Auto-Saving], page 476.
buffer-undo-list
See Section 32.9 [Undo], page 596.
cache-long-line-scans
See Section 38.3 [Truncation], page 740.
case-fold-search
See Section 34.2 [Searching and Case], page 663.
ctl-arrow
See Section 38.20 [Usual Display], page 806.
cursor-type
See Section 29.3.3.7 [Cursor Parameters], page 536.
cursor-in-non-selected-windows
See Section 28.1 [Basic Windows], page 497.
comment-column
See section “Comments” in The GNU Emacs Manual.
default-directory
See Section 25.8.4 [File Name Expansion], page 457.
defun-prompt-regexp
See Section 30.2.6 [List Motion], page 566.
desktop-save-buffer
See Section 23.7 [Desktop Save Mode], page 424.
enable-multibyte-characters
Section 33.1 [Text Representations], page 640.
fill-column
See Section 32.12 [Margins], page 602.
fill-prefix
See Section 32.12 [Margins], page 602.
font-lock-defaults
See Section 23.6.1 [Font Lock Basics], page 413.
fringe-cursor-alist
See Section 38.13.3 [Fringe Cursors], page 779.
fringe-indicator-alist
See Section 38.13.2 [Fringe Indicators], page 777.
Appendix G: Buffer-Local Variables 897
fringes-outside-margins
See Section 38.13 [Fringes], page 776.
goal-column
See section “Moving Point” in The GNU Emacs Manual.
header-line-format
See Section 23.4.7 [Header Lines], page 409.
indicate-buffer-boundaries
See Section 38.20 [Usual Display], page 806.
indicate-empty-lines
See Section 38.20 [Usual Display], page 806.
left-fringe-width
See Section 38.13.1 [Fringe Size/Pos], page 776.
left-margin
See Section 32.12 [Margins], page 602.
left-margin-width
See Section 38.15.4 [Display Margins], page 786.
line-spacing
See Section 38.11 [Line Height], page 761.
local-abbrev-table
See Section 36.6 [Standard Abbrev Tables], page 704.
major-mode
See Section 23.2.4 [Mode Help], page 390.
mark-active
See Section 31.7 [The Mark], page 577.
mark-ring
See Section 31.7 [The Mark], page 577.
mode-line-buffer-identification
See Section 23.4.4 [Mode Line Variables], page 405.
mode-line-format
See Section 23.4.2 [Mode Line Data], page 402.
mode-line-modified
See Section 23.4.4 [Mode Line Variables], page 405.
mode-line-process
See Section 23.4.4 [Mode Line Variables], page 405.
mode-name
See Section 23.4.4 [Mode Line Variables], page 405.
point-before-scroll
Used for communication between mouse commands and scroll-bar commands.
Appendix G: Buffer-Local Variables 898
right-fringe-width
See Section 38.13.1 [Fringe Size/Pos], page 776.
right-margin-width
See Section 38.15.4 [Display Margins], page 786.
save-buffer-coding-system
See Section 33.10.2 [Encoding and I/O], page 649.
scroll-bar-width
See Section 38.14 [Scroll Bars], page 781.
scroll-down-aggressively
See Section 28.11 [Textual Scrolling], page 515.
scroll-up-aggressively
See Section 28.11 [Textual Scrolling], page 515.
selective-display
See Section 38.7 [Selective Display], page 750.
selective-display-ellipses
See Section 38.7 [Selective Display], page 750.
tab-width
See Section 38.20 [Usual Display], page 806.
truncate-lines
See Section 38.3 [Truncation], page 740.
vertical-scroll-bar
See Section 38.14 [Scroll Bars], page 781.
window-size-fixed
See Section 28.15 [Resizing Windows], page 522.
write-contents-functions
See Section 25.2 [Saving Buffers], page 437.
Appendix H: Standard Keymaps 899
Info-mode-map
A sparse keymap containing Info commands.
isearch-mode-map
A keymap that defines the characters you can type within incremental search.
key-translation-map
A keymap for translating keys. This one overrides ordinary key bindings, unlike
function-key-map. See Section 22.14 [Translation Keymaps], page 365.
kmacro-map
A sparse keymap for keys that follows the C-x C-k prefix search.
lisp-interaction-mode-map
A sparse keymap used by Lisp Interaction mode.
lisp-mode-map
A sparse keymap used by Lisp mode.
menu-bar-edit-menu
The keymap which displays the Edit menu in the menu bar.
menu-bar-files-menu
The keymap which displays the Files menu in the menu bar.
menu-bar-help-menu
The keymap which displays the Help menu in the menu bar.
menu-bar-mule-menu
The keymap which displays the Mule menu in the menu bar.
menu-bar-search-menu
The keymap which displays the Search menu in the menu bar.
menu-bar-tools-menu
The keymap which displays the Tools menu in the menu bar.
mode-specific-map
The keymap for characters following C-c. Note, this is in the global map. This
map is not actually mode specific: its name was chosen to be informative for
the user in C-h b (display-bindings), where it describes the main use of the
C-c prefix key.
occur-mode-map
A sparse keymap used by Occur mode.
query-replace-map
A sparse keymap used for responses in query-replace and related commands;
also for y-or-n-p and map-y-or-n-p. The functions that use this map do not
support prefix keys; they look up one event at a time.
text-mode-map
A sparse keymap used by Text mode.
tool-bar-map
The keymap defining the contents of the tool bar.
Appendix H: Standard Keymaps 902
view-mode-map
A full keymap used by View mode.
Appendix I: Standard Hooks 903
before-make-frame-hook
See Section 29.1 [Creating Frames], page 529.
before-revert-hook
See Section 26.3 [Reverting], page 479.
before-save-hook
See Section 25.2 [Saving Buffers], page 437.
blink-paren-function
See Section 38.19 [Blinking], page 805.
buffer-access-fontify-functions
See Section 32.19.8 [Lazy Properties], page 627.
calendar-load-hook
See Info file ‘emacs-xtra’, node ‘Calendar Customizing’.
change-major-mode-hook
See Section 11.10.2 [Creating Buffer-Local], page 149.
command-line-functions
See Section 39.1.4 [Command-Line Arguments], page 815.
comment-indent-function
See section “Options Controlling Comments” in the GNU Emacs Manual.
compilation-finish-functions
Functions to call when a compilation process finishes.
custom-define-hook
Hook called after defining each customize option.
deactivate-mark-hook
See Section 31.7 [The Mark], page 577.
desktop-after-read-hook
Normal hook run after a successful desktop-read. May be used to show a
buffer list. See section “Saving Emacs Sessions” in the GNU Emacs Manual.
desktop-no-desktop-file-hook
Normal hook run when desktop-read can’t find a desktop file. May be used to
show a dired buffer. See section “Saving Emacs Sessions” in the GNU Emacs
Manual.
desktop-save-hook
Normal hook run before the desktop is saved in a desktop file. This is useful
for truncating history lists, for example. See section “Saving Emacs Sessions”
in the GNU Emacs Manual.
diary-display-hook
See Info file ‘emacs-xtra’, node ‘Fancy Diary Display’.
diary-hook
List of functions called after the display of the diary. Can be used for appoint-
ment notification.
Appendix I: Standard Hooks 905
disabled-command-function
See Section 21.13 [Disabling Commands], page 344.
echo-area-clear-hook
See Section 38.4.4 [Echo Area Customization], page 745.
emacs-startup-hook
See Section 39.1.2 [Init File], page 813.
find-file-hook
See Section 25.1.1 [Visiting Functions], page 434.
find-file-not-found-functions
See Section 25.1.1 [Visiting Functions], page 434.
first-change-hook
See Section 32.26 [Change Hooks], page 638.
font-lock-beginning-of-syntax-function
See Section 23.6.8 [Syntactic Font Lock], page 420.
font-lock-fontify-buffer-function
See Section 23.6.4 [Other Font Lock Variables], page 418.
font-lock-fontify-region-function
See Section 23.6.4 [Other Font Lock Variables], page 418.
font-lock-mark-block-function
See Section 23.6.4 [Other Font Lock Variables], page 418.
font-lock-syntactic-face-function
See Section 23.6.8 [Syntactic Font Lock], page 420.
font-lock-unfontify-buffer-function
See Section 23.6.4 [Other Font Lock Variables], page 418.
font-lock-unfontify-region-function
See Section 23.6.4 [Other Font Lock Variables], page 418.
initial-calendar-window-hook
See Info file ‘emacs-xtra’, node ‘Calendar Customizing’.
kbd-macro-termination-hook
See Section 21.15 [Keyboard Macros], page 345.
kill-buffer-hook
See Section 27.10 [Killing Buffers], page 493.
kill-buffer-query-functions
See Section 27.10 [Killing Buffers], page 493.
kill-emacs-hook
See Section 39.2.1 [Killing Emacs], page 817.
kill-emacs-query-functions
See Section 39.2.1 [Killing Emacs], page 817.
Appendix I: Standard Hooks 906
lisp-indent-function
list-diary-entries-hook
See Info file ‘emacs-xtra’, node ‘Fancy Diary Display’.
mail-setup-hook
See section “Mail Mode Miscellany” in the GNU Emacs Manual.
mark-diary-entries-hook
See Info file ‘emacs-xtra’, node ‘Fancy Diary Display’.
menu-bar-update-hook
See Section 22.17.5 [Menu Bar], page 377.
minibuffer-setup-hook
See Section 20.14 [Minibuffer Misc], page 302.
minibuffer-exit-hook
See Section 20.14 [Minibuffer Misc], page 302.
mouse-position-function
See Section 29.14 [Mouse Position], page 547.
nongregorian-diary-listing-hook
See Info file ‘emacs-xtra’, node ‘Hebrew/Islamic Entries’.
nongregorian-diary-marking-hook
See Info file ‘emacs-xtra’, node ‘Hebrew/Islamic Entries’.
occur-hook
post-command-hook
See Section 21.1 [Command Overview], page 304.
pre-abbrev-expand-hook
See Section 36.5 [Abbrev Expansion], page 702.
pre-command-hook
See Section 21.1 [Command Overview], page 304.
print-diary-entries-hook
See Info file ‘emacs-xtra’, node ‘Diary Customizing’.
redisplay-end-trigger-functions
See Section 28.19 [Window Hooks], page 527.
scheme-indent-function
suspend-hook
See Section 39.2.2 [Suspending Emacs], page 817.
suspend-resume-hook
See Section 39.2.2 [Suspending Emacs], page 817.
temp-buffer-setup-hook
See Section 38.8 [Temporary Displays], page 752.
temp-buffer-show-function
See Section 38.8 [Temporary Displays], page 752.
Appendix I: Standard Hooks 907
temp-buffer-show-hook
See Section 38.8 [Temporary Displays], page 752.
term-setup-hook
See Section 39.1.3 [Terminal-Specific], page 814.
today-visible-calendar-hook
See Info file ‘emacs-xtra’, node ‘Calendar Customizing’.
today-invisible-calendar-hook
See Info file ‘emacs-xtra’, node ‘Calendar Customizing’.
window-configuration-change-hook
See Section 28.19 [Window Hooks], page 527.
window-scroll-functions
See Section 28.19 [Window Hooks], page 527.
window-setup-hook
See Section 38.23 [Window Systems], page 811.
window-size-change-functions
See Section 28.19 [Window Hooks], page 527.
write-contents-functions
See Section 25.2 [Saving Buffers], page 437.
write-file-functions
See Section 25.2 [Saving Buffers], page 437.
write-region-annotate-functions
See Section 32.19.7 [Saving Properties], page 626.
Index 908
Index
" ,
‘"’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 , (with backquote) . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
‘"’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 ,@ (with backquote) . . . . . . . . . . . . . . . . . . . . . . . . . . 179
# -
‘#$’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
‘#’’ syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
‘#:’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
‘#@count ’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 .
‘#n #’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 ‘.’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
‘#n =’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 ‘.’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
‘.emacs’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
$
‘$’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740 /
‘$’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 / . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
/= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
%
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 ;
‘%’ in format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 ‘;’ in comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
& <
‘&’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 < . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
&optional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
<= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
&rest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
’ =
‘’’ for quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
( >
> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
‘(’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
‘(...)’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 >= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
) ?
‘)’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669 ‘?’ in character constant . . . . . . . . . . . . . . . . . . . . . . . 10
? in minibuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
‘?’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
*
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 @
‘*’ in interactive. . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
‘*’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664 ‘@’ in interactive. . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
‘*scratch*’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
[
+ ‘[’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
+ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 [. . . ] (Edebug) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
‘+’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
Index 909
] 2
‘]’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 2C-mode-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
^ A
‘^’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 abbrev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
abbrev tables in modes . . . . . . . . . . . . . . . . . . . . . . . 386
abbrev-all-caps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
‘ abbrev-expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
abbrev-file-name. . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
‘ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
abbrev-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
‘ (list substitution) . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
abbrev-prefix-mark . . . . . . . . . . . . . . . . . . . . . . . . . 702
abbrev-start-location . . . . . . . . . . . . . . . . . . . . . . 703
abbrev-start-location-buffer . . . . . . . . . . . . . . 703
\ abbrev-symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
‘\’ in character constant . . . . . . . . . . . . . . . . . . . . . . . 11 abbrev-table-name-list . . . . . . . . . . . . . . . . . . . . . 700
‘\’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740 abbreviate-file-name . . . . . . . . . . . . . . . . . . . . . . . 457
‘\’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 abbrevs-changed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
‘\’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 abnormal hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
‘\’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 abort-recursive-edit . . . . . . . . . . . . . . . . . . . . . . . 343
‘\’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 aborting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
‘\’ in symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
‘\’’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 absolute file name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
‘\<’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 accept input from processes . . . . . . . . . . . . . . . . . . . 721
‘\=’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 accept-change-group . . . . . . . . . . . . . . . . . . . . . . . . 637
‘\>’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 accept-process-output . . . . . . . . . . . . . . . . . . . . . . 721
‘\_<’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 access-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
‘\_>’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 accessibility of a file . . . . . . . . . . . . . . . . . . . . . . . . . . 443
‘\‘’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 accessible portion (of a buffer) . . . . . . . . . . . . . . . . 569
‘\a’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 accessible-keymaps . . . . . . . . . . . . . . . . . . . . . . . . . 368
‘\b’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
‘\b’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 action (button property) . . . . . . . . . . . . . . . . . . . . . 797
‘\B’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 action, customization keyword . . . . . . . . . . . . . . . 198
‘\e’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 activate-change-group . . . . . . . . . . . . . . . . . . . . . . 637
‘\f’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 activate-mark-hook . . . . . . . . . . . . . . . . . . . . . . . . . 579
‘\n’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 activating advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
‘\n’ in print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 active display table . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
‘\n ’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 active keymap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
‘\r’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 active-minibuffer-window . . . . . . . . . . . . . . . . . . 300
‘\s’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 ad-activate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
‘\s’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 ad-activate-all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
‘\S’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 ad-activate-regexp . . . . . . . . . . . . . . . . . . . . . . . . . 231
ad-add-advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
‘\t’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
ad-deactivate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
‘\v’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
ad-deactivate-all . . . . . . . . . . . . . . . . . . . . . . . . . . 231
‘\w’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
ad-deactivate-regexp . . . . . . . . . . . . . . . . . . . . . . . 231
‘\W’ in regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
ad-default-compilation-action . . . . . . . . . . . . . 231
ad-define-subr-args . . . . . . . . . . . . . . . . . . . . . . . . 235
ad-disable-advice . . . . . . . . . . . . . . . . . . . . . . . . . . 232
| ad-disable-regexp . . . . . . . . . . . . . . . . . . . . . . . . . . 232
‘|’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 ad-do-it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
ad-enable-advice. . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
ad-enable-regexp. . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
1 ad-get-arg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
1+ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 ad-get-args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
1- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 ad-return-value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
1value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 ad-set-arg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
ad-set-args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Index 910
O padding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
obarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 page-delimiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
obarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 paired delimiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
obarray in completion . . . . . . . . . . . . . . . . . . . . . . . . 286 paragraph-separate . . . . . . . . . . . . . . . . . . . . . . . . . 683
object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 paragraph-start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
object internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880 parent of char-table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
object to string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 parent process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
occur-mode-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901 parenthesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
octal character code . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 parenthesis depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
octal character input . . . . . . . . . . . . . . . . . . . . . . . . . 335 parenthesis matching . . . . . . . . . . . . . . . . . . . . . . . . . 805
octal numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 parenthesis mismatch, debugging . . . . . . . . . . . . . 265
one-window-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 parenthesis syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
only-global-abbrevs . . . . . . . . . . . . . . . . . . . . . . . . 701 parse-colon-path. . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
open parenthesis character . . . . . . . . . . . . . . . . . 685 parse-partial-sexp . . . . . . . . . . . . . . . . . . . . . . . . . 694
open-dribble-file . . . . . . . . . . . . . . . . . . . . . . . . . . 833 parse-sexp-ignore-comments . . . . . . . . . . . . . . . . 695
open-network-stream . . . . . . . . . . . . . . . . . . . . . . . . 725 parse-sexp-lookup-properties . . . . . . . . . 690, 695
open-paren-in-column-0-is-defun-start . . . 567 parser state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
open-termscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834 parsing buffer text . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
operating system environment . . . . . . . . . . . . . . . . 819 passwords, reading . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
operations (property) . . . . . . . . . . . . . . . . . . . . . . . 467 PATH environment variable . . . . . . . . . . . . . . . . . . . . 705
option descriptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 path-separator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
optional arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 PBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
options on command line . . . . . . . . . . . . . . . . . . . . . 816 peculiar error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
options, defcustom keyword . . . . . . . . . . . . . . . . . 189 peeking at input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 percent symbol in mode line . . . . . . . . . . . . . . . . . . 403
ordering of windows, cyclic . . . . . . . . . . . . . . . . . . . 503 perform-replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
other-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 performance analysis . . . . . . . . . . . . . . . . . . . . . . . . . 256
other-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504 permanent local variable . . . . . . . . . . . . . . . . . . . . . . 152
other-window-scroll-buffer . . . . . . . . . . . . . . . . 516 permission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
output from processes . . . . . . . . . . . . . . . . . . . . . . . . 717 piece of advice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
output stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 pipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
output-controlling variables . . . . . . . . . . . . . . . . . . . 276 play-sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
overall prompt string . . . . . . . . . . . . . . . . . . . . . . . . . 349 play-sound-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 play-sound-functions . . . . . . . . . . . . . . . . . . . . . . . 835
overflow-newline-into-fringe . . . . . . . . . . . . . . 779 plist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
overlay-arrow-position . . . . . . . . . . . . . . . . . . . . . 781 plist vs. alist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
overlay-arrow-string . . . . . . . . . . . . . . . . . . . . . . . 781 plist-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
overlay-arrow-variable-list . . . . . . . . . . . . . . . 781 plist-member . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
overlay-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 plist-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
overlay-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
overlay-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 point excursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
overlay-properties . . . . . . . . . . . . . . . . . . . . . . . . . 757 point in window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
overlay-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 point with narrowing . . . . . . . . . . . . . . . . . . . . . . . . . 559
overlay-recenter. . . . . . . . . . . . . . . . . . . . . . . . . . . . 756 point-entered (text property) . . . . . . . . . . . . . . . 623
overlay-start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 point-left (text property) . . . . . . . . . . . . . . . . . . . 623
overlayp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 point-marker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
overlays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 point-max . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
overlays-at . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759 point-max-marker. . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
overlays-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 point-min . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
overriding-local-map . . . . . . . . . . . . . . . . . . . . . . . 357 point-min-marker. . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
overriding-local-map-menu-flag . . . . . . . . . . . 357 pointer (text property) . . . . . . . . . . . . . . . . . . . . . . 623
overriding-terminal-local-map . . . . . . . . . . . . . 357 pointer shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
overwrite-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
pop-mark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
P pop-to-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
package-version, customization keyword . . . . . 186 pop-up-frame-alist . . . . . . . . . . . . . . . . . . . . . . . . . 509
packing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732 pop-up-frame-function . . . . . . . . . . . . . . . . . . . . . . 509
Index 931
x-parse-geometry. . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 Y
x-pointer-shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
x-popup-dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549 y-or-n-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
x-popup-menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548 y-or-n-p-with-timeout . . . . . . . . . . . . . . . . . . . . . . 298
x-resource-class. . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 yank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
x-resource-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 yank suppression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
x-select-enable-clipboard . . . . . . . . . . . . . . . . . 552 yank-pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
x-sensitive-text-pointer-shape . . . . . . . . . . . 550 yank-undo-function . . . . . . . . . . . . . . . . . . . . . . . . . 594
x-server-vendor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
yes-or-no questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
x-server-version. . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
x-set-cut-buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 yes-or-no-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
x-set-selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
x-super-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
X11 keysyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835 Z
XBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
XPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792 zerop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34