Gnu Emacs Lisp Reference Manual: by Bil Lewis, Dan Laliberte, Richard Stallman, The Gnu Manual Group, Et Al
Gnu Emacs Lisp Reference Manual: by Bil Lewis, Dan Laliberte, Richard Stallman, The Gnu Manual Group, Et Al
Gnu Emacs Lisp Reference Manual: by Bil Lewis, Dan Laliberte, Richard Stallman, The Gnu Manual Group, Et Al
Short Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 Lisp Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4 Strings and Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6 Sequences, Arrays, and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . 91
7 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
10 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
11 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
12 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
13 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
14 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
15 Customization Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
16 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
17 Byte Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
18 Debugging Lisp Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
19 Reading and Printing Lisp Objects . . . . . . . . . . . . . . . . . . . . . 323
20 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
21 Command Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
22 Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
23 Major and Minor Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
24 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
25 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
26 Backups and Auto-Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
27 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
28 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
29 Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
30 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
31 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
32 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
33 Non-ASCII Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
ii
Table of Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Lisp History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
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 Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1 Integer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2 Floating-Point Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3 Type Predicates for Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.4 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.5 Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.6 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.7 Rounding Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.8 Bitwise Operations on Integers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.9 Standard Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.10 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.1 Lists and Cons Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.2 Predicates on Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.3 Accessing Elements of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.4 Building Cons Cells and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.5 Modifying List Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.6 Modifying Existing List Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.6.1 Altering List Elements with setcar . . . . . . . . . . . . . . . . . . . . . . . 78
5.6.2 Altering the CDR of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.6.3 Functions that Rearrange Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.7 Using Lists as Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.8 Association Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.9 Property Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.9.1 Property Lists and Association Lists . . . . . . . . . . . . . . . . . . . . . . 89
5.9.2 Property Lists Outside Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.1 Record Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.2 Backward Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.1 Symbol Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.2 Defining Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
9.3 Creating and Interning Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
9.4 Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.4.1 Accessing Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.4.2 Standard Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
10 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.1 Kinds of Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10.1.1 Self-Evaluating Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10.1.2 Symbol Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10.1.3 Classification of List Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.1.4 Symbol Function Indirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.1.5 Evaluation of Function Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.1.6 Lisp Macro Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.1.7 Special Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
10.1.8 Autoloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
10.2 Quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.3 Backquote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.4 Eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
12 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
12.1 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
12.2 Variables that Never Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
12.3 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
12.4 When a Variable is Void . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
12.5 Defining Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
12.6 Tips for Defining Variables Robustly. . . . . . . . . . . . . . . . . . . . . . . . . 175
12.7 Accessing Variable Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
12.8 Setting Variable Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
12.9 Running a function when a variable is changed. . . . . . . . . . . . . . . 179
12.9.1 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
12.10 Scoping Rules for Variable Bindings . . . . . . . . . . . . . . . . . . . . . . . . 179
12.10.1 Dynamic Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
12.10.2 Proper Use of Dynamic Binding . . . . . . . . . . . . . . . . . . . . . . . 181
12.10.3 Lexical Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
12.10.4 Using Lexical Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
12.11 Buffer-Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
12.11.1 Introduction to Buffer-Local Variables . . . . . . . . . . . . . . . . . 185
12.11.2 Creating and Deleting Buffer-Local Bindings . . . . . . . . . . . 186
12.11.3 The Default Value of a Buffer-Local Variable . . . . . . . . . . 189
12.12 File Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
12.13 Directory Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
12.14 Connection Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
12.15 Variable Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
12.16 Variables with Restricted Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
12.17 Generalized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
12.17.1 The setf Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
12.17.2 Defining new setf forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
13 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
13.1 What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
13.2 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
13.2.1 Components of a Lambda Expression . . . . . . . . . . . . . . . . . . . 205
13.2.2 A Simple Lambda Expression Example . . . . . . . . . . . . . . . . . 206
13.2.3 Other Features of Argument Lists . . . . . . . . . . . . . . . . . . . . . . 206
13.2.4 Documentation Strings of Functions . . . . . . . . . . . . . . . . . . . . 208
13.3 Naming a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
13.4 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
13.5 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
13.6 Mapping Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
13.7 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
13.8 Generic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
13.9 Accessing Function Cell Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
13.10 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
13.11 Advising Emacs Lisp Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
13.11.1 Primitives to manipulate advices . . . . . . . . . . . . . . . . . . . . . . 223
13.11.2 Advising Named Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
13.11.3 Ways to compose advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
viii
14 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
14.1 A Simple Example of a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
14.2 Expansion of a Macro Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
14.3 Macros and Byte Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
14.4 Defining Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
14.5 Common Problems Using Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
14.5.1 Wrong Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
14.5.2 Evaluating Macro Arguments Repeatedly . . . . . . . . . . . . . . . 239
14.5.3 Local Variables in Macro Expansions . . . . . . . . . . . . . . . . . . . 241
14.5.4 Evaluating Macro Arguments in Expansion . . . . . . . . . . . . . 241
14.5.5 How Many Times is the Macro Expanded? . . . . . . . . . . . . . . 242
14.6 Indenting Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
16 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
16.1 How Programs Do Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
16.2 Load Suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
16.3 Library Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
16.4 Loading Non-ASCII Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
16.5 Autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
16.5.1 Autoload by Prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
16.5.2 When to Use Autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
16.6 Repeated Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
16.7 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
16.8 Which File Defined a Certain Symbol. . . . . . . . . . . . . . . . . . . . . . . . 275
16.9 Unloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
16.10 Hooks for Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
16.11 Emacs Dynamic Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
ix
20 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
20.1 Introduction to Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
20.2 Reading Text Strings with the Minibuffer . . . . . . . . . . . . . . . . . . . . 335
20.3 Reading Lisp Objects with the Minibuffer . . . . . . . . . . . . . . . . . . . 338
20.4 Minibuffer History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
20.5 Initial Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
20.6 Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
20.6.1 Basic Completion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
20.6.2 Completion and the Minibuffer . . . . . . . . . . . . . . . . . . . . . . . . . 345
20.6.3 Minibuffer Commands that Do Completion . . . . . . . . . . . . . 347
20.6.4 High-Level Completion Functions . . . . . . . . . . . . . . . . . . . . . . . 349
20.6.5 Reading File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
20.6.6 Completion Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
20.6.7 Programmed Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
20.6.8 Completion in Ordinary Buffers . . . . . . . . . . . . . . . . . . . . . . . . 358
20.7 Yes-or-No Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
20.8 Asking Multiple-Choice Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
20.9 Reading a Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
20.10 Minibuffer Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
20.11 Minibuffer Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
20.12 Minibuffer Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
20.13 Recursive Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
20.14 Minibuffer Miscellany . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
22 Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
22.1 Key Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
22.2 Keymap Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
22.3 Format of Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
22.4 Creating Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
22.5 Inheritance and Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
22.6 Prefix Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
22.7 Active Keymaps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
22.8 Searching the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
22.9 Controlling the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
22.10 Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
22.11 Functions for Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
22.12 Changing Key Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
22.13 Remapping Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
xii
24 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
24.1 Documentation Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
24.2 Access to Documentation Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
24.3 Substituting Key Bindings in Documentation . . . . . . . . . . . . . . . . 513
24.4 Text Quoting Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
24.5 Describing Characters for Help Messages . . . . . . . . . . . . . . . . . . . . 516
24.6 Help Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
25 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
25.1 Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
25.1.1 Functions for Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
25.1.2 Subroutines of Visiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
25.2 Saving Buffers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
25.3 Reading from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
25.4 Writing to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
25.5 File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
25.6 Information about Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
25.6.1 Testing Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
25.6.2 Distinguishing Kinds of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
25.6.3 Truenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
25.6.4 File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
25.6.5 Extended File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
25.6.6 Locating Files in Standard Places . . . . . . . . . . . . . . . . . . . . . . . 540
25.7 Changing File Names and Attributes . . . . . . . . . . . . . . . . . . . . . . . . 541
xiv
27 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
27.1 Buffer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
27.2 The Current Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
27.3 Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
27.4 Buffer File Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
27.5 Buffer Modification. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
27.6 Buffer Modification Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
27.7 Read-Only Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
27.8 The Buffer List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
27.9 Creating Buffers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
27.10 Killing Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
27.11 Indirect Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
27.12 Swapping Text Between Two Buffers . . . . . . . . . . . . . . . . . . . . . . . 596
27.13 The Buffer Gap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
28 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
28.1 Basic Concepts of Emacs Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 598
28.2 Windows and Frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
28.3 Window Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
28.4 Resizing Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
28.5 Preserving Window Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
xv
29 Frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
29.1 Creating Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
29.2 Multiple Terminals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
29.3 Frame Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
29.3.1 Frame Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
29.3.2 Frame Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
29.3.3 Frame Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
29.3.4 Frame Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
29.3.5 Implied Frame Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
29.4 Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
29.4.1 Access to Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
29.4.2 Initial Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
29.4.3 Window Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
29.4.3.1 Basic Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
29.4.3.2 Position Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
xvi
30 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
30.1 Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
30.2 Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
30.2.1 Motion by Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
30.2.2 Motion by Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
30.2.3 Motion to an End of the Buffer . . . . . . . . . . . . . . . . . . . . . . . . . 745
30.2.4 Motion by Text Lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
30.2.5 Motion by Screen Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
30.2.6 Moving over Balanced Expressions . . . . . . . . . . . . . . . . . . . . . . 750
30.2.7 Skipping Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
30.3 Excursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
30.4 Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
xvii
31 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
31.1 Overview of Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
31.2 Predicates on Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
31.3 Functions that Create Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
31.4 Information from Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
31.5 Marker Insertion Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
31.6 Moving Marker Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
31.7 The Mark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
31.8 The Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
32 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
32.1 Examining Text Near Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
32.2 Examining Buffer Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
32.3 Comparing Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
32.4 Inserting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
32.5 User-Level Insertion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
32.6 Deleting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
32.7 User-Level Deletion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
32.8 The Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
32.8.1 Kill Ring Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
32.8.2 Functions for Killing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
32.8.3 Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
32.8.4 Functions for Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
32.8.5 Low-Level Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
32.8.6 Internals of the Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
32.9 Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
32.10 Maintaining Undo Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
32.11 Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
32.12 Margins for Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
32.13 Adaptive Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
32.14 Auto Filling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
32.15 Sorting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
32.16 Counting Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
32.17 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
32.17.1 Indentation Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
32.17.2 Indentation Controlled by Major Mode . . . . . . . . . . . . . . . . 796
32.17.3 Indenting an Entire Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
32.17.4 Indentation Relative to Previous Lines . . . . . . . . . . . . . . . . . 799
32.17.5 Adjustable Tab Stops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
32.17.6 Indentation-Based Motion Commands . . . . . . . . . . . . . . . . . 800
32.18 Case Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
32.19 Text Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
32.19.1 Examining Text Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
32.19.2 Changing Text Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
32.19.3 Text Property Search Functions . . . . . . . . . . . . . . . . . . . . . . . 806
32.19.4 Properties with Special Meanings . . . . . . . . . . . . . . . . . . . . . . 808
32.19.5 Formatted Text Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
32.19.6 Stickiness of Text Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . 814
xviii
37 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
37.1 Basic Thread Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
37.2 Mutexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916
37.3 Condition Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
xx
38 Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
38.1 Functions that Create Subprocesses. . . . . . . . . . . . . . . . . . . . . . . . . . 919
38.2 Shell Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921
38.3 Creating a Synchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922
38.4 Creating an Asynchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . 926
38.5 Deleting Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
38.6 Process Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932
38.7 Sending Input to Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
38.8 Sending Signals to Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936
38.9 Receiving Output from Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 938
38.9.1 Process Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 938
38.9.2 Process Filter Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940
38.9.3 Decoding Process Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 942
38.9.4 Accepting Output from Processes . . . . . . . . . . . . . . . . . . . . . . . 942
38.9.5 Processes and Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
38.10 Sentinels: Detecting Process Status Changes . . . . . . . . . . . . . . . . 944
38.11 Querying Before Exit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
38.12 Accessing Other Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
38.13 Transaction Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948
38.14 Network Connections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949
38.15 Network Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
38.16 Datagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
38.17 Low-Level Network Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
38.17.1 make-network-process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
38.17.2 Network Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956
38.17.3 Testing Availability of Network Features . . . . . . . . . . . . . . . 957
38.18 Misc Network Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
38.19 Communicating with Serial Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
38.20 Packing and Unpacking Byte Arrays. . . . . . . . . . . . . . . . . . . . . . . . 961
38.20.1 Describing Data Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
38.20.2 Functions to Unpack and Pack Bytes . . . . . . . . . . . . . . . . . . 963
38.20.3 Examples of Byte Unpacking and Packing . . . . . . . . . . . . . 964
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1203
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 pro-
gramming 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 3.1 of the GNU Emacs Lisp Reference Manual, corresponding to Emacs
version 26.3.
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.
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 version of the edition you are criticizing.
Please send comments and corrections using M-x report-emacs-bug.
Dozens of Lisp implementations have been built over the years, each with its own id-
iosyncrasies. Many of them were inspired by Maclisp, which was written in the 1960s at
MIT’s Project MAC. Eventually the implementers of the descendants of Maclisp came to-
gether and developed a standard for Lisp systems, called Common Lisp. In the meantime,
Gerry Sussman and Guy Steele at MIT developed a simplified but very powerful dialect of
Lisp, called Scheme.
GNU Emacs Lisp is largely inspired by Maclisp, and a little by Common Lisp. If you
know Common Lisp, you will notice many similarities. However, many features of Common
Lisp have been omitted or simplified in order to reduce the memory requirements of GNU
Emacs. Sometimes the simplifications are so drastic that a Common Lisp user might be
very confused. We will occasionally point out how GNU Emacs Lisp differs from Common
Lisp. If you don’t know Common Lisp, don’t worry about it; this manual is self-contained.
A certain amount of Common Lisp emulation is available via the cl-lib library. See
Section “Overview” in Common Lisp Extensions.
Emacs Lisp is not at all influenced by Scheme; but the GNU project has an implementa-
tion of Scheme, called Guile. We use it in all new GNU software that calls for extensibility.
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 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 that 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 12.2 [Constant
Variables], page 169.
booleanp object [Function]
Return non-nil if object is one of the two canonical boolean values: t or nil.
More generally,
(foo w x y...)
≡
(+ (- x w) y...)
By convention, any argument whose name contains the name of a type (e.g., integer,
integer1 or buffer) is expected to be of that type. A plural of a type (such as buffers)
often means a list of objects of that type. An argument named object may be of any type.
(For a list of Emacs object types, see Chapter 2 [Lisp Data Types], page 8.) An argument
with any other sort of name (e.g., new-file) is specific to the function; if the function has a
documentation string, the type of the argument should be described there (see Chapter 24
[Documentation], page 510).
See Section 13.2 [Lambda Expressions], page 205, for a more complete description of
arguments modified by &optional and &rest.
Command, macro, and special form descriptions have the same format, but the word
‘Function’ is replaced by ‘Command’, ‘Macro’, or ‘Special Form’, respectively. Commands
are simply functions that may be called interactively; macros process their arguments dif-
ferently from functions (the arguments are not evaluated), but are presented the same way.
The descriptions of macros and special forms use a more complex notation to specify
optional and repeated arguments, because they can break the argument list down into
separate arguments in more complicated ways. ‘[optional-arg]’ means that optional-arg
is optional and ‘repeated-args...’ stands for zero or more arguments. Parentheses are
used when several arguments are grouped into additional levels of list structure. Here is an
example:
emacs-build-number [Variable]
An integer that increments each time Emacs is built in the same directory (without
cleaning). This is only of relevance when developing Emacs.
1.5 Acknowledgments
This manual was originally written by Robert Krawitz, Bil Lewis, Dan LaLiberte,
Richard M. Stallman 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 support of the Defense Advanced Research Projects Agency, ARPA
Order 6082, arranged by Warren A. Hunt, Jr. of Computational Logic, Inc. Additional
sections have since been written by Miles Bader, Lars Brinkhoff, Chong Yidong, Kenichi
Handa, Lute Kamstra, Juri Linkov, Glenn Morris, Thien-Thi Nguyen, Dan Nicolaescu,
Martin Rudalics, Kim F. Storm, Luc Teirlinck, and Eli Zaretskii, and others.
Corrections were supplied by Drew Adams, Juanma Barranquero, 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, Jesper Harder, 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, Stefan Monnier, Skip Montanaro, John
Gardiner Myers, Thomas A. Peterson, Francesco Potortı̀, Friedrich Pukelsheim, Arnold
D. Robbins, Raul Rockwell, Jason Rumney, Per Starbäck, Shinichirou Sugou, Kimmo
Suominen, Edward Tharp, Bill Trost, Rickard Westman, Jean White, Eduard Wiebe,
Matthew Wilding, Carl Witty, Dale Worley, Rusty Wright, and David D. Zuhn.
For a more complete list of contributors, please see the relevant change log entries in the
Emacs source repository.
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, an unescaped
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 17 [Byte Compilation], page 279). It isn’t meant for source files,
however.
See Section D.7 [Comment Tips], page 1151, for conventions for formatting comments.
You can express the characters control-g, backspace, tab, newline, vertical tab, formfeed,
space, return, del, and escape as ‘?\a’, ‘?\b’, ‘?\t’, ‘?\n’, ‘?\v’, ‘?\f’, ‘?\s’, ‘?\r’, ‘?\d’,
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 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 must add a backslash before any of the characters ‘()[]\;"’, and
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.)
is the character A, ‘?\x1’ is the character C-a, and ?\xe0 is the character à (a with
grave accent). You can use any number of hex digits, so you can represent any character
code in this way.
4. You can specify characters by their character code in octal. An octal escape sequence
consists of a backslash followed by up to three octal digits; thus, ‘?\101’ for the charac-
ter A, ‘?\001’ for the character C-a, and ?\002 for the character C-b. Only characters
up to octal code 777 can be specified this way.
These escape sequences may also be used in strings. See Section 2.3.8.2 [Non-ASCII in
Strings], page 19.
next pair of boxes, the second cons cell. The car of the second cons cell is violet, and its
cdr is the third cons cell. The cdr of the third (and last) cons cell is nil.
Here is another diagram of the same list, (rose violet buttercup), sketched in a dif-
ferent manner:
--------------- ---------------- -------------------
| car | cdr | | car | cdr | | car | cdr |
| rose | o-------->| violet | o-------->| buttercup | nil |
| | | | | | | | |
--------------- ---------------- -------------------
A list with no elements in it is the empty list; it is identical to the symbol nil. In other
words, nil is both a symbol and a list.
Here is the list (A ()), or equivalently (A nil), depicted with boxes and arrows:
--- --- --- ---
| | |--> | | |--> nil
--- --- --- ---
| |
| |
--> A --> nil
Here is a more complex illustration, showing the three-element list, ((pine needles)
oak maple), the first element of which is a two-element list:
--- --- --- --- --- ---
| | |--> | | |--> | | |--> nil
--- --- --- --- --- ---
| | |
| | |
| --> oak --> maple
|
| --- --- --- ---
--> | | |--> | | |--> nil
--- --- --- ---
| |
| |
--> pine --> needles
The same list represented in the second box notation looks like this:
-------------- -------------- --------------
| car | cdr | | car | cdr | | car | cdr |
| o | o------->| oak | o------->| maple | nil |
| | | | | | | | | |
-- | --------- -------------- --------------
|
|
| -------------- ----------------
| | car | cdr | | car | cdr |
------>| pine | o------->| needles | nil |
| | | | | |
-------------- ----------------
Chapter 2: Lisp Data Types 17
For example,
(setq alist-of-colors
'((rose . red) (lily . white) (buttercup . yellow)))
sets the variable alist-of-colors to an alist of three elements. In the first element, rose
is the key and red is the value.
See Section 5.8 [Association Lists], page 85, for a further explanation of alists and for
functions that work on alists. See Chapter 8 [Hash Tables], page 115, for another kind of
lookup table, which is much faster for handling a large number of keys.
The newline character is not special in the read syntax for strings; if you write a new line
between the double-quotes, it becomes a character in the string. But an escaped newline—
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."
See Section 6.4 [Vectors], page 105, for functions that work with vectors.
Primitive functions have no read syntax and print in hash notation with the name of the
subroutine.
(symbol-function 'car) ; Access the function cell
; of the symbol.
⇒ #<subr car>
(subrp (symbol-function 'car)) ; Is this a primitive function?
⇒ t ; Yes.
a garbage collection pass, Emacs calls the finalizer’s associated function object. When
deciding whether a finalizer is reachable, Emacs does not count references from finalizer
objects themselves, allowing you to use finalizers without having to worry about accidentally
capturing references to finalized objects themselves.
Errors in finalizers are printed to *Messages*. Emacs runs a given finalizer object’s
associated function exactly once, even if that function fails.
make-finalizer function [Function]
Make a finalizer that will run function. function will be called after garbage collection
when the returned finalizer object becomes unreachable. If the finalizer object is
reachable only through references from finalizer objects, it does not count as reachable
for the purpose of deciding whether to run function. function will be run once per
finalizer object.
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 596.
Buffers have no read syntax. They print in hash notation, showing the buffer name.
(current-buffer)
⇒ #<buffer objects.texi>
buffer temporarily in a different display style. Overlays have no read syntax, and print in
hash notation, giving the buffer name and range of positions.
See Section 39.9 [Overlays], page 985, for information on how you can create and use
overlays.
char-or-string-p
See Section 4.2 [Predicates for Strings], page 51.
char-table-p
See Section 6.6 [Char-Tables], page 107.
commandp See Section 21.3 [Interactive Call], page 375.
condition-variable-p
See Section 37.3 [Condition Variables], page 917.
consp See Section 5.2 [List-related Predicates], page 68.
custom-variable-p
See Section 15.3 [Variable Definitions], page 247.
floatp See Section 3.3 [Predicates on Numbers], page 37.
fontp See Section 39.12.12 [Low-Level Font], page 1015.
frame-configuration-p
See Section 29.13 [Frame Configurations], page 725.
frame-live-p
See Section 29.7 [Deleting Frames], page 718.
framep See Chapter 29 [Frames], page 683.
functionp
See Chapter 13 [Functions], page 203.
hash-table-p
See Section 8.4 [Other Hash], page 119.
integer-or-marker-p
See Section 31.2 [Predicates on Markers], page 757.
integerp See Section 3.3 [Predicates on Numbers], page 37.
keymapp See Section 22.4 [Creating Keymaps], page 418.
keywordp See Section 12.2 [Constant Variables], page 169.
listp See Section 5.2 [List-related Predicates], page 68.
markerp See Section 31.2 [Predicates on Markers], page 757.
mutexp See Section 37.2 [Mutexes], page 916.
nlistp See Section 5.2 [List-related Predicates], page 68.
number-or-marker-p
See Section 31.2 [Predicates on Markers], page 757.
numberp See Section 3.3 [Predicates on Numbers], page 37.
overlayp See Section 39.9 [Overlays], page 985.
processp See Chapter 38 [Processes], page 919.
recordp See Section 2.3.17 [Record Type], page 23.
Chapter 2: Lisp Data Types 31
sequencep
See Section 6.1 [Sequence Functions], page 91.
string-or-null-p
See Section 4.2 [Predicates for Strings], page 51.
stringp See Section 4.2 [Predicates for Strings], page 51.
subrp See Section 13.9 [Function Cells], page 221.
symbolp See Chapter 9 [Symbols], page 120.
syntax-table-p
See Chapter 35 [Syntax Tables], page 892.
threadp See Section 37.1 [Basic Thread Functions], page 915.
vectorp See Section 6.4 [Vectors], page 105.
wholenump
See Section 3.3 [Predicates on Numbers], page 37.
window-configuration-p
See Section 28.26 [Window Configurations], page 676.
window-live-p
See Section 28.7 [Deleting Windows], page 615.
windowp See Section 28.1 [Basic Windows], page 598.
The most general way to check the type of an object is to call the function type-of.
Recall that each object belongs to one and only one primitive type; type-of tells you which
one (see Chapter 2 [Lisp Data Types], page 8). But type-of knows nothing about non-
primitive types. In most cases, it is more convenient to use type predicates than type-of.
contain the same sequence of character codes and all these codes are in the range 0
through 127 (ASCII).
(equal "asdf" "ASDF")
⇒ nil
However, two distinct buffers are never considered equal, even if their textual contents
are the same.
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).
3 Numbers
GNU Emacs supports two numeric data types: integers and floating-point numbers. Inte-
gers are whole numbers such as −3, 0, 7, 13, and 511. Floating-point numbers are numbers
with fractional parts, such as −4.5, 0.0, and 2.71828. They can also be expressed in ex-
ponential notation: ‘1.5e2’ is the same as ‘150.0’; here, ‘e2’ stands for ten to the second
power, and that is multiplied by 1.5. Integer computations are exact, though they may
overflow. Floating-point computations often involve rounding errors, as the numbers have
a fixed amount of precision.
The IEEE floating-point standard supports positive infinity and negative infinity as
floating-point values. It also provides for a class of values called NaN, or “not a num-
ber”; numerical functions return such values in cases where there is no correct answer.
For example, (/ 0.0 0.0) returns a NaN. Although NaN values carry a sign, for practical
purposes there is no other significant difference between different NaN values in Emacs Lisp.
Here are read syntaxes for these special floating-point values:
infinity ‘1.0e+INF’ and ‘-1.0e+INF’
not-a-number
‘0.0e+NaN’ and ‘-0.0e+NaN’
The following functions are specialized for handling floating-point numbers:
isnan x [Function]
This predicate returns t if its floating-point argument is a NaN, nil otherwise.
frexp x [Function]
This function returns a cons cell (s . e), where s and e are respectively the significand
and exponent of the floating-point number x.
If x is finite, then s is a floating-point number between 0.5 (inclusive) and 1.0 (exclu-
sive), e is an integer, and x = s2e . If x is zero or infinity, then s is the same as x. If
x is a NaN, then s is also a NaN. If x is zero, then e is 0.
ldexp s e [Function]
Given a numeric significand s and an integer exponent e, this function returns the
floating point number s2e .
copysign x1 x2 [Function]
This function copies the sign of x2 to the value of x1, and returns the result. x1 and
x2 must be floating point.
logb x [Function]
This function returns the binary exponent of x. More precisely, the value is the
logarithm base 2 of |x|, rounded down to an integer.
(logb 10)
⇒ 3
(logb 10.0e20)
⇒ 69
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. If divisor is zero (whether integer or floating point), Emacs signals
an arith-error error.
(ceiling 1.7)
⇒ 2
(ceiling -1.2)
⇒ -1
(ceiling -1.7)
⇒ -1
round number &optional divisor [Function]
This returns number, converted to an integer by rounding towards the nearest integer.
Rounding a value equidistant between two integers returns the even integer.
(round 1.2)
⇒ 1
(round 1.7)
⇒ 2
(round -1.2)
⇒ -1
(round -1.7)
⇒ -2
⇒ 0
(+ 1)
⇒ 1
(+ 1 2 3 4)
⇒ 10
- &optional number-or-marker &rest more-numbers-or-markers [Function]
The - function serves two purposes: negation and subtraction. When - has a single
argument, the value is the negative of the argument. When there are multiple ar-
guments, - subtracts each of the more-numbers-or-markers from number-or-marker,
cumulatively. If there are no arguments, the result is 0.
(- 10 1 2 3 4)
⇒ 0
(- 10)
⇒ -10
(-)
⇒ 0
* &rest numbers-or-markers [Function]
This function multiplies its arguments together, and returns the product. When given
no arguments, * returns 1.
(*)
⇒ 1
(* 1)
⇒ 1
(* 1 2 3 4)
⇒ 24
/ number &rest divisors [Function]
With one or more divisors, this function divides number by each divisor in divisors in
turn, and returns the quotient. With no divisors, this function returns 1/number, i.e.,
the multiplicative inverse of number. Each argument may be a number or a marker.
If all the arguments are integers, the result is an integer, obtained by rounding the
quotient towards zero after each division.
(/ 6 2)
⇒ 3
(/ 5 2)
⇒ 2
(/ 5.0 2)
⇒ 2.5
(/ 5 2.0)
⇒ 2.5
(/ 5.0 2.0)
⇒ 2.5
(/ 4.0)
⇒ 0.25
(/ 4)
⇒ 0
Chapter 3: Numbers 43
(/ 25 3 2)
⇒ 4
(/ -17 6)
⇒ -2
If you divide an integer by the integer 0, Emacs signals an arith-error error (see
Section 11.7.3 [Errors], page 160). Floating-point division of a nonzero number by
zero yields either positive or negative infinity (see Section 3.2 [Float Basics], page 36).
always equals dividend, subject to rounding error if either argument is floating point
and to an arith-error if dividend is an integer and divisor is 0. For floor, see
Section 3.5 [Numeric Conversions], page 40.
(lsh 5 1)
⇒ 10
;; Decimal 5 becomes decimal 10.
00000101 ⇒ 00001010
(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
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 536,870,911 produces −2 in the 30-bit implementation:
(lsh 536870911 1) ; left shift
⇒ -2
In binary, the argument looks like this:
;; Decimal 536,870,911
0111...111111 (30 bits total)
which becomes the following when left shifted:
;; Decimal −2
1111...111110 (30 bits total)
ash gives the same results as lsh except when integer1 and count are both negative.
In that case, ash puts ones in the empty bit positions on the left, while lsh puts zeros
in those bit positions.
Thus, with ash, shifting the pattern of bits one place to the right looks like this:
(ash -6 -1) ⇒ -3
;; Decimal −6 becomes decimal −3.
1111...111010 (30 bits total)
⇒
1111...111101 (30 bits total)
In contrast, shifting the pattern of bits one place to the right with lsh looks like this:
(lsh -6 -1) ⇒ 536870909
;; Decimal −6 becomes decimal 536,870,909.
1111...111010 (30 bits total)
⇒
0111...111101 (30 bits total)
Here are other examples:
; 30-bit binary values
(lsh 5 2) ; 5 = 0000...000101
⇒ 20 ; = 0000...010100
(ash 5 2)
⇒ 20
(lsh -5 2) ; -5 = 1111...111011
⇒ -20 ; = 1111...101100
(ash -5 2)
⇒ -20
(lsh 5 -2) ; 5 = 0000...000101
⇒ 1 ; = 0000...000001
(ash 5 -2)
⇒ 1
(lsh -5 -2) ; -5 = 1111...111011
⇒ 268435454
; = 0011...111110
(ash -5 -2) ; -5 = 1111...111011
⇒ -2 ; = 1111...111110
If logand is not passed any argument, it returns a value of −1. This number is an
identity element for logand because its binary representation consists entirely of ones.
If logand is passed just one argument, it returns that argument.
; 30-bit binary values
(logand 14 13 4) ; 14 = 0000...001110
; 13 = 0000...001101
; 4 = 0000...000100
⇒ 4 ; 4 = 0000...000100
(logand)
⇒ -1 ; -1 = 1111...111111
(logior 12 5) ; 12 = 0000...001100
; 5 = 0000...000101
⇒ 13 ; 13 = 0000...001101
(logior 12 5 7) ; 12 = 0000...001100
; 5 = 0000...000101
; 7 = 0000...000111
⇒ 15 ; 15 = 0000...001111
(logxor 12 5) ; 12 = 0000...001100
; 5 = 0000...000101
⇒ 9 ; 9 = 0000...001001
(logxor 12 5 7) ; 12 = 0000...001100
; 5 = 0000...000101
; 7 = 0000...000111
⇒ 14 ; 14 = 0000...001110
expt x y [Function]
This function returns x raised to power y. If both arguments are integers and y is
positive, the result is an integer; in this case, overflow causes truncation, so watch
out. If x is a finite negative number and y is a finite non-integer, expt returns a NaN.
float-e [Variable]
The mathematical constant e (2.71828. . . ).
float-pi [Variable]
The mathematical constant pi (3.14159. . . ).
Chapter 3: Numbers 49
primitives that copy text from strings to buffers or other strings also copy the properties of
the characters being copied.
See Chapter 32 [Text], page 765, for information about functions that display strings
or copy them into buffers. See Section 2.3.3 [Character Type], page 10, and Section 2.3.8
[String Type], page 18, for information about the syntax of characters and strings. See
Chapter 33 [Non-ASCII Characters], page 835, for functions to convert between text repre-
sentations and to encode and decode character codes.
In the above example, the index for ‘a’ is 0, the index for ‘b’ is 1, and the index for ‘c’
is 2. The index 3—which is the fourth character in the string—marks the character
position up to which the substring is copied. Thus, ‘abc’ is copied from the string
"abcdefg".
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 91).
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 802.
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 766), 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.
contained in string1 and string2, but also further rules about relations between these
characters. Usually, it is defined by the locale environment Emacs is running with.
For example, characters with different coding points but the same meaning might be
considered as equal, like different grave accent Unicode characters:
(string-collate-equalp (string ?\uFF40) (string ?\u1FEF))
⇒ t
The optional argument locale, a string, overrides the setting of your current locale
identifier for collation. The value is system dependent; a locale "en_US.UTF-8" is ap-
plicable on POSIX systems, while it would be, e.g., "enu_USA.1252" on MS-Windows
systems.
If ignore-case is non-nil, characters are converted to lower-case before comparing
them.
To emulate Unicode-compliant collation on MS-Windows systems, bind
w32-collate-ignore-punctuation to a non-nil value, since the codeset part of
the locale cannot be "UTF-8" on MS-Windows.
If your system does not support a locale environment, this function behaves like
string-equal.
Do not use this function to compare file names for equality, as filesystems generally
don’t honor linguistic equivalence of strings that collation implements.
Typically grave accent and apostrophe in the format translate to matching curved
quotes, e.g., "Missing ‘%s’" might result in "Missing ‘foo’". See Section 24.4
[Text Quoting Style], page 515, for how to influence or inhibit this translation.
(format-message
"The name of this buffer is ‘%s’." (buffer-name))
⇒ "The name of this buffer is ‘strings.texi’."
(format-message
"The buffer object prints as `%s'." (current-buffer))
⇒ "The buffer object prints as ‘strings.texi’."
By default, format specifications correspond to successive values from objects. Thus, the
first format specification in string uses the first such value, the second format specification
uses the second such value, and so on. Any extra format specifications (those for which
there are no corresponding values) cause an error. Any extra values to be formatted are
ignored.
A format specification can have a field number, which is a decimal number immediately
after the initial ‘%’, followed by a literal dollar sign ‘$’. It causes the format specification to
convert the argument with the given number instead of the next argument. Field numbers
start at 1. A format can contain either numbered or unnumbered format specifications but
not both, except that ‘%%’ can be mixed with numbered specifications.
(format "%2$s, %3$s, %%, %1$s" "x" "y" "z")
⇒ "y, z, %, x"
After the ‘%’ and any field number, you can put certain flag characters.
The flag ‘+’ inserts a plus sign before a positive number, so that it always has a sign.
A space character as flag inserts a space before a positive number. (Otherwise, positive
numbers start with the first digit.) These flags are useful for ensuring that positive numbers
and negative numbers use the same number of columns. They are ignored except for ‘%d’,
‘%e’, ‘%f’, ‘%g’, and if both flags are used, ‘+’ takes precedence.
The flag ‘#’ specifies an alternate form which depends on the format in use. For ‘%o’, it
ensures that the result begins with a ‘0’. For ‘%x’ and ‘%X’, it prefixes the result with ‘0x’
or ‘0X’. For ‘%e’ and ‘%f’, the ‘#’ flag means include a decimal point even if the precision
is zero. For ‘%g’, it always includes a decimal point, and also forces any trailing zeros after
the decimal point to be left in place where they would otherwise be removed.
The flag ‘0’ ensures that the padding consists of ‘0’ characters instead of spaces. This
flag is ignored for non-numerical specification characters like ‘%s’, ‘%S’ and ‘%c’. These
specification characters accept the ‘0’ flag, but still pad with spaces.
Chapter 4: Strings and Characters 63
The flag ‘-’ causes any padding inserted by the width, if specified, to be inserted on the
right rather than the left. If both ‘-’ and ‘0’ are present, the ‘0’ flag is ignored.
(format "%06d is padded on the left with zeros" 123)
⇒ "000123 is padded on the left with zeros"
specify a different case conversion mapping by specifying a case table (see Section 4.9 [Case
Tables], page 65).
These functions do not modify the strings that are passed to them as arguments.
The examples below use the characters ‘X’ and ‘x’ which have ASCII codes 88 and 120
respectively.
(downcase ?X)
⇒ 120
(upcase ?x)
⇒ 88
(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.
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 893).
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"
Note that case conversion is not a one-to-one mapping of codepoints and length of the
result may differ from length of the argument. Furthermore, because passing a character
forces return type to be a character, functions are unable to perform proper substitution
and result may differ compared to treating a one-character string. For example:
(upcase "fi") ; note: single character, ligature "fi"
⇒ "FI"
(upcase ?fi)
⇒ 64257 ; i.e. ?fi
To avoid this, a character must first be converted into a string, using string function,
before being passed to one of the casing functions. Of course, no assumptions on the length
of the result may be made.
Mapping for such special cases are taken from special-uppercase, special-lowercase
and special-titlecase See Section 33.6 [Character Properties], page 840.
See Section 4.5 [Text Comparison], page 55, for functions that compare strings; some of
them ignore case differences, or can optionally ignore case differences.
canonicalize
The canonicalize table maps all of a set of case-related characters into a partic-
ular member of that set.
equivalences
The equivalences table maps each one of a set of case-related characters into
the next character in that set.
In simple cases, all you need to specify is the mapping to lower-case; the three related
tables will be calculated automatically from that one.
For some languages, upper and lower case letters are not in one-to-one correspondence.
There may be two different lower case letters with the same upper case equivalent. In these
cases, you need to specify the maps for both lower case and upper case.
The extra table canonicalize maps each character to a canonical equivalent; any two
characters that are related by case-conversion have the same canonical equivalent character.
For example, since ‘a’ and ‘A’ are related by case-conversion, they should have the same
canonical equivalent character (which should be either ‘a’ for both of them, or ‘A’ for both
of them).
The extra table equivalences is a map that cyclically permutes each equivalence class (of
characters with the same canonical equivalent). (For ordinary ASCII, this would map ‘a’
into ‘A’ and ‘A’ into ‘a’, and likewise for each set of equivalent characters.)
When constructing a case table, you can provide nil for canonicalize; then Emacs fills
in this slot from the lower case and upper case mappings. You can also provide nil for
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 modify the case conversions of ASCII characters; for exam-
ple, in the Turkish language environment, the ASCII capital 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 892. 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.
68
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.
As a special case, if cons-cell is nil, this function returns nil; therefore, any list is a
valid argument. An error is signaled if the argument is not a cons cell or nil.
(cdr '(a b c))
⇒ (b c)
(cdr '())
⇒ nil
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 91.
In addition to the above, 24 additional compositions of car and cdr are defined as
cxxxr and cxxxxr, where each x is either a or d. cadr, caddr, and cadddr pick out the
second, third or fourth elements of a list, respectively. cl-lib provides the same under the
names cl-second, cl-third, and cl-fourth. See Section “List Functions” in Common
Lisp Extensions.
2
There is no strictly equivalent way to add an element to the end of a list. You can use (append listname
(list newelt)), which creates a whole new list by copying listname and adding newelt to its end. Or
you can use (nconc listname (list newelt)), which modifies listname by following all the cdrs and
then replacing the terminating nil. Compare this to adding an element to the beginning of a list with
cons, which neither copies nor modifies the list.
Chapter 5: Lists 73
trees
⇒ (pine oak)
more-trees
⇒ (maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
⇒ t
Chapter 5: Lists 74
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 91.
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 13.5 [Calling Functions], page 212), 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])
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.
Normally, when tree is anything other than a cons cell, copy-tree simply returns
tree. However, if vecp is non-nil, it copies vectors too (and operates recursively on
their elements).
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 necessary.
The ordering information is stored in a hash table on symbol’s list-order property.
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:
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:
Chapter 5: Lists 79
Here is an example of replacing the cdr of a list with a different list. All but the first
element of the list are removed in favor of a different sequence of elements. The first element
is unchanged, because it resides in the car of the list, and is not reached via the cdr.
(setq x '(1 2 3))
⇒ (1 2 3)
(setcdr x '(4))
⇒ (4)
x
⇒ (1 4)
Chapter 5: Lists 80
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)))
Emacs Lisp does not have them, the cl-lib library provides versions. See
Section “Lists as Sets” in Common Lisp Extensions.
memq object list [Function]
This function tests to see whether object is a member of list. If it is, memq returns a
list starting with the first occurrence of object. Otherwise, it returns nil. The letter
‘q’ in memq says that it uses eq to compare object against the elements of the list. For
example:
(memq 'b '(a b c b a))
⇒ (b c b a)
(memq '(2) '((1) (2))) ; (2) and (2) are not eq.
⇒ nil
delq object list [Function]
This function destructively removes all elements eq to object from list, and returns
the resulting list. The letter ‘q’ in delq says that it uses eq to compare object against
the elements of the list, like memq and remq.
Typically, when you invoke delq, you should use the return value by assigning it to
the variable which held the original list. The reason for this is explained below.
The delq function deletes elements from the front of the list by simply advancing down
the list, and returning a sublist that starts after those elements. For example:
(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 79).
(setq sample-list '(a b c (4)))
⇒ (a b c (4))
(delq 'a sample-list)
⇒ (b c (4))
sample-list
⇒ (a b c (4))
(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))
If you want to delete elements that are equal to a given value, use delete (see below).
Chapter 5: Lists 83
For example:
(setq l '((2) (1) (2)))
(delete '(2) l)
⇒ ((1))
l
⇒ ((2) (1))
;; If you want to change l reliably,
;; write (setq l (delete '(2) l)).
(setq l '((2) (1) (2)))
(delete '(1) l)
⇒ ((2) (2))
l
⇒ ((2) (2))
;; In this case, it makes no difference whether you set l,
;; but you should do so for the sake of the other case.
(delete '(2) [(2) (1) (2)])
⇒ [(1)]
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.
See also the function add-to-list, in Section 5.5 [List Variables], page 75, for a way to
add an element to a list stored in a variable and used as a set.
Chapter 5: Lists 85
3
This usage of “key” is not related to the term “key sequence”; it means a value used to look up an item
in a table. In this case, the table is the alist, and the alist associations are the items.
Chapter 5: Lists 86
⇒ (oak . acorns)
(cdr (assoc 'oak trees))
⇒ acorns
(assoc 'birch trees)
⇒ nil
Here is another example, in which the keys and values are not symbols:
(setq needles-per-cluster
'((2 "Austrian Pine" "Red Pine")
(3 "Pitch Pine")
(5 "White Pine")))
The function assoc-string is much like assoc except that it ignores certain differences
between strings. See Section 4.5 [Text Comparison], page 55.
This is a generalized variable (see Section 12.17 [Generalized Variables], page 200)
that can be used to change a value with setf. When using it to set a value, optional
argument remove non-nil means to remove key’s association from alist if the new
value is eql to default.
(3 "Pitch Pine")
(5 "White Pine"))
This example shows how copy-alist makes it possible to change the associations of
one copy without affecting the other:
(setcdr (assq 3 copy) '("Martian Vacuum Pine"))
(cdr (assq 3 needles-per-cluster))
⇒ ("Pitch Pine")
6.1 Sequences
This section describes functions that accept any kind of sequence.
(length ())
⇒ 0
(length "foobar")
⇒ 6
(length [1 2 3])
⇒ 3
(length (make-bool-vector 5 nil))
⇒ 5
This function does not work for dotted lists. Trying to copy a circular list may cause
an infinite loop.
See also append in Section 5.4 [Building Lists], page 72, concat in Section 4.3 [Cre-
ating Strings], page 51, and vconcat in Section 6.5 [Vector Functions], page 105, for
other ways to copy sequences.
(setq bar '(1 2))
⇒ (1 2)
(setq x (vector 'foo bar))
⇒ [foo (1 2)]
(setq y (copy-sequence x))
⇒ [foo (1 2)]
(eq x y)
⇒ nil
(equal x y)
⇒ t
(eq (elt x 1) (elt y 1))
⇒ t
(reverse x)
⇒ "yzzyx"
x
⇒ "xyzzy"
The argument predicate must be a function that accepts two arguments. It is called
with two elements of sequence. To get an increasing order sort, the predicate should
return non-nil if the first element is “less” than the second, or nil if not.
The comparison function predicate must give reliable results for any given pair of
arguments, at least within a single call to sort. It must be antisymmetric; that is,
if a is less than b, b must not be less than a. It must be transitive—that is, if a is
less than b, and b is less than c, then a must be less than c. If you use a comparison
function which does not meet these requirements, the result of sort is unpredictable.
The destructive aspect of sort for lists is that it rearranges the cons cells forming
sequence by changing cdrs. A nondestructive sort function would create new cons
cells to store the elements in their sorted order. If you wish to make a sorted copy
without destroying the original, copy it first with copy-sequence and then sort.
Sorting does not change the cars of the cons cells in sequence; the cons cell that
originally contained the element a in sequence still has a in its car after sorting,
but it now appears in a different position in the list due to the change of cdrs. For
example:
(setq nums '(1 3 2 6 5 4 0))
⇒ (1 3 2 6 5 4 0)
(sort nums '<)
⇒ (0 1 2 3 4 5 6)
nums
⇒ (1 2 3 4 5 6)
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 '<))
For the better understanding of what stable sort is, consider the following vector
example. After sorting, all items whose car is 8 are grouped at the beginning of
vector, but their relative order is preserved. All items whose car is 9 are grouped
at the end of vector, but their relative order is also preserved:
(setq
vector
(vector '(8 . "xxx") '(9 . "aaa") '(8 . "bbb") '(9 . "zzz")
'(9 . "ppp") '(8 . "ttt") '(8 . "eee") '(9 . "fff")))
⇒ [(8 . "xxx") (9 . "aaa") (8 . "bbb") (9 . "zzz")
(9 . "ppp") (8 . "ttt") (8 . "eee") (9 . "fff")]
(sort vector (lambda (x y) (< (car x) (car y))))
⇒ [(8 . "xxx") (8 . "bbb") (8 . "ttt") (8 . "eee")
(9 . "aaa") (9 . "zzz") (9 . "ppp") (9 . "fff")]
See Section 32.15 [Sorting], page 791, for more functions that perform sorting. See
documentation in Section 24.2 [Accessing Documentation], page 511, for a useful
example of sort.
Chapter 6: Sequences, Arrays, and Vectors 96
The seq.el library provides the following additional sequence manipulation macros and
functions, prefixed with seq-. To use them, you must first load the seq library.
All functions defined in this library are free of side-effects; i.e., they do not modify any
sequence (list, vector, or string) that you pass as an argument. Unless otherwise stated, the
result is a sequence of the same type as the input. For those functions that take a predicate,
this should be a function of one argument.
The seq.el library can be extended to work with additional types of sequential
data-structures. For that purpose, all functions are defined using cl-defgeneric. See
Section 13.8 [Generic Functions], page 217, for more details about using cl-defgeneric
for adding extensions.
the number of sequences. Mapping stops at the end of the shortest sequence, and the
returned value is a list.
(seq-mapn #'+ '(2 4 6) '(20 40 60))
⇒ (22 44 66)
(seq-mapn #'concat '("moskito" "bite") ["bee" "sting"])
⇒ ("moskitobee" "bitesting")
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, the time
to access an element of a list is proportional to the position of that element in the list.
Emacs defines four types of array, all one-dimensional: strings (see Section 2.3.8 [String
Type], page 18), vectors (see Section 2.3.9 [Vector Type], page 20), bool-vectors (see
Section 2.3.11 [Bool-Vector Type], page 21), and char-tables (see Section 2.3.10 [Char-
Table Type], page 21). Vectors and char-tables can hold elements of any type, but strings
can only hold characters, and bool-vectors can only hold t and nil.
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—i.e., 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 104).
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 802.
• 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 50.
Chapter 6: Sequences, Arrays, and Vectors 104
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.8.1 [Key Sequence Input], page 397.
(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.
Chapter 6: Sequences, Arrays, and Vectors 105
6.4 Vectors
A vector is a general-purpose array whose elements can be any Lisp objects. (By contrast,
the elements of a string can only be characters. See Chapter 4 [Strings and Characters],
page 50.) Vectors are used in Emacs for many purposes: as key sequences (see Section 22.1
[Key Sequences], page 415), as symbol-lookup tables (see Section 9.3 [Creating Symbols],
page 122), as part of the representation of a byte-compiled function (see Chapter 17 [Byte
Compilation], page 279), and more.
Like other arrays, vectors use zero-origin indexing: the first element has index 0.
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 10.1.1 [Self-Evaluating Forms], page 130.
Here are examples illustrating these principles:
(setq avector [1 two '(three) "four" [five]])
⇒ [1 two (quote (three)) "four" [five]]
(eval avector)
⇒ [1 two (quote (three)) "four" [five]]
(eq avector (eval avector))
⇒ t
(vectorp [a])
⇒ t
(vectorp "asdf")
⇒ nil
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])
Chapter 6: Sequences, Arrays, and Vectors 107
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.
Like vectors, char-tables are constants when evaluated, and can hold elements of any type.
Each char-table has a subtype, a symbol, which serves two purposes:
• The subtype provides an easy way to tell what the char-table is for. For instance,
display tables are char-tables with display-table as the subtype, and syntax tables
are char-tables with syntax-table as the subtype. The subtype can be queried using
the function char-table-subtype, described below.
• The subtype controls the number of extra slots in the char-table. This number is
specified by the subtype’s char-table-extra-slots symbol property (see Section 9.4
[Symbol Properties], page 125), whose value should be an integer between 0 and 10. If
the subtype has no such symbol property, the char-table has no extra slots.
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.
A char-table can specify an element value for a single character code; it can also specify
a value for an entire character set.
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.
Several functions work specifically with bool-vectors; aside from that, you manipulate
them with same functions used for other kinds of arrays.
make-bool-vector length initial [Function]
Return a new bool-vector of length elements, each one initialized to initial.
bool-vector &rest objects [Function]
This function creates and returns a bool-vector whose elements are the arguments,
objects.
bool-vector-p object [Function]
This returns t if object is a bool-vector, and nil otherwise.
There are also some bool-vector set operation functions, described below:
bool-vector-exclusive-or a b &optional c [Function]
Return bitwise exclusive or of bool vectors a and b. If optional argument c is given,
the result of this operation is stored into c. All arguments should be bool vectors of
the same length.
bool-vector-union a b &optional c [Function]
Return bitwise or of bool vectors a and b. If optional argument c is given, the result
of this operation is stored into c. All arguments should be bool vectors of the same
length.
bool-vector-intersection a b &optional c [Function]
Return bitwise and of bool vectors a and b. If optional argument c is given, the result
of this operation is stored into c. All arguments should be bool vectors of the same
length.
Chapter 6: Sequences, Arrays, and Vectors 110
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)))
112
7 Records
The purpose of records is to allow programmers to create objects with new types that are
not built into Emacs. They are used as the underlying representation of cl-defstruct and
defclass instances.
Internally, a record object is much like a vector; its slots can be accessed using aref and
it can be copied using copy-sequence. However, the first slot is used to hold its type as
returned by type-of. Also, in the current implementation records can have at most 4096
slots, whereas vectors can be much larger. Like arrays, records use zero-origin indexing:
the first slot has index 0.
The type slot should be a symbol or a type descriptor. If it’s a type descriptor, the
symbol naming its type will be returned; Section 2.3.18 [Type Descriptors], page 23. Any
other kind of object is returned as-is.
The printed representation of records is ‘#s’ followed by a list specifying the contents.
The first list element must be the record type. The following elements are the record slots.
To avoid conflicts with other type names, Lisp programs that define new types of records
should normally use the naming conventions of the package where these record types are
introduced for the names of the types. Note that the names of the types which could
possibly conflict might not be known at the time the package defining a record type is
loaded; they could be loaded at some future point in time.
A record is considered a constant for evaluation: the result of evaluating it is the same
record. This does not evaluate or even examine the slots. See Section 10.1.1 [Self-Evaluating
Forms], page 130.
8 Hash Tables
A hash table is a very fast kind of lookup table, somewhat like an alist (see Section 5.8
[Association Lists], page 85) 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 a special printed representation, which
consists of ‘#s’ followed by a list specifying the hash table properties and contents. See
Section 8.1 [Creating Hash], page 115. (Hash notation, the initial ‘#’ character used in the
printed representations of objects with no read representation, has nothing to do with hash
tables. See Section 2.1 [Printed Representation], page 8.)
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 9.3 [Creating Symbols], page 122).
: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 approximately that much to the nominal size. If rehash-size is
floating point, it had better be greater than 1, and the hash table grows
by multiplying the old size by approximately 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
Chapter 8: Hash Tables 117
If two objects obj1 and obj2 are eql, then (sxhash-eql obj1) and (sxhash-eql
obj2) are the same integer.
This example creates a hash table whose keys are strings that are compared case-
insensitively.
(defun case-fold-string= (a b)
(eq t (compare-strings a nil nil b nil nil t)))
(defun case-fold-string-hash (a)
(sxhash-equal (upcase a)))
(define-hash-table-test 'case-fold
'case-fold-string= 'case-fold-string-hash)
9 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 12 [Variables],
page 169, and Chapter 13 [Functions], page 203. 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:
The property list cell normally should hold a correctly formatted property list. To get a
symbol’s property list, use the function symbol-plist. See Section 9.4 [Symbol Properties],
page 125.
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’.
Because each symbol has separate value and function cells, variables names and function
names do not conflict. For example, the symbol buffer-file-name has a value (the name
of the file being visited in the current buffer) as well as a function definition (a primitive
function that returns the name of the file):
buffer-file-name
⇒ "/gnu/elisp/symbols.texi"
(symbol-function 'buffer-file-name)
⇒ #<subr buffer-file-name>
These definitions also act as guides for programming tools. For example, the C-h f and
C-h v commands create help buffers containing links to the relevant variable, function, or
macro definitions. See Section “Name Help” in The GNU Emacs Manual.
Common Lisp note: Unlike Common Lisp, Emacs Lisp does not provide for
interning a single symbol 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
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
Chapter 9: Symbols 124
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.
face-documentation
The value stores the documentation string of the named face. This is set auto-
matically by defface. See Section 39.12.2 [Defining Faces], page 1001.
history-length
The value, if non-nil, specifies the maximum minibuffer history length for the
named history list variable. See Section 20.4 [Minibuffer History], page 340.
interactive-form
The value is an interactive form for the named function. Normally, you should
not set this directly; use the interactive special form instead. See Section 21.3
[Interactive Call], page 375.
menu-enable
The value is an expression for determining whether the named menu item should
be enabled in menus. See Section 22.17.1.1 [Simple Menu Items], page 440.
mode-class
If the value is special, the named major mode is special. See Section 23.2.1
[Major Mode Conventions], page 456.
permanent-local
If the value is non-nil, the named variable is a buffer-local variable whose value
should not be reset when changing major modes. See Section 12.11.2 [Creating
Buffer-Local], page 186.
permanent-local-hook
If the value is non-nil, the named function should not be deleted from the
local value of a hook variable when changing major modes. See Section 23.1.2
[Setting Hooks], page 454.
pure If the value is non-nil, the named function is considered to be pure (see
Section 13.1 [What Is a Function], page 203). Calls with constant arguments
can be evaluated at compile time. This may shift run time errors to compile
time. Not to be confused with pure storage (see Section E.2 [Pure Storage],
page 1157).
risky-local-variable
If the value is non-nil, the named variable is considered risky as a file-local
variable. See Section 12.12 [File Local Variables], page 191.
safe-function
If the value is non-nil, the named function is considered generally safe for
evaluation. See Section 13.16 [Function Safety], page 233.
safe-local-eval-function
If the value is non-nil, the named function is safe to call in file-local evaluation
forms. See Section 12.12 [File Local Variables], page 191.
safe-local-variable
The value specifies a function for determining safe file-local values for the named
variable. See Section 12.12 [File Local Variables], page 191.
Chapter 9: Symbols 128
side-effect-free
A non-nil value indicates that the named function is free of side effects (see
Section 13.1 [What Is a Function], page 203), so the byte compiler may ig-
nore a call whose value is unused. If the property’s value is error-free, the
byte compiler may even delete such unused calls. In addition to byte compiler
optimizations, this property is also used for determining function safety (see
Section 13.16 [Function Safety], page 233).
variable-documentation
If non-nil, this specifies the named variable’s documentation string. This is set
automatically by defvar and related functions. See Section 39.12.2 [Defining
Faces], page 1001.
129
10 Evaluation
The evaluation of expressions in Emacs Lisp is performed by the Lisp interpreter—a pro-
gram 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 a form or expression1 . The fact that
forms are data objects and not merely text is one of the fundamental differences 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.
In subsequent sections, we will describe the details of what evaluation means for each
kind of form.
It is very common to read a Lisp form and then evaluate the form, 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 to specify whether this object is a form to be evaluated,
or serves some entirely different purpose. See Section 19.3 [Input Functions], page 325.
Evaluation is a recursive process, and evaluating a form often involves evaluating parts
within that form. For instance, when you evaluate a function call form such as (car x),
Emacs first evaluates the argument (the subform x). After evaluating the argument, Emacs
executes the function (car), and if the function is written in Lisp, execution works by
evaluating the body of the function (in this example, however, car is not a Lisp function; it
is a primitive function implemented in C). See Chapter 13 [Functions], page 203, for more
information about functions and function calls.
Evaluation takes place in a context called the environment, which consists of the current
values and bindings of all Lisp variables (see Chapter 12 [Variables], page 169).2 Whenever
a form refers to a variable without creating a new binding for it, the variable evaluates to
the value given by the current environment. Evaluating a form may also temporarily alter
the environment by binding variables (see Section 12.3 [Local Variables], page 170).
Evaluating a form may also make changes that persist; these changes are called side
effects. An example of a form that produces a side effect is (setq foo 1).
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 execute that command. Executing
the command usually involves evaluation, if the command is written in Lisp; however, this
step is not considered a part of command key interpretation. See Chapter 21 [Command
Loop], page 368.
1
It is sometimes also referred to as an S-expression or sexp, but we generally do not use this terminology
in this manual.
2
This definition of “environment” is specifically not intended to include all the data that can affect the
result of a program.
Chapter 10: Evaluation 130
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 12.2 [Constant Variables], page 169.
evaluated. Instead, these elements themselves are used as the arguments of the macro. The
macro definition computes a replacement form, called the expansion of the macro, to be
evaluated in place of the original form. The expansion may be any sort of form: a self-
evaluating constant, a symbol, or a list. If the expansion is itself a macro call, this process
of expansion repeats until some other sort of form results.
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 14 [Macros], page 236, for a complete description of Emacs Lisp macros.
Here is a list, in alphabetical order, of all of the special forms in Emacs Lisp with a
reference to where each is described.
and see Section 11.3 [Combining Conditions], page 143,
catch see Section 11.7.1 [Catch and Throw], page 158,
cond see Section 11.2 [Conditionals], page 141,
condition-case
see Section 11.7.3.3 [Handling Errors], page 163,
Chapter 10: Evaluation 134
10.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.
The way to arrange for an autoload object to appear as a symbol’s function definition is
described in Section 16.5 [Autoload], page 268.
Chapter 10: Evaluation 135
10.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.)
Because quote is used so often in programs, Lisp provides a convenient read syntax for
it. An apostrophe character (‘'’) followed by a Lisp object (in read syntax) expands to a
list whose first element is quote, and whose second element is the object. Thus, the read
syntax 'x is an abbreviation for (quote x).
Here are some examples of expressions that use quote:
(quote (+ 1 2))
⇒ (+ 1 2)
(quote foo)
⇒ foo
'foo
⇒ foo
''foo
⇒ (quote foo)
'(quote foo)
⇒ (quote foo)
['foo]
⇒ [(quote foo)]
Other quoting constructs include function (see Section 13.7 [Anonymous Functions],
page 216), which causes an anonymous lambda expression written in Lisp to be compiled,
and ‘`’ (see Section 10.3 [Backquote], page 135), which is used to quote only part of a list,
while computing and substituting other parts.
10.3 Backquote
Backquote constructs allow you to quote a list, but selectively evaluate elements of that
list. In the simplest case, it is identical to the special form quote 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. The Emacs Lisp evaluator evaluates the argument of ‘,’, and puts the value in
the list structure:
`(a list of ,(+ 2 3) elements)
⇒ (a list of 5 elements)
Chapter 10: Evaluation 136
Substitution with ‘,’ is allowed at deeper levels of the list structure also. For example:
`(1 2 (3 ,(+ 4 5)))
⇒ (1 2 (3 9))
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)
10.4 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. Often eval is not needed
and something else should be used instead. For example, to get the value of a variable, while
eval works, symbol-value is preferable; or rather than store expressions in a property list
that then need to go through eval, it is better to store functions instead that are then
passed to funcall.
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 16 [Loading], page 263).
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.
using the default dynamic scoping rule. If it is t, that means to use the lexical scoping
rule. The value of lexical can also be a non-empty alist specifying a particular lexical
environment for lexical bindings; however, this feature is only useful for specialized
purposes, such as in Emacs Lisp debuggers. See Section 12.10.3 [Lexical Binding],
page 182.
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
(setq bar 'baz)
⇒ baz
;; Here eval receives argument foo
(eval 'foo)
⇒ bar
;; Here eval receives argument bar, which is the value of foo
(eval foo)
⇒ baz
The number of currently active calls to eval is limited to max-lisp-eval-depth (see
below).
buffer-file-name (see Section 27.4 [Buffer File Name], page 585). If unibyte is
non-nil, read converts strings to unibyte whenever possible.
eval-current-buffer is an alias for this command.
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, C-x C-e, and similar evaluation commands
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)
139
11 Control Structures
A Lisp program consists of a set of expressions, or forms (see Section 10.1 [Forms], page 130).
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 14 [Macros], page 236).
11.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.
11.2 Conditionals
Conditional control structures choose among alternatives. Emacs Lisp has five conditional
forms: if, which is much the same as in other languages; when and unless, which are vari-
ants of if; cond, which is a generalized case statement; and pcase, which is a generalization
of cond (see Section 11.4 [Pattern-Matching Conditional], page 144).
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 11.1
[Sequencing], page 140.)
Chapter 11: Control Structures 142
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 this example, true is not printed because print is never called:
(if nil
(print 'true)
'very-false)
⇒ very-false
when condition then-forms. . . [Macro]
This is a variant of if where there are no else-forms, and possibly several then-forms.
In particular,
(when condition a b c)
is entirely equivalent to
(if condition (progn a b c) nil)
unless condition forms. . . [Macro]
This is a variant of if where there is no then-form:
(unless condition a b c)
is entirely equivalent to
(if condition nil
a b c)
cond clause. . . [Special Form]
cond chooses among an arbitrary number of alternatives. Each clause in the cond
must be a list. The car of this list is the condition; the remaining elements, if any,
the body-forms. Thus, a clause looks like this:
(condition body-forms...)
cond tries the clauses in textual order, by evaluating the condition of each clause. If
the value of condition is non-nil, the clause succeeds; then cond evaluates its body-
forms, and returns the value of the last of body-forms. Any remaining clauses are
ignored.
If the value of condition is nil, the clause fails, so the cond moves on to the following
clause, trying its condition.
A clause may also look like this:
(condition)
Then, if condition is non-nil when tested, the cond form returns the value of
condition.
If every condition evaluates to nil, so that every clause fails, cond returns nil.
The following example has four clauses, which test for the cases where the value of x
is a number, string, buffer and symbol, respectively:
(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)))
Chapter 11: Control Structures 143
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))
Note that (car foo) is not executed if (consp foo) returns nil, thus avoiding an
error.
and expressions can also be written using either if or cond. Here’s how:
(and arg1 arg2 arg3)
≡
(if arg1 (if arg2 arg3))
≡
(cond (arg1 (cond (arg2 arg3))))
or conditions. . . [Special Form]
The or special form tests whether at least one of the conditions is true. It works by
evaluating all the conditions one by one in the order written.
If any of the conditions evaluates to a non-nil value, then the result of the or must
be non-nil; so or returns right away, ignoring the remaining conditions. The value
it returns is the non-nil value of the condition just evaluated.
If all the conditions turn out nil, then the or expression returns nil. Just (or),
with no conditions, returns nil, appropriate because all the conditions turned out
nil. (Think about it; which one did not?)
For example, this expression tests whether x is either nil or the integer zero:
(or (eq x nil) (eq x 0))
Like the and construct, or can be written in terms of cond. For example:
(or arg1 arg2 arg3)
≡
(cond (arg1)
(arg2)
(arg3))
You could almost write or in terms of if, but not quite:
(if arg1 arg1
(if arg2 arg2
arg3))
This is not completely equivalent because it can evaluate arg1 or arg2 twice. By
contrast, (or arg1 arg2 arg3) never evaluates any argument more than once.
• The cl-case macro chooses among alternatives by evaluating the equality of its first
argument against a set of specific values.
Its limitations are two-fold:
1. The equality tests use eql.
2. The values must be known and written in advance.
These render cl-case unsuitable for strings or compound data structures (e.g., lists or
vectors). (cond doesn’t have these limitations, but it has others, see above.)
Conceptually, the pcase macro borrows the first-arg focus of cl-case and the clause-
processing flow of cond, replacing condition with a generalization of the equality test which
is a variant of pattern matching, and adding facilities so that you can concisely express
a clause’s predicate, and arrange to share let-bindings between a clause’s predicate and
body-forms.
The concise expression of a predicate is known as a pattern. When the predicate, called
on the value of the first arg, returns non-nil, we say that “the pattern matches the value”
(or sometimes “the value matches the pattern”).
Each pattern has to be a pcase pattern, which can use either one of the core patterns
defined below, or one of the patterns defined via pcase-defmacro (see Section 11.4.2 [Ex-
tending pcase], page 151).
The rest of this subsection describes different forms of core patterns, presents some
examples, and concludes with important caveats on using the let-binding facility provided
by some pattern forms. A core pattern can have the following forms:
_ Matches any expval. This is also known as don’t care or wildcard.
'val Matches if expval equals val. The comparison is done as if by equal (see
Section 2.7 [Equality Predicates], page 32).
keyword
integer
string Matches if expval equals the literal object. This is a special case of 'val, above,
possible because literal objects of these types are self-quoting.
symbol Matches any expval, and additionally let-binds symbol to expval, such that
this binding is available to body-forms (see Section 12.10.1 [Dynamic Binding],
page 180).
Chapter 11: Control Structures 146
"key:NUMBER", return NUMBER (a string). Otherwise, return the list ("149" default).”
First, the traditional implementation (see Section 34.3 [Regular Expressions], page 868):
(defun grok/traditional (obj)
(if (and (stringp obj)
(string-match "^key:\\([[:digit:]]+\\)$" obj))
(match-string 1 obj)
(list "149" 'default)))
Let’s consider the situation where obj is not a string, or it is a string but has the wrong
form. In this case, one of the pred (lines 3-5) fails to match, thus and (line 2) fails to match,
thus or (line 1) proceeds to try sub-pattern let (line 8).
First, let evaluates (list "149" 'default) to get ("149" default), the exprval, and
then tries to match exprval against pattern val. Since that is a symbol pattern, it matches
unconditionally and additionally binds val to exprval. Now that let has matched, or
matches.
Note how both and and let sub-patterns finish in the same way: by trying (always
successfully) to match against the symbol pattern val, in the process binding val. Thus,
or always matches and control always passes to the body form (line 9). Because that is the
last body form in a successfully matched pcase clause, it is the value of pcase and likewise
the return value of grok/pcase (see Section 13.1 [What Is a Function], page 203).
1. When symbol occurs more than once in seqpat, the second and subsequent occurrences
do not expand to re-binding, but instead expand to an equality test using eq.
The following example features a pcase form with two clauses and two seqpat, A and
B. Both A and B first check that expval is a pair (using pred), and then bind symbols
to the car and cdr of expval (using one app each).
For A, because symbol st is mentioned twice, the second mention becomes an equality
test using eq. On the other hand, B uses two separate symbols, s1 and s2, both of
which become independent bindings.
(defun grok (object)
(pcase object
((and (pred consp) ; seqpat A
(app car st) ; first mention: st
(app cdr st)) ; second mention: st
(list 'eq st))
((and (pred consp) ; seqpat B
(app car s1) ; first mention: s1
(app cdr s2)) ; first mention: s2
(list 'not-eq s1 s2))))
Enter an integer: 42
error Symbol’s value as variable is void: o-num
Enter an integer: 149
error Symbol’s value as variable is void: e-num
Evaluating body form (list e-num o-num) signals error. To distinguish between sub-
patterns, you can use another symbol, identical in name in all sub-patterns but differing
in value. Reworking the above example:
(pcase (read-number "Enter an integer: ")
((and num ; line 1
(or (and (pred evenp) ; line 2
(let spin 'even)) ; line 3
(let spin 'odd))) ; line 4
(list spin num))) ; line 5
Enter an integer: 42
⇒ (even 42)
Enter an integer: 149
⇒ (odd 149)
Line 1 “factors out” the expval binding with and and symbol (in this case, num). On
line 2, or begins in the same way as before, but instead of binding different symbols,
uses let twice (lines 3-4) to bind the same symbol spin in both sub-patterns. The
value of spin distinguishes the sub-patterns. The body form references both symbols
(line 5).
,pattern Matches if the corresponding element of expval matches pattern. Note that
pattern is any kind that pcase supports. (In the example above, second-elem
is a symbol core pattern; it therefore matches anything, and let-binds
second-elem.)
The corresponding element is the portion of expval that is in the same structural position
as the structural position of qpat in the backquote-style pattern. (In the example above,
the corresponding element of second-elem is the second element of expval.)
Here is an example of using pcase to implement a simple interpreter for a little expression
language (note that this requires lexical binding for the lambda expression in the fn clause
to properly capture body and arg (see Section 12.10.3 [Lexical Binding], page 182):
(defun evaluate (form env)
(pcase form
(`(add ,x ,y) (+ (evaluate x env)
(evaluate y env)))
(`(call ,fun ,arg) (funcall (evaluate fun env)
(evaluate arg env)))
(`(fn ,arg ,body) (lambda (val)
(evaluate body (cons (cons arg val)
env))))
((pred numberp) form)
((pred symbolp) (cdr (assq form env)))
(_ (error "Syntax error: %S" form))))
The first three clauses use backquote-style patterns. `(add ,x ,y) is a pattern that checks
that form is a three-element list starting with the literal symbol add, then extracts the
second and third elements and binds them to symbols x and y, respectively. The clause
body evaluates x and y and adds the results. Similarly, the call clause implements a
function call, and the fn clause implements an anonymous function definition.
The remaining clauses use core patterns. (pred numberp) matches if form is a number.
On match, the body evaluates it. (pred symbolp) matches if form is a symbol. On match,
the body looks up the symbol in env and returns its association. Finally, _ is the catch-all
pattern that matches anything, so it’s suitable for reporting syntax errors.
Here are some sample programs in this small language, including their evaluation results:
(evaluate '(add 1 2) nil) ⇒ 3
(evaluate '(add x y) '((x . 1) (y . 2))) ⇒ 3
(evaluate '(call (fn x (add 1 x)) 2) nil) ⇒ 3
(evaluate '(sub 1 2) nil) ⇒ error
This will not only extract x and y but will additionally test that my-list is a list
containing exactly 3 elements and whose first element is the symbol add. If any of those
tests fail, pcase will immediately return nil without calling message.
Extraction of multiple values stored in an object is known as destructuring. Using pcase
patterns allows to perform destructuring binding, which is similar to a local binding (see
Section 12.3 [Local Variables], page 170), but gives values to multiple elements of a variable
by extracting those values from an object of compatible structure.
The macros described in this section use pcase patterns to perform destructuring bind-
ing. The condition of the object to be of compatible structure means that the object must
match the pattern, because only then the object’s subfields can be extracted. For example:
(pcase-let ((`(add ,x ,y) my-list))
(message "Contains %S and %S" x y))
does the same as the previous example, except that it directly tries to extract x and y from
my-list without first verifying if my-list is a list which has the right number of elements
and has add as its first element. The precise behavior when the object does not actually
match the pattern is undefined, although the body will not be silently skipped: either an
error is signaled or the body is run with some of the variables potentially bound to arbitrary
values like nil.
The pcase patterns that are useful for destructuring bindings are generally those de-
scribed in Section 11.4.3 [Backquote Patterns], page 152, since they express a specification
of the structure of objects that will match.
For an alternative facility for destructuring binding, see [seq-let], page 102.
11.5 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.
nil if result is omitted. For example, here is how you could use dolist to define the
reverse function:
(defun reverse (list)
(let (value)
(dolist (elt list value)
(setq value (cons elt value)))))
dotimes (var count [result]) body. . . [Macro]
This construct executes body once for each integer from 0 (inclusive) to count (exclu-
sive), binding the variable var to the integer for the current iteration. Then it returns
the value of evaluating result, or nil if result is omitted. Here is an example of using
dotimes to do something 100 times:
(dotimes (i 100)
(insert "I will not obey absurd orders\n"))
11.6 Generators
A generator is a function that produces a potentially-infinite stream of values. Each time
the function produces a value, it suspends itself and waits for a caller to request the next
value.
iter-defun name args [doc] [declare] [interactive] body. . . [Macro]
iter-defun defines a generator function. A generator function has the same signature
as a normal function, but works differently. Instead of executing body when called,
a generator function returns an iterator object. That iterator runs body to generate
values, emitting a value and pausing where iter-yield or iter-yield-from appears.
When body returns normally, iter-next signals iter-end-of-sequence with body’s
result as its condition data.
Any kind of Lisp code is valid inside body, but iter-yield and iter-yield-from
cannot appear inside unwind-protect forms.
iter-lambda args [doc] [interactive] body. . . [Macro]
iter-lambda produces an unnamed generator function that works just like a generator
function produced with iter-defun.
iter-yield value [Macro]
When it appears inside a generator function, iter-yield indicates that the current
iterator should pause and return value from iter-next. iter-yield evaluates to the
value parameter of next call to iter-next.
iter-yield-from iterator [Macro]
iter-yield-from yields all the values that iterator produces and evaluates to the
value that iterator’s generator function returns normally. While it has control, itera-
tor receives values sent to the iterator using iter-next.
To use a generator function, first call it normally, producing a iterator object. An
iterator is a specific instance of a generator. Then use iter-next to retrieve values from
this iterator. When there are no more values to pull from an iterator, iter-next raises an
iter-end-of-sequence condition with the iterator’s final value.
Chapter 11: Control Structures 157
It’s important to note that generator function bodies only execute inside calls to
iter-next. A call to a function defined with iter-defun produces an iterator; you must
drive this iterator with iter-next for anything interesting to happen. Each call to a
generator function produces a different iterator, each with its own state.
Some convenience functions are provided to make working with iterators easier:
The Common Lisp loop facility also contains features for working with iterators. See
Section “Loop Facility” in Common Lisp Extensions.
The following piece of code demonstrates some important principles of working with
iterators.
(require 'generator)
(iter-defun my-iter (x)
(iter-yield (1+ (iter-yield (1+ x))))
;; Return normally
-1)
(iter-end-of-sequence
;; Prints -1, which my-iter returned normally
(print (cdr x)))))
(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 12.3
[Local Variables], page 170). Likewise, throw restores the buffer and position saved by
save-excursion (see Section 30.3 [Excursions], page 752), and the narrowing status saved
by save-restriction. It also runs any cleanups established with the unwind-protect
special form when it exits that form (see Section 11.7.4 [Cleanups], page 167).
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.13 [Recursive Editing],
page 410).
Chapter 11: Control Structures 159
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. The cl-lib library provides
versions of some of these. See Section “Blocks and Exits” in Common Lisp
Extensions.
(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.
Now let’s change the argument given to catch2:
(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.
11.7.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 11.7.4 [Cleanups], page 167.) 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 11.7.1 [Catch and Throw],
page 158.
Most errors are signaled automatically within Lisp primitives which you call for other
purposes, such as if you try to take the car of an integer or move forward a character at
the end of the buffer. You can also signal errors explicitly with the functions error and
signal.
Quitting, which happens when the user types C-g, is not considered an error, but it is
handled almost like an error. See Section 21.11 [Quitting], page 407.
Every error specifies an error message, one way or another. The message should state
what is wrong (“File does not exist”), not how things ought to be (“File must exist”).
The convention in Emacs Lisp is that error messages should start with a capital letter, but
should not end with any sort of punctuation.
error format-string &rest args [Function]
This function signals an error with an error message constructed by applying
format-message (see Section 4.7 [Formatting Strings], page 60) to format-string
and args.
These examples show typical uses of error:
(error "That is an error -- try something else")
error That is an error -- try something else
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 11.7.3.3 [Handling Errors], page 163).
The function signal never returns.
(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 289) 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.
Chapter 11: Control Structures 163
Once Emacs decides that a certain handler handles the error, it returns control to that
handler. To do so, Emacs unbinds all variable bindings made by binding constructs that
are being exited, and executes the cleanups of all unwind-protect forms that are being
exited. Once control arrives at the handler, the body of the handler executes normally.
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.
Error signaling and handling have some resemblance to throw and catch (see
Section 11.7.1 [Catch and Throw], page 158), 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).
((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, and which describes also a list of condition names (see Section 11.7.3.4 [Error
Symbols], page 166). 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.
Chapter 11: Control Structures 165
If var is nil, that means no variable is bound. Then the error symbol and associated
data are not available to the handler.
where err is the error description variable, the first argument to condition-case
whose error condition you want to re-throw. See [Definition of signal], page 161.
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.
(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 (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 from error:
(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
In addition to its parents, the error symbol has a message which is a string to be printed
when that error is signaled but not handled. If that message is not valid, the error message
‘peculiar error’ is used. See [Definition of signal], page 161.
Internally, the set of parents is stored in the error-conditions property of the error
symbol and the message is stored in the error-message property of the error symbol.
Here is how we define a new error symbol, new-error:
(define-error 'new-error "A new error" 'my-own-errors)
This error has several condition names: new-error, the narrowest classification; my-own-
errors, which we imagine is a wider classification; and all the conditions of my-own-errors
which should include 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 161) 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 its 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 1192, for a list of the main error symbols and
their conditions.
For example, here we make an invisible buffer for temporary use, and make sure to kill
it before finishing:
(let ((buffer (get-buffer-create " *temp*")))
(with-current-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
a save-current-buffer 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 583). 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 38 [Processes], page 919) 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.
169
12 Variables
A variable is a name used in a program to stand for a value. In Lisp, each variable is
represented by a Lisp symbol (see Chapter 9 [Symbols], page 120). The variable name is
simply the symbol’s name, and the variable’s value is stored in the symbol’s value cell1 .
See Section 9.1 [Symbol Components], page 120. In Emacs Lisp, the use of a symbol as a
variable is independent of its use as a function name.
As previously noted in this manual, a Lisp program is represented primarily by Lisp
objects, and only secondarily as text. The textual form of a Lisp program is given by the
read syntax of the Lisp objects that constitute the program. Hence, the textual form of a
variable in a Lisp program is written using the read syntax for the symbol representing the
variable.
whose name starts with ‘:’), if it is interned in the standard obarray, except that setting
such a symbol to itself is not an error.
nil ≡ 'nil
⇒ nil
(setq nil 500)
error Attempt to set constant symbol: nil
These constants are fundamentally different from the constants defined using the
defconst special form (see Section 12.5 [Defining Variables], page 173). A defconst form
serves to inform human readers that you do not intend to change the value of a variable,
but Emacs does not raise an error if you actually change it.
A small number of additional symbols are made read-only for various practical reasons.
These include enable-multibyte-characters, most-positive-fixnum, most-negative-
fixnum, and a few others. Any attempt to set or bind these also signals a setting-constant
error.
any given point in the execution of a program is the most recently-created binding for that
variable that still exists. For details about dynamic scoping, and an alternative scoping rule
called lexical scoping, See Section 12.10 [Variable Scoping], page 179.
The special forms let and let* exist to create local bindings:
let (bindings. . . ) forms. . . [Special Form]
This special form sets up local bindings for a certain set of variables, as specified by
bindings, and then evaluates all of the forms in textual order. Its return value is the
value of the last form in forms. The local bindings set up by let will be in effect only
within the body of forms.
Each of the bindings is either (i) a symbol, in which case that symbol is locally bound
to nil; or (ii) a list of the form (symbol value-form), in which case symbol is locally
bound to the result of evaluating value-form. If value-form is omitted, nil is used.
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)
On the other hand, the order of bindings is unspecified: in the following example,
either 1 or 2 might be printed.
(let ((x 1)
(x 2))
(print x))
Therefore, avoid binding a variable more than once in a single let form.
let* (bindings. . . ) forms. . . [Special Form]
This special form is like let, but it binds each variable right after computing its local
value, before computing the local value for the next variable. Therefore, an expression
in bindings can refer to the preceding symbols bound in this let* form. Compare
the following example with the example above for let.
(setq y 2)
⇒ 2
(let* ((y 1)
(z y)) ; Use the just-established value of y.
(list y z))
⇒ (1 1)
Here is a complete list of the other facilities that create local bindings:
• Function calls (see Chapter 13 [Functions], page 203).
• Macro calls (see Chapter 14 [Macros], page 236).
Chapter 12: Variables 172
If value is specified, and symbol is void (i.e., it has no dynamically bound value; see
Section 12.4 [Void Variables], page 172), then value is evaluated and symbol is set to
the result. But if symbol is not void, value is not evaluated, and symbol’s value is
left unchanged. If value is omitted, the value of symbol is not changed in any case.
Note that specifying a value, even nil, marks the variable as special permanently.
Whereas if value is omitted then the variable is only marked special locally (i.e. within
the current lexical scope, or file if at the top-level). This can be useful for suppressing
byte compilation warnings, see Section 17.6 [Compiler Errors], page 284.
If symbol has a buffer-local binding in the current buffer, defvar acts on the default
value, which is buffer-independent, rather than the buffer-local binding. It sets the
default value if the default value is void. See Section 12.11 [Buffer-Local Variables],
page 185.
If symbol is already lexically bound (e.g., if the defvar form occurs in a let form with
lexical binding enabled), then defvar sets the dynamic value. The lexical binding
remains in effect until its binding construct exits. See Section 12.10 [Variable Scoping],
page 179.
When you evaluate a top-level defvar 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.
If the doc-string argument is supplied, it specifies the documentation string for the
variable (stored in the symbol’s variable-documentation property). See Chapter 24
[Documentation], page 510.
Here are some examples. This form defines foo but does not initialize it:
(defvar foo)
⇒ foo
This example initializes the value of bar to 23, and gives it a documentation string:
(defvar bar 23
"The normal weight of a bar.")
⇒ bar
The defvar form returns symbol, but it is normally used at top level in a file where
its value does not matter.
For a more elaborate example of using defvar without a value, see [Local defvar
example], page 184.
defconst symbol value [doc-string] [Special Form]
This special form defines symbol as a value and initializes it. It informs a person
reading your code that symbol has a standard global value, established here, that
should not be changed by the user or by other programs. Note that symbol is not
evaluated; the symbol to be defined must appear explicitly in the defconst.
The defconst form, like defvar, marks the variable as special, meaning that it
should always be dynamically bound (see Section 12.10 [Variable Scoping], page 179).
In addition, it marks the variable as risky (see Section 12.12 [File Local Variables],
page 191).
defconst always evaluates value, and sets the value of symbol to the result. If symbol
does have a buffer-local binding in the current buffer, defconst sets the default value,
Chapter 12: Variables 175
not the buffer-local value. (But you should not be making buffer-local bindings for a
symbol that is defined with defconst.)
An example of the use of defconst is Emacs’s definition of float-pi—the math-
ematical constant pi, which ought not to be changed by anyone (attempts by the
Indiana State Legislature notwithstanding). As the second form illustrates, however,
defconst is only advisory.
(defconst float-pi 3.141592653589793 "The value of Pi.")
⇒ float-pi
(setq float-pi 3)
⇒ float-pi
float-pi
⇒ 3
Warning: If you use a defconst or defvar special form while the variable has a local
binding (made with let, or a function argument), it sets the local binding rather than the
global binding. This is not what you usually want. To prevent this, use these special forms
at top level in a file, where normally no local binding is in effect, and make sure to load the
file before making a local binding for the variable.
‘...-command’
The value is a whole shell command.
‘...-switches’
The value specifies options for a command.
‘prefix--...’
The variable is intended for internal use and is defined in the file prefix.el.
(Emacs code contributed before 2018 may follow other conventions, which are
being phased out.)
‘...-internal’
The variable is intended for internal use and is defined in C code. (Emacs code
contributed before 2018 may follow other conventions, which are being phased
out.)
When you define a variable, always consider whether you should mark it as safe or risky;
see Section 12.12 [File Local Variables], page 191.
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.
Chapter 12: Variables 177
(symbol-value 'abracadabra)
⇒ 5
The value of the setq form is the value of the last form.
(setq x (1+ 2))
⇒ 3
x ; x now has a global value.
⇒ 3
(let ((x 5))
(setq x 6) ; The local binding of x is set.
x)
⇒ 6
x ; The global value is unchanged.
⇒ 3
Note that the first form is evaluated, then the first symbol is set, then the second
form is evaluated, then the second symbol is set, and so on:
(setq x 10 ; Notice that x is set before
y (1+ x)) ; the value of y is computed.
⇒ 11
12.9.1 Limitations
There are a couple of ways in which a variable could be modified (or at least appear to be
modified) without triggering a watchpoint.
Since watchpoints are attached to symbols, modification to the objects contained within
variables (e.g., by a list modification function see Section 5.6 [Modifying Lists], page 77) is
not caught by this mechanism.
Additionally, C code can modify the value of variables directly, bypassing the watchpoint
mechanism.
A minor limitation of this feature, again because it targets symbols, is that only variables
of dynamic scope may be watched. This poses little difficulty, since modifications to lexical
variables can be discovered easily by inspecting the code within the scope of the variable
(unlike dynamic variables, which can be modified by any code at all, see Section 12.10
[Variable Scoping], page 179).
By default, the local bindings that Emacs creates are dynamic bindings. Such a binding
has dynamic scope, meaning that any part of the program can potentially access the variable
binding. It also has dynamic extent, meaning that the binding lasts only while the binding
construct (such as the body of a let form) is being executed.
Emacs can optionally create lexical bindings. A lexical binding has lexical scope, meaning
that any reference to the variable must be located textually within the binding construct2 .
It also has indefinite extent, meaning that under some circumstances the binding can live on
even after the binding construct has finished executing, by means of special objects called
closures.
The following subsections describe dynamic binding and lexical binding in greater detail,
and how to enable lexical binding in Emacs Lisp programs.
Dynamic bindings have dynamic scope and extent, as shown by the following example:
(defun getx ()
x) ; x is used free in this function.
(getx)
⇒ -99
The function getx refers to x. This is a free reference, in the sense that there is no binding
for x within that defun construct itself. When we call getx from within a let form in
which x is (dynamically) bound, it retrieves the local value (i.e., 1). But when we call getx
outside the let form, it retrieves the global value (i.e., −99).
Here is another example, which illustrates setting a dynamically bound variable using
setq:
2
With some exceptions; for instance, a lexical binding can also be accessed from the Lisp debugger.
Chapter 12: Variables 181
(defun addx ()
(setq x (1+ x))) ; Add 1 to x and return its new value.
(addx)
⇒ -98
Dynamic binding is implemented in Emacs Lisp in a simple way. Each symbol has a
value cell, which specifies its current dynamic value (or absence of value). See Section 9.1
[Symbol Components], page 120. When a symbol is given a dynamic local binding, Emacs
records the contents of the value cell (or absence thereof) in a stack, and stores the new
local value in the value cell. When the binding construct finishes executing, Emacs pops
the old value off the stack, and puts it in the value cell.
• If a variable has no global definition, use it as a local variable only within a binding
construct, such as the body of the let form where the variable was bound. If this
convention is followed consistently throughout a program, the value of the variable will
not affect, nor be affected by, any uses of the same variable symbol elsewhere in the
program.
• Otherwise, define the variable with defvar, defconst (see Section 12.5 [Defining Vari-
ables], page 173), or defcustom (see Section 15.3 [Variable Definitions], page 247).
Usually, the definition should be at top-level in an Emacs Lisp file. As far as possible,
it should include a documentation string which explains the meaning and purpose of
the variable. You should also choose the variable’s name to avoid name conflicts (see
Section D.1 [Coding Conventions], page 1142).
Then you can bind the variable anywhere in a program, knowing reliably what the
effect will be. Wherever you encounter the variable, it will be easy to refer back to
the definition, e.g., via the C-h v command (provided the variable definition has been
loaded into Emacs). See Section “Name Help” in The GNU Emacs Manual.
For example, it is common to use local bindings for customizable variables like
case-fold-search:
Chapter 12: Variables 182
(defun search-for-abc ()
"Search for the string \"abc\", ignoring case differences."
(let ((case-fold-search t))
(re-search-forward "abc")))
(defun getx ()
x) ; x is used free in this function.
(funcall my-ticker)
⇒ 1
(funcall my-ticker)
⇒ 2
(funcall my-ticker)
⇒ 3
lexical-binding [Variable]
If this buffer-local variable is non-nil, Emacs Lisp files and buffers are evaluated
using lexical binding instead of dynamic binding. (However, special variables are still
dynamically bound; see below.) If nil, dynamic binding is used for all local variables.
This variable is typically set for a whole Emacs Lisp file, as a file local variable (see
Section 12.12 [File Local Variables], page 191). Note that unlike other such variables,
this one must be set in the first line of a file.
When evaluating Emacs Lisp code directly using an eval call, lexical binding is enabled if
the lexical argument to eval is non-nil. See Section 10.4 [Eval], page 136.
Chapter 12: Variables 184
Even when lexical binding is enabled, certain variables will continue to be dynamically
bound. These are called special variables. Every variable that has been defined with
defvar, defcustom or defconst is a special variable (see Section 12.5 [Defining Variables],
page 173). All other variables are subject to lexical binding.
Using defvar without a value, it is possible to bind a variable dynamically just in one
file, or in just one part of a file while still binding it lexically elsewhere. For example:
(let (_)
(defvar x) ; Let-bindings of x will be dynamic within this let.
(let ((x -99)) ; This is a dynamic binding of x.
(defun get-dynamic-x ()
x)))
(let (_)
(defvar x)
(let ((x 'dynamic))
(list (get-lexical-x)
(get-dynamic-x))))
⇒ (lexical dynamic)
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.
A buffer-local variable cannot be made terminal-local (see Section 29.2 [Multiple Termi-
nals], page 685).
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.
It is an error to make a constant or a read-only variable buffer-local. See Section 12.2
[Constant Variables], page 169.
If the variable is terminal-local (see Section 29.2 [Multiple Terminals], page 685), this
function signals an error. Such variables cannot have buffer-local bindings as well.
Warning: do not use make-local-variable for a hook variable. The hook vari-
ables are automatically made buffer-local as needed if you use the local argument to
add-hook or remove-hook.
kill-all-local-variables [Function]
This function eliminates all the buffer-local variable bindings of the current buffer
except for variables marked as permanent and local hook functions that have a non-
nil permanent-local-hook property (see Section 23.1.2 [Setting Hooks], page 454).
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.
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 453.
A variable can be let-bound (see Section 12.3 [Local Variables], page 170) to a value.
This makes its global value shadowed by the binding; default-value will then return the
value from that binding, not the global value, and set-default will be prevented from
setting the global value (it will change the let-bound value instead). The following two
functions allow to reference the global value even if it’s shadowed by a let-binding.
inhibit-local-variables-regexps [Variable]
This is a list of regular expressions. If a file has a name matching an element of this
list, then it is not scanned for any form of file-local variable. For examples of why
you might want to use this, see Section 23.2.2 [Auto Major Mode], page 459.
file-local-variables-alist [Variable]
This buffer-local variable holds the alist of file-local variable settings. Each element of
the alist is of the form (var . value), where var is a symbol of the local variable and
value is its value. When Emacs visits a file, it first collects all the file-local variables
into this alist, and then the hack-local-variables function applies them one by
one.
before-hack-local-variables-hook [Variable]
Emacs calls this hook immediately before applying file-local variables stored in
file-local-variables-alist.
Chapter 12: Variables 193
hack-local-variables-hook [Variable]
Emacs calls this hook immediately after it finishes applying file-local variables stored
in file-local-variables-alist.
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 have safe-local-
variable properties; these include fill-column, fill-prefix, and indent-tabs-mode.
For boolean-valued variables that are safe, use booleanp as the property value.
If you want to define safe-local-variable properties for variables defined in C source
code, add the names and the properties of those variables to the list in the “Safe local
variables” section of files.el.
When defining a user option using defcustom, you can set its safe-local-variable
property by adding the arguments :safe function to defcustom (see Section 15.3 [Variable
Definitions], page 247). However, a safety predicate defined using :safe will only be known
once the package that contains the defcustom is loaded, which is often too late. As an
alternative, you can use the autoload cookie (see Section 16.5 [Autoload], page 268) to
assign the option its safety predicate, like this:
;;;###autoload (put 'var 'safe-local-variable 'pred)
The safe value definitions specified with autoload are copied into the package’s autoloads
file (loaddefs.el for most packages bundled with Emacs), and are known to Emacs since
the beginning of a session.
safe-local-variable-values [User Option]
This variable provides another way to mark some variable values as safe. It is a list
of cons cells (var . val), where var is a variable name and val is a value which is
safe for that variable.
When Emacs asks the user whether or not to obey a set of file-local variable specifica-
tions, the user can choose to mark them as safe. Doing so adds those variable/value
pairs to safe-local-variable-values, and saves it to the user’s custom file.
safe-local-variable-p sym val [Function]
This function returns non-nil if it is safe to give sym the value val, based on the
above criteria.
Some variables are considered risky. If a variable is risky, it is never entered auto-
matically into safe-local-variable-values; Emacs always queries before setting a risky
variable, unless the user explicitly allows a value by customizing safe-local-variable-
values directly.
Any variable whose name has a non-nil risky-local-variable property is
considered risky. When you define a user option using defcustom, you can set its
risky-local-variable property by adding the arguments :risky value to defcustom
(see Section 15.3 [Variable Definitions], page 247). In addition, any 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 automatically considered risky. The variables ‘font-lock-keywords’,
‘font-lock-keywords’ followed by a digit, and ‘font-lock-syntactic-keywords’ are
also considered risky.
Chapter 12: Variables 194
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.
The ‘Eval:’ “variable” is also a potential loophole, so Emacs normally asks for confir-
mation before handling it.
dir-locals-file [Constant]
This constant is the name of the file where Emacs expects to find the directory-
local variables. The name of the file is .dir-locals.el3 . A file by that name in
a directory causes Emacs to apply its settings to any file in that directory or any
of its subdirectories (optionally, you can exclude subdirectories; see below). If some
of the subdirectories have their own .dir-locals.el files, Emacs uses the settings
from the deepest file it finds starting from the file’s directory and moving up the
directory tree. This constant is also used to derive the name of a second dir-locals
file .dir-locals-2.el. If this second dir-locals file is present, then that is loaded
instead of .dir-locals.el. This is useful when .dir-locals.el is under version
3
The MS-DOS version of Emacs uses _dir-locals.el instead, due to limitations of the DOS filesystems.
Chapter 12: Variables 195
control in a shared repository and cannot be used for personal customizations. The
file specifies local variables as a specially formatted list; see Section “Per-directory
Local Variables” in The GNU Emacs Manual, for more details.
hack-dir-local-variables [Function]
This function reads the .dir-locals.el file and stores the directory-local vari-
ables in file-local-variables-alist that is local to the buffer visiting any file
in the directory, without applying them. It also stores the directory-local settings in
dir-locals-class-alist, where it defines a special class for the directory in which
.dir-locals.el file was found. This function works by calling dir-locals-set-
class-variables and dir-locals-set-directory-class, described below.
hack-dir-local-variables-non-file-buffer [Function]
This function looks for directory-local variables, and immediately applies them in
the current buffer. It is intended to be called in the mode commands for non-file
buffers, such as Dired buffers, to let them obey directory-local variable settings. For
non-file buffers, Emacs looks for directory-local variables in default-directory and
its parent directories.
dir-locals-class-alist [Variable]
This alist holds the class symbols and the associated variable settings. It is updated
by dir-locals-set-class-variables.
Chapter 12: Variables 196
dir-locals-directory-cache [Variable]
This alist holds directory names, their assigned class names, and modification times of
the associated directory local variables file (if there is one). The function dir-locals-
set-directory-class updates this list.
enable-dir-local-variables [Variable]
If nil, directory-local variables are ignored. This variable may be useful for modes
that want to ignore directory-locals while still respecting file-local variables (see
Section 12.12 [File Local Variables], page 191).
(connection-local-set-profile-variables
'remote-ksh
'((shell-file-name . "/bin/ksh")
(shell-command-switch . "-c")
(shell-interactive-switch . "-i")
(shell-login-switch . "-l")))
(connection-local-set-profile-variables
'remote-null-device
'((null-device . "/dev/null")))
connection-local-profile-alist [Variable]
This alist holds the connection profile symbols and the associated variable settings.
It is updated by connection-local-set-profile-variables.
:machine. The property value of :application is a symbol, all other property values
are strings. All properties are optional; if criteria is nil, it always applies. Example:
(connection-local-set-profiles
'(:application 'tramp :protocol "ssh" :machine "localhost")
'remote-bash 'remote-null-device)
(connection-local-set-profiles
'(:application 'tramp :protocol "sudo"
:user "root" :machine "localhost")
'remote-ksh 'remote-null-device)
If criteria is nil, it applies for all remote connections. Therefore, the example above
would be equivalent to
(connection-local-set-profiles
'(:application 'tramp :protocol "ssh" :machine "localhost")
'remote-bash)
(connection-local-set-profiles
'(:application 'tramp :protocol "sudo"
:user "root" :machine "localhost")
'remote-ksh)
(connection-local-set-profiles
nil 'remote-null-device)
Any connection profile of profiles must have been already defined by
connection-local-set-profile-variables.
connection-local-criteria-alist [Variable]
This alist contains connection criteria and their assigned profile names. The function
connection-local-set-profiles updates this list.
connection-local-variables-alist
⇒ ((null-device . "/dev/null")
(shell-login-switch . "-l")
(shell-interactive-switch . "-i")
(shell-command-switch . "-c")
(shell-file-name . "/bin/bash"))
(with-connection-local-profiles '(remote-perl)
do something useful)
enable-connection-local-variables [Variable]
If nil, connection-local variables are ignored. This variable shall be changed tem-
porarily only in special modes.
The optional argument access-type, if non-nil, should specify the kind of access that
will trigger obsolescence warnings; it can be either get or set.
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
byte-boolean-vars [Variable]
This variable holds a list of all variables of type DEFVAR_BOOL.
Variables of type DEFVAR_INT can take on only integer values. Attempting to assign
them any other value will result in an error:
(setq undo-limit 1000.0)
error Wrong type argument: integerp, 1000.0
The following Lisp forms are the forms in Emacs that will work as generalized variables,
and so may appear in the place argument of setf:
• A symbol. In other words, (setf x y) is exactly equivalent to (setq x y), and setq
itself is strictly speaking redundant given that setf exists. Most programmers will
continue to prefer setq for setting simple variables, though, for stylistic and histor-
ical reasons. The macro (setf x y) actually expands to (setq x y), so there is no
performance penalty for using it in compiled code.
• A call to any of the following standard Lisp functions:
aref cddr symbol-function
car elt symbol-plist
caar get symbol-value
cadr gethash
cdr nth
cdar nthcdr
• A call to any of the following Emacs-specific functions:
alist-get process-get
Chapter 12: Variables 201
frame-parameter process-sentinel
terminal-parameter window-buffer
keymap-parent window-display-table
match-data window-dedicated-p
overlay-get window-hscroll
overlay-start window-parameter
overlay-end window-point
process-buffer window-start
process-filter default-value
setf signals an error if you pass a place form that it does not know how to handle.
Note that for nthcdr, the list argument of the function must itself be a valid place form.
For example, (setf (nthcdr 0 foo) 7) will set foo itself to 7.
The macros push (see Section 5.5 [List Variables], page 75) and pop (see Section 5.3
[List Elements], page 69) can manipulate generalized variables, not just lists. (pop place)
removes and returns the first element of the list stored in place. It is analogous to (prog1
(car place) (setf place (cdr place))), except that it takes care to evaluate all subforms
only once. (push x place) inserts x at the front of the list stored in place. It is analogous
to (setf place (cons x place)), except for evaluation of the subforms. Note that push
and pop on an nthcdr place can be used to insert or delete at any position in a list.
The cl-lib library defines various extensions for generalized variables, including addi-
tional setf places. See Section “Generalized Variables” in Common Lisp Extensions.
This macro expands the form (setf (name args...) value) by first binding the
setf argument forms (value args...) according to arglist, and then executing body.
body should return a Lisp form that does the assignment, and finally returns the value
that was set. An example of using this macro is:
(gv-define-setter caar (val x) `(setcar (car ,x) ,val))
For more control over the expansion, see the macro gv-define-expander. The macro
gv-letplace can be useful in defining macros that perform similarly to setf; for example,
the incf macro of Common Lisp. Consult the source file gv.el for more details.
Common Lisp note: Common Lisp defines another way to specify the setf
behavior of a function, namely setf functions, whose names are lists (setf
name) rather than symbols. For example, (defun (setf foo) ...) defines the
function that is used when setf is applied to foo. Emacs does not support
this. It is a compile-time error to use setf on a form that has not already had
an appropriate expansion defined. In Common Lisp, this is not an error since
the function (setf func) might be defined later.
203
13 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.
− Functions that determine the argument list dynamically, as part of their code.
Unlike functionp, the next three functions do not treat a symbol as its function definition.
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 works like func-arity, but only for built-in functions and without symbol
indirection. It signals an error for non-built-in functions. We recommend to use
func-arity instead.
The documentation string is a Lisp string object placed within the function definition
to describe the function for the Emacs help facilities. See Section 13.2.4 [Function Docu-
mentation], page 208.
The interactive declaration is a list of the form (interactive code-string). This
declares how to provide arguments if the function is used interactively. Functions with
this declaration are called commands; they can be called using M-x or bound to a key.
Functions not intended to be called in this way should not have interactive declarations.
See Section 21.2 [Defining Commands], page 369, for how to write an interactive declaration.
The rest of the elements are the body of the function: the Lisp code to do the work of
the function (or, as a Lisp programmer would say, “a list of Lisp forms to evaluate”). The
value returned by the function is the value returned by the last element of the body.
To specify optional arguments that may be omitted when a function is called, simply
include the keyword &optional before the optional arguments. To specify a list of zero or
more extra arguments, include the keyword &rest before one final argument.
Thus, the complete syntax for an argument list is as follows:
(required-vars...
[&optional optional-vars...]
[&rest rest-var])
The square brackets indicate that the &optional and &rest clauses, and the variables that
follow them, are optional.
A call to the function requires one actual argument for each of the required-vars. There
may be actual arguments for zero or more of the optional-vars, and there cannot be any
actual arguments beyond that unless the lambda list uses &rest. In that case, there may
be any number of extra actual arguments.
If actual arguments for the optional and rest variables are omitted, then they always
default to nil. There is no way for the function to distinguish between an explicit argument
of nil and an omitted argument. However, the body of the function is free to consider nil
an abbreviation for some other meaningful value. This is what substring does; nil as the
third argument to substring means to use the length of the string supplied.
Common Lisp note: Common Lisp allows the function to specify what default
value to use when an optional argument is omitted; Emacs Lisp always uses
nil. Emacs Lisp does not support supplied-p variables that tell you whether
an argument was explicitly passed.
For example, an argument list that looks like this:
(a b &optional c d &rest e)
binds a and b to the first two actual arguments, which are required. If one or two more
arguments are provided, c and d are bound to them respectively; any arguments after the
first four are collected into a list and e is bound to that list. Thus, if there are only two
arguments, c, d and e are nil; if two or three arguments, d and e are nil; if four arguments
or fewer, e is nil. Note that exactly five arguments with an explicit nil argument provided
for e will cause that nil argument to be passed as a list with one element, (nil), as with
any other single value for e.
There is no way to have required arguments following optional ones—it would not make
sense. To see why this must be so, suppose that c in the example were optional and d
were required. Suppose three actual arguments are given; which variable would the third
argument be for? Would it be used for the c, or for d? One can argue for both possibilities.
Similarly, it makes no sense to have any more arguments (either required or optional) after
a &rest argument.
Here are some examples of argument lists and proper calls:
(funcall (lambda (n) (1+ n)) ; One required:
1) ; requires exactly one argument.
⇒ 2
(funcall (lambda (n &optional n1) ; One required and one optional:
(if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments.
1 2)
Chapter 13: Functions 208
⇒ 3
(funcall (lambda (n &rest ns) ; One required and one rest:
(+ n (apply '+ ns))) ; 1 or more arguments.
1 2 3 4 5)
⇒ 15
will cause the byte compiler emit a warning message when it compiles Lisp programs which
use the deprecated calling convention.
be a declare form specifying function metadata (see Section 13.14 [Declare Form],
page 231). interactive, if present, should be an interactive form specifying how the
function is to be called interactively (see Section 21.3 [Interactive Call], page 375).
The return value of defun is undefined.
Here are some examples:
(defun foo () 5)
(foo)
⇒ 5
(defun capitalize-backwards ()
"Upcase the last letter of the word at point."
(interactive)
(backward-word 1)
(forward-word 1)
(backward-char 1)
(capitalize-word 1))
Be careful not to redefine existing functions unintentionally. defun redefines even
primitive functions such as car without any hesitation or notification. Emacs does
not prevent you from doing this, because redefining a function is sometimes done de-
liberately, and there is no way to distinguish deliberate redefinition from unintentional
redefinition.
defalias name definition &optional doc [Function]
This function defines the symbol name as a function, with definition definition (which
can be any valid Lisp function). Its return value is undefined.
If doc is non-nil, it becomes the function documentation of name. Otherwise, any
documentation provided by definition is used.
Internally, defalias normally uses fset to set the definition. If name has a
defalias-fset-function property, however, the associated value is used as a
function to call in place of fset.
The proper place to use defalias is where a specific function name is being defined—
especially where that name appears explicitly in the source file being loaded. This
is because defalias records which file defined the function, just like defun (see
Section 16.9 [Unloading], page 276).
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 13.9 [Function
Cells], page 221.
Chapter 13: Functions 211
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
perform inline expansion on it. See Section 13.13 [Inline Functions], page 230.
Alternatively, you can define a function by providing the code which will inline it as a
compiler macro. The following macros make this possible.
Functions defined via define-inline have several advantages with respect to macros
defined by defsubst or defmacro:
− They can be passed to mapcar (see Section 13.6 [Mapping Functions], page 214).
− They are more efficient.
− They can be used as place forms to store values (see Section 12.17 [Generalized Vari-
ables], page 200).
− They behave in a more predictable way than cl-defsubst (see Section “Argument
Lists” in Common Lisp Extensions for GNU Emacs Lisp).
Like defmacro, a function inlined with define-inline inherits the scoping rules, either
dynamic or lexical, from the call site. See Section 12.10 [Variable Scoping], page 179.
The following macros should be used in the body of a function defined by define-inline.
Sometimes it is useful to fix some of the function’s arguments at certain values, and
leave the rest of arguments for when the function is actually called. The act of fixing some
of the function’s arguments is called partial application of the function1 . The result is a
new function that accepts the rest of arguments and calls the original function with all the
arguments combined.
Here’s how to do partial application in Emacs Lisp:
It is common for Lisp functions to accept functions as arguments or find them in data
structures (especially in hook variables and property lists) and call them using funcall or
apply. Functions that accept function arguments are often called functionals.
Sometimes, when you call a functional, it is useful to supply a no-op function as the
argument. Here are two different kinds of no-op function:
Some functions are user-visible commands, which can be called interactively (usually by
a key sequence). It is possible to invoke such a command exactly as though it was called
interactively, by using the call-interactively function. See Section 21.3 [Interactive
Call], page 375.
The read syntax #' is a short-hand for using function. The following forms are all
equivalent:
(lambda (x) (* x x))
(function (lambda (x) (* x x)))
Chapter 13: Functions 217
Note that, unlike in message-based OO languages, such as C++ and Simula, methods that
implement generic functions don’t belong to a class, they belong to the generic function they
implement.
When a generic function is invoked, it selects the applicable methods by comparing the
actual arguments passed by the caller with the argument specializers of each method. A
method is applicable if the actual arguments of the call are compatible with the method’s
specializers. If more than one method is applicable, they are combined using certain rules,
described below, and the combination then handles the call.
(declare declarations)
A declare form, as described in Section 13.14 [Declare Form], page 231.
type This specializer requires the argument to be of the given type, one of the
types from the type hierarchy described below.
(eql object)
This specializer requires the argument be eql to the given object.
(head object)
The argument must be a cons cell whose car is eql to object.
Chapter 13: Functions 219
struct-type
The argument must be an instance of a class named struct-type defined
with cl-defstruct (see Section “Structures” in Common Lisp Exten-
sions for GNU Emacs Lisp), or of one of its child classes.
Alternatively, the argument specializer can be of the form &context (expr spec),
in which case the value of expr must be compatible with the specializer provided by
spec; spec can be any of the forms described above. In other words, this form of
specializer uses the value of expr instead of arguments for the decision whether the
method is applicable. For example, &context (overwrite-mode (eql t)) will make
the method compatible only when overwrite-mode is turned on.
The type specializer, (arg type), can specify one of the system types in the following
list. When a parent type is specified, an argument whose type is any of its more
specific child types, as well as grand-children, grand-grand-children, etc. will also be
compatible.
integer Parent type: number.
number
null Parent type: symbol
symbol
string Parent type: array.
array Parent type: sequence.
cons Parent type: list.
list Parent type: sequence.
marker
overlay
float Parent type: number.
window-configuration
process
window
subr
compiled-function
buffer
char-table
Parent type: array.
bool-vector
Parent type: array.
vector Parent type: array.
frame
Chapter 13: Functions 220
hash-table
font-spec
font-entity
font-object
The optional qualifier allows combining several applicable methods. If it is not
present, the defined method is a primary method, responsible for providing the pri-
mary implementation of the generic function for the specialized arguments. You can
also define auxiliary methods, by using one of the following values as qualifier:
:before This auxiliary method will run before the primary method. More ac-
curately, all the :before methods will run before the primary, in the
most-specific-first order.
:after This auxiliary method will run after the primary method. More accu-
rately, all such methods will run after the primary, in the most-specific-
last order.
:around This auxiliary method will run instead of the primary method. The
most specific of such methods will be run before any other method. Such
methods normally use cl-call-next-method, described below, to invoke
the other auxiliary or primary methods.
:extra string
This allows you to add more methods, distinguished by string, for the
same specializers and qualifiers.
Functions defined using cl-defmethod cannot be made interactive, i.e. commands
(see Section 21.2 [Defining Commands], page 369), by adding the interactive form
to them. If you need a polymorphic command, we recommend defining a nor-
mal command that calls a polymorphic function defined via cl-defgeneric and
cl-defmethod.
Each time a generic function is called, it builds the effective method which will handle
this invocation by combining the applicable methods defined for the function. The process
of finding the applicable methods and producing the effective method is called dispatch.
The applicable methods are those all of whose specializers are compatible with the actual
arguments of the call. Since all of the arguments must be compatible with the specializers,
they all determine whether a method is applicable. Methods that explicitly specialize more
than one argument are called multiple-dispatch methods.
The applicable methods are sorted into the order in which they will be combined. The
method whose left-most argument specializer is the most specific one will come first in
the order. (Specifying :argument-precedence-order as part of cl-defmethod overrides
that, as described above.) If the method body calls cl-call-next-method, the next most-
specific method will run. If there are applicable :around methods, the most-specific of them
will run first; it should call cl-call-next-method to run any of the less specific :around
methods. Next, the :before methods run in the order of their specificity, followed by the
primary method, and lastly the :after methods in the reverse order of their specificity.
cl-call-next-method &rest args [Function]
When invoked from within the lexical body of a primary or an :around auxiliary
method, call the next applicable method for the same generic function. Normally, it
Chapter 13: Functions 221
is called with no arguments, which means to call the next applicable method with
the same arguments that the calling method was invoked. Otherwise, the specified
arguments are used instead.
cl-next-method-p [Function]
This function, when called from within the lexical body of a primary or an :around
auxiliary method, returns non-nil if there is a next method to call.
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 the symbol as a function, Emacs 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.
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.
(fmakunbound 'foo)
⇒ foo
(foo 1)
error Symbol's function definition is void: foo
13.10 Closures
As explained in Section 12.10 [Variable Scoping], page 179, Emacs can optionally enable
lexical binding of variables. When lexical binding is enabled, any named function that you
create (e.g., with defun), as well as any anonymous function that you create using the
lambda macro or the function special form or the #' syntax (see Section 13.7 [Anonymous
Functions], page 216), is automatically converted into a closure.
A closure is a function that also carries a record of the lexical environment that existed
when the function was defined. When it is invoked, any lexical variable references within
its definition use the retained lexical environment. In all other respects, closures behave
much like ordinary functions; in particular, they can be called in the same way as ordinary
functions.
See Section 12.10.3 [Lexical Binding], page 182, for an example of using a closure.
Currently, an Emacs Lisp closure object is represented by a list with the symbol closure
as the first element, a list representing the lexical environment as the second element, and
the argument list and body forms as the remaining elements:
;; lexical binding is enabled.
(lambda (x) (* x x))
⇒ (closure (t) (x) (* x x))
However, the fact that the internal structure of a closure is exposed to the rest of the
Lisp world is considered an internal implementation detail. For this reason, we recommend
against directly examining or altering the structure of closure objects.
holds a function value, you can use the appropriate setter function, such as fset or defun
for named functions, setq for hook variables, or set-process-filter for process filters,
but those are often too blunt, completely throwing away the previous value.
The advice feature lets you add to the existing definition of a function, by advising the
function. This is a cleaner method than redefining the whole function.
Emacs’s advice system provides two sets of primitives for that: the core set, for func-
tion values held in variables and object fields (with the corresponding primitives being
add-function and remove-function) and another set layered on top of it for named func-
tions (with the main primitives being advice-add and advice-remove).
For example, in order to trace the calls to the process filter of a process proc, you could
use:
(defun my-tracing-function (proc string)
(message "Proc %S received %S" proc string))
[Advice combinators], page 226, for the list of available ways to compose the two
functions.
When modifying a variable (whose name will usually end with -function), you can
choose whether function is used globally or only in the current buffer: if place is just
a symbol, then function is added to the global value of place. Whereas if place is of
the form (local symbol), where symbol is an expression which returns the variable
name, then function will only be added in the current buffer. Finally, if you want to
modify a lexical variable, you will have to use (var variable).
Every function added with add-function can be accompanied by an association list
of properties props. Currently only two of those properties have a special meaning:
name This gives a name to the advice, which remove-function can use to
identify which function to remove. Typically used when function is an
anonymous function.
depth This specifies how to order the advice, should several pieces of advice be
present. By default, the depth is 0. A depth of 100 indicates that this
piece of advice should be kept as deep as possible, whereas a depth of
−100 indicates that it should stay as the outermost piece. When two
pieces of advice specify the same depth, the most recently added one will
be outermost.
For :before advice, being outermost means that this advice will be run
first, before any other advice, whereas being innermost means that it will
run right before the original function, with no other advice run between
itself and the original function. Similarly, for :after advice innermost
means that it will run right after the original function, with no other
advice run in between, whereas outermost means that it will be run right
at the end after all other advice. An innermost :override piece of advice
will only override the original function and other pieces of advice will
apply to it, whereas an outermost :override piece of advice will override
not only the original function but all other advice applied to it as well.
If function is not interactive, then the combined function will inherit the interactive
spec, if any, of the original function. Else, the combined function will be interactive
and will use the interactive spec of function. One exception: if the interactive spec
of function is a function (rather than an expression or a string), then the interactive
spec of the combined function will be a call to that function with as sole argument the
interactive spec of the original function. To interpret the spec received as argument,
use advice-eval-interactive-spec.
Note: The interactive spec of function will apply to the combined function and
should hence obey the calling convention of the combined function rather than that
of function. In many cases, it makes no difference since they are identical, but it does
matter for :around, :filter-args, and :filter-return, where function receives
different arguments than the original function stored in place.
function is compared with functions added to place using equal, to try and make it
work also with lambda expressions. It is additionally compared also with the name
property of the functions added to place, which can be more reliable than comparing
lambda expressions using equal.
code that has already been macro-expanded, so you need to make sure the advice is installed
before the macro is expanded.
It is possible to advise a primitive (see Section 13.1 [What Is a Function], page 203), but
one should typically not do so, for two reasons. Firstly, some primitives are used by the
advice mechanism, and advising them could cause an infinite recursion. Secondly, many
primitives are called directly from C, and such calls ignore advice; hence, one ends up in a
confusing situation where some calls (occurring from Lisp code) obey the advice and other
calls (from C code) do not.
It’s possible to use defmacro to define a macro to expand into the same code that an
inline function would execute (see Chapter 14 [Macros], page 236). 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 easy; just 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.
As an alternative to defsubst, you can use define-inline to define functions via their
exhaustive compiler macro. See Section 13.4 [Defining Functions], page 209.
All you need to do is add a declare-function statement before the first use of the
function in question:
(declare-function shell-mode "shell" ())
This says that shell-mode is defined in shell.el (the ‘.el’ can be omitted). The
compiler takes for granted that that file really defines the function, and does not check.
The optional third argument specifies the argument list of shell-mode. In this case, it
takes no arguments (nil is different from not specifying a value). In other cases, this might
be something like (file &optional overwrite). You don’t have to specify the argument
list, but if you do the byte compiler can check that the calls match the declaration.
To verify that these functions really are declared where declare-function says they
are, use check-declare-file to check all declare-function calls in one source file, or use
check-declare-directory check all the files in and under a certain directory.
These commands find the file that ought to contain a function’s definition using
locate-library; if that finds no file, they expand the definition file name relative to the
directory of the file that contains the declare-function call.
You can also say that a function is a primitive by specifying a file name ending in ‘.c’ or
‘.m’. This is useful only when you call a primitive that is defined only on certain systems.
Most primitives are always defined, so they will never give you a warning.
Sometimes a file will optionally use functions from an external package. If you prefix
the filename in the declare-function statement with ‘ext:’, then it will be checked if it
is found, otherwise skipped without error.
There are some function definitions that ‘check-declare’ does not understand (e.g.,
defstruct and some other macros). In such cases, you can pass a non-nil fileonly argument
to declare-function, meaning to only check that the file exists, not that it actually defines
the function. Note that to do this without having to specify an argument list, you should
set the arglist argument to t (because nil means an empty argument list, as opposed to
an unspecified one).
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.
mapconcat
See Section 13.6 [Mapping Functions], page 214.
undefined
See Section 22.11 [Functions for Key Lookup], page 428.
236
14 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 13.13 [Inline Functions],
page 230.
Since the expansion is evaluated in the normal manner, it may contain calls to other
macros. It may even be a call to the same macro, though this is unusual.
Note that Emacs tries to expand macros when loading an uncompiled Lisp file. This is
not always possible, but if it is, it speeds up subsequent execution. See Section 16.1 [How
Programs Do Loading], page 263.
You can see the expansion of a given macro call by calling macroexpand.
Macros often need to construct large list structures from a mixture of constants and
nonconstant parts. To make this easier, use the ‘`’ syntax (see Section 10.3 [Backquote],
page 135). 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))
(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.
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.
(let ((i 1)
(max 3))
(while (<= i max)
(setq square (* i i))
(princ (format "%d %d" i square))
(inc i)))
(setq x 'b)
(foo x) 7→ (setq b t)
⇒ t ; and b has been set.
;; but
(setq a 'c)
(foo a) 7→ (setq a t)
⇒ t ; but this set a, not c.
15 Customization Settings
Users of Emacs can customize variables and faces without writing Lisp code, by using the
Customize interface. See Section “Easy Customization” in The GNU Emacs Manual. This
chapter describes how to define customization items that users can interact with through
the Customize interface.
Customization items include customizable variables, which are defined with the
defcustom macro; customizable faces, which are defined with defface (described
separately in Section 39.12.2 [Defining Faces], page 1001); and customization groups,
defined with defgroup, which act as containers for groups of related customization items.
(url-link url)
Link to a web page; url is a string which specifies the URL. The link
appears in the customization buffer as url and invokes the WWW
browser specified by browse-url-browser-function.
(emacs-commentary-link library)
Link to the commentary section of a library; library is a string
which specifies the library name. See Section D.8 [Library Headers],
page 1152.
(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’.
You can use this keyword more than once, to add multiple links.
:load file
Load file file (a string) before displaying this customization item (see Chapter 16
[Loading], page 263). Loading is done with load, 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.
Chapter 15: Customization Settings 246
: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. This
keyword takes priority over :version.
package should be the official name of the package, as a symbol (e.g., MH-E).
version should be a string. If the package package is released as part of Emacs,
package and version should appear in the value of customize-package-emacs-
version-alist.
Packages distributed as part of Emacs that use the :package-version keyword must
also update the customize-package-emacs-version-alist variable.
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 are:
(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
an error message, a good choice is the official name of the package, such as MH-E or
Gnus.
installed as the default value. Otherwise, the result of evaluating standard is installed
as the default value.
Like defvar, this macro marks option as a special variable, meaning that it should
always be dynamically bound. If option is already lexically bound, that lexical bind-
ing remains in effect until the binding construct exits. See Section 12.10 [Variable
Scoping], page 179.
The expression standard can be evaluated at various other times, too—whenever the
customization facility needs to know option’s standard value. So be sure to use an
expression which is harmless to evaluate at any time.
The argument doc specifies the documentation string for the variable.
If a defcustom does not specify any :group, the last group defined with defgroup in
the same file will be used. This way, most defcustom do not need an explicit :group.
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 Section 12.5
[Defining Variables], page 173.) Using eval-defun on a defcustom that is already
defined calls the :set function (see below), if there is one.
If you put a defcustom in a pre-loaded Emacs Lisp file (see Section E.1 [Building
Emacs], page 1156), the standard value installed at dump time might be incorrect,
e.g., because another variable that it depends on has not been assigned the right value
yet. In that case, use custom-reevaluate-setting, described below, to re-evaluate
the standard value after Emacs starts up.
In addition to the keywords listed in Section 15.1 [Common Keywords], page 244, this
macro accepts the following keywords:
: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 15.4 [Customization Types], page 251).
Every defcustom should specify a value for this keyword.
: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 when using
the Customize interface. 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); preferably, though, it should
not modify its value argument destructively. The default for setfunction is
set-default.
Chapter 15: Customization Settings 249
If you specify this keyword, the variable’s documentation string should describe
how to do the same job in hand-written Lisp code.
: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.
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-delay
This functions behaves like custom-initialize-set, but it delays
the actual initialization to the next Emacs start. This should be
used in files that are preloaded (or for autoloaded variables), so that
the initialization is done in the run-time context rather than the
build-time context. This also has the side-effect that the (delayed)
initialization is performed with the :set function. See Section E.1
[Building Emacs], page 1156.
:risky value
Set the variable’s risky-local-variable property to value (see Section 12.12
[File Local Variables], page 191).
Chapter 15: Customization Settings 250
:safe function
Set the variable’s safe-local-variable property to function (see Section 12.12
[File Local Variables], page 191).
:set-after variables
When setting variables according to saved customizations, make sure to set the
variables variables before this one; i.e., 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.
It is useful to specify the :require keyword for an option that turns on a certain feature.
This causes Emacs to load the feature, if it is not already loaded, whenever the option is
set. See Section 15.1 [Common Keywords], page 244. Here is an example:
(defcustom frobnicate-automatically nil
"Non-nil means automatically frobnicate all buffers."
:type 'boolean
:require 'frobnicate-mode
:group 'frobnicate)
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)
Internally, defcustom uses the symbol property standard-value to record the expres-
sion for the standard value, saved-value to record the value saved by the user with the
customization buffer, and customized-value to record the value set by the user with the
customization buffer, but not saved. See Section 9.4 [Symbol Properties], page 125. These
properties are lists, the car of which is an expression that evaluates to the value.
file The value must be a file name. The widget provides completion.
(file :must-match t)
The value must be a file name for an existing file. The widget provides com-
pletion.
directory
The value must be a directory. The widget provides completion.
hook The value must be a list of functions. 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 functions recommended for use in the hook; See Section 15.3
[Variable Definitions], page 247.
symbol The value must be a symbol. It appears in the customization buffer as the
symbol name. The widget provides completion.
function The value must be either a lambda expression or a function name. The widget
provides completion for function names.
variable The value must be a variable name. The widget provides completion.
face The value must be a symbol which is a face name. The widget provides com-
pletion.
boolean The value is boolean—either nil or t. Note that by using choice and const
together (see the next section), you can specify that the value must be nil or
t, but also specify the text to describe each value in a way that fits the specific
meaning of the alternative.
key-sequence
The value is a key sequence. The customization buffer shows the key sequence
using the same syntax as the kbd function. See Section 22.1 [Key Sequences],
page 415.
coding-system
The value must be a coding-system name, and you can do completion with
M-TAB.
color The value must be a valid color name. The widget provides completion for color
names, as well as a sample and a button for selecting a color name from a list
of color names shown in a *Colors* buffer.
Here is a table of constructors and how to use them to write composite types:
(cons car-type cdr-type)
The value must be a cons cell, its car must fit car-type, and its cdr must fit
cdr-type. For example, (cons string symbol) is a customization type which
matches values such as ("foo" . foo).
In the customization buffer, the car and cdr are displayed and edited sepa-
rately, each according to their specified type.
(list element-types...)
The value must be a list with exactly as many elements as the element-types
given; and each element must fit the corresponding element-type.
For example, (list integer string function) describes a list of three ele-
ments; the first element must be an integer, the second a string, and the third
a function.
In the customization buffer, each element is displayed and edited separately,
according to the type specified for it.
(group element-types...)
This works like list except for the formatting of text in the Custom buffer.
list labels each element value with its tag; group does not.
(vector element-types...)
Like list except that the value must be a vector instead of a list. The elements
work the same as in list.
(alist :key-type key-type :value-type value-type)
The value must be a list of cons-cells, the car of each cell representing a key of
customization type key-type, and the cdr of the same cell representing a value
of customization type value-type. The user can add and delete key/value pairs,
and edit both the key and the value of each pair.
If omitted, key-type and value-type default to 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 15.3 [Variable Definitions], page 247). 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. For example:
:options '("foo" "bar" "baz")
specifies that there are three known keys, namely "foo", "bar" and "baz",
which will always be shown first.
You may want to restrict the value type for specific keys, for example, the value
associated with the "bar" key can only be an integer. You can specify this by
using a list instead of an atom in the list. The first element will specify the key,
like before, while the second element will specify the value type. For example:
Chapter 15: Customization Settings 254
Normally the strings in this menu are determined automatically from the
choices; however, you can specify different strings for the menu by including
the :tag keyword in the alternatives. For example, if an integer stands for a
number of spaces, while a string is text to use verbatim, you might write the
customization type this way,
(choice (integer :tag "Number of spaces")
(string :tag "Literal text"))
so that the menu offers ‘Number of spaces’ and ‘Literal text’.
In any alternative for which nil is not a valid value, other than a const, you
should specify a valid default for that alternative using the :value keyword.
See Section 15.4.4 [Type Keywords], page 257.
If some values are covered by more than one of the alternatives, customize will
choose the first alternative that the value fits. This means you should always
list the most specific types first, and the most general last. Here’s an example
of proper usage:
(choice (const :tag "Off" nil)
symbol (sexp :tag "Other"))
This way, the special value nil is not treated like other symbols, and symbols
are not treated like other Lisp expressions.
(radio element-types...)
This is similar to choice, except that the choices are displayed using radio
buttons rather than a menu. This has the advantage of displaying documenta-
tion for the choices when applicable and so is often a good choice for a choice
between constant functions (function-item customization types).
(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”.
(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
Chapter 15: Customization Settings 256
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:
• A predicate—that is, a function of one argument that returns either nil
or non-nil according to the argument. Using a predicate in the list says
that objects for which the predicate returns non-nil are acceptable.
• A quoted constant—that is, 'object. This sort of element in the list says
that object itself is an acceptable value.
For example,
(restricted-sexp :match-alternatives
(integerp 't 'nil))
allows integers, t and nil as legitimate values.
Chapter 15: Customization Settings 257
The customization buffer shows all legitimate values using their read syntax,
and the user edits them textually.
Here is a table of the keywords you can use in keyword-value pairs in a composite type:
:tag tag Use tag as the name of this alternative, for user communication purposes. This
is useful for a type that appears inside of a choice.
:match-alternatives criteria
Use criteria to match possible values. This is used only in restricted-sexp.
:args argument-list
Use the elements of argument-list as the arguments of the type construct. For
instance, (const :args (foo)) is equivalent to (const foo). You rarely need
to write :args explicitly, because normally the arguments are recognized auto-
matically as whatever follows the last keyword-value pair.
If nil is not a valid value for the alternative, then it is essential to specify a
valid default with :value.
If you use this for a type that appears as an alternative inside of choice; it
specifies the default value to use, at first, if and when the user selects this
alternative with the menu in the customization buffer.
Of course, if the actual value of the option fits this alternative, it will appear
showing the actual value, not default.
:format format-string
This string will be inserted in the buffer to represent the value corresponding
to the type. The following ‘%’ escapes are available for use in format-string:
‘%[button%]’
Display the text button marked as a button. The :action attribute
specifies what the button will do if the user invokes it; its value is a
function which takes two arguments—the widget which the button
appears in, and the event.
There is no way to specify two different buttons with different ac-
tions.
‘%{sample%}’
Show sample in a special face specified by :sample-face.
‘%v’ Substitute the item’s value. How the value is represented depends
on the kind of item, and (for variables) on the customization type.
‘%d’ Substitute the item’s documentation string.
‘%h’ Like ‘%d’, but if the documentation string is more than one line,
add a button to control whether to show all of it or just the first
line.
‘%t’ Substitute the tag here. You specify the tag with the :tag keyword.
‘%%’ Display a literal ‘%’.
:action action
Perform action if the user clicks on a button.
: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.
Chapter 15: Customization Settings 259
: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.
:validate function
Specify a validation function for input. function takes a widget as an argument,
and should return nil if the widget’s current value is valid for the widget.
Otherwise, it should return the widget containing the invalid data, and set that
widget’s :error property to a string explaining the error.
form has not been evaluated. request is a list of features to be loaded immediately
(see Section 16.7 [Named Features], page 273). comment is a string describing the
customization.
In between deftheme and provide-theme are Lisp forms specifying the theme settings:
usually a call to custom-theme-set-variables and/or a call to custom-theme-set-faces.
In theory, a theme file can also contain other Lisp forms, which would be evaluated when
loading the theme, but that is bad form. To protect against loading themes containing
malicious code, Emacs displays the source file and asks for confirmation from the user
before loading any non-built-in theme for the first time. As such, themes are not ordinarily
byte-compiled, and source files always take precedence when Emacs is looking for a theme
to load.
The following functions are useful for programmatically enabling and disabling themes:
custom-known-themes [Variable]
The value of this variable is a list of themes loaded into Emacs. Each theme is
represented by a Lisp symbol (the theme name). The default value of this variable
is a list containing two dummy themes: (user changed). The changed theme stores
settings made before any Custom themes are applied (e.g., variables set outside of
Customize). The user theme stores settings the user has customized and saved. Any
additional themes declared with the deftheme macro are added to the front of this
list.
16 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. Such a file is also called a Lisp library.
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.
Emacs can also load compiled dynamic modules: shared libraries that provide additional
functionality for use in Emacs Lisp programs, just like a package written in Emacs Lisp
would. When a dynamic module is loaded, Emacs calls a specially-named initialization
function which the module needs to implement, and which exposes the additional functions
and variables to Emacs Lisp programs.
For on-demand loading of external libraries which are known in advance to be required
by certain Emacs primitives, see Section 40.21 [Dynamic Libraries], page 1110.
each of the suffixes in jka-compr-load-suffixes to the file name. The value of this
variable must be a list of strings. Its standard value is (".gz").
If the optional argument nosuffix is non-nil, then load does not try the suffixes ‘.elc’
and ‘.el’. In this case, you must specify the precise file name you want, except that, if
Auto Compression mode is enabled, load will still use jka-compr-load-suffixes to
find compressed versions. By specifying the precise file name and using t for nosuffix,
you can prevent file names like foo.el.el from being tried.
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)
or the shared-library extension, unless it contains an explicit directory name.
If the option load-prefer-newer is non-nil, then when searching suffixes, load
selects whichever version of a file (‘.elc’, ‘.el’, etc.) has been modified most recently.
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 16.3
[Library Search], page 266.
Whatever the name under which the file is eventually found, and the directory where
Emacs found it, Emacs sets the value of the variable load-file-name to that file’s
name.
If you get a warning that foo.elc is older than foo.el, it means you should consider
recompiling foo.el. See Chapter 17 [Byte Compilation], page 279.
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 848.
When loading an uncompiled file, Emacs tries to expand any macros that the file
contains (see Chapter 14 [Macros], page 236). We refer to this as eager macro expan-
sion. Doing this (rather than deferring the expansion until the relevant code runs)
can significantly speed up the execution of uncompiled code. Sometimes, this macro
expansion cannot be done, owing to a cyclic dependency. In the simplest example of
this, the file you are loading refers to a macro defined in another file, and that file
in turn requires the file you are loading. This is generally harmless. Emacs prints a
warning (‘Eager macro-expansion skipped due to cycle...’) giving details of the
problem, but it still loads the file, just leaving the macro unexpanded for now. You
may wish to restructure your code so that this does not happen. Loading a com-
piled file does not cause macroexpansion, because this should already have happened
during compilation. See Section 14.3 [Compiling Macros], page 238.
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 a file-error (with ‘Cannot
open load file filename’). But if missing-ok is non-nil, then load just returns nil.
Chapter 16: Loading 265
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-file-name [Variable]
When Emacs is in the process of loading a file, this variable’s value is the name of
that file, as Emacs found it during the search described earlier in this section.
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.
By default, this variable’s value is read. See Section 19.3 [Input Functions], page 325.
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 137.
For information about how load is used in building Emacs, see Section E.1 [Building
Emacs], page 1156.
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.
Chapter 16: Loading 266
and
"/usr/local/share/emacs/site-lisp"
The first one is for locally installed files for a specific Emacs version; the second is for
locally installed files meant for use with all installed Emacs versions. (If Emacs is running
uninstalled, it also adds site-lisp directories from the source and build directories, if they
exist. Normally these directories do not contain site-lisp directories.)
If the environment variable EMACSLOADPATH is set, it modifies the above initialization
procedure. Emacs initializes load-path based on the value of the environment variable.
The syntax of EMACSLOADPATH is the same as used for PATH; directories are separated by
‘:’ (or ‘;’, on some operating systems). Here is an example of how to set EMACSLOADPATH
variable (from a sh-style shell):
export EMACSLOADPATH=/home/foo/.emacs.d/lisp:
An empty element in the value of the environment variable, whether trailing (as in the
above example), leading, or embedded, is replaced by the default value of load-path as
determined by the standard initialization procedure. If there are no such empty elements,
then EMACSLOADPATH specifies the entire load-path. You must include either an empty
element, or the explicit path to the directory containing the standard Lisp files, else Emacs
will not function. (Another way to modify load-path is to use the -L command-line option
when starting Emacs; see below.)
For each directory in load-path, Emacs then checks to see if it contains a file
subdirs.el, and if so, loads it. The subdirs.el file is created when Emacs is
built/installed, and contains code that causes Emacs to add any subdirectories of those
directories to load-path. Both immediate subdirectories and subdirectories multiple levels
down are added. But it excludes subdirectories whose names do not start with a letter or
digit, and subdirectories named RCS or CVS, and subdirectories containing a file named
.nosearch.
Next, Emacs adds any extra load directories that you specify using the -L command-
line option (see Section “Action Arguments” in The GNU Emacs Manual). It also adds
the directories where optional packages are installed, if any (see Section 41.1 [Packaging
Basics], page 1114).
It is common to add code to one’s init file (see Section 40.1.2 [Init File], page 1075) to
add one or more directories to load-path. For example:
(push "~/.emacs.d/lisp" load-path)
Dumping Emacs uses a special value of load-path. If you use a site-load.el or
site-init.el file to customize the dumped Emacs (see Section E.1 [Building Emacs],
page 1156), any changes to load-path that these files make will be lost after dumping.
locate-library library &optional nosuffix path interactive-call [Command]
This command finds the precise file name for library library. It searches for the library
in the same way load does, and the argument nosuffix has the same meaning as in
load: don’t add suffixes ‘.elc’ or ‘.el’ to the specified name library.
If the path is non-nil, that list of directories is used instead of load-path.
When locate-library is called from a program, it returns the file name as a string.
When the user runs locate-library interactively, the argument interactive-call is t,
and this tells locate-library to display the file name in the echo area.
Chapter 16: Loading 268
16.5 Autoload
The autoload facility lets you register the existence of a function or macro, but put off
loading the file that defines it. The first call to the function automatically loads the proper
library, in order to install the real definition and other associated code, then runs the real
definition as if it had been loaded all along. Autoloading can also be triggered by looking
up the documentation of the function or macro (see Section 24.1 [Documentation Basics],
page 510), and completion of variable and function names (see Section 16.5.1 [Autoload by
Prefix], page 272, below).
There are two ways to set up an autoloaded function: by calling autoload, and by
writing a “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.
Chapter 16: Loading 269
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. (The string that serves as the autoload
cookie and the name of the file generated by update-file-autoloads can be changed
from the above defaults, see below.) 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. The form
following the magic comment is copied verbatim, except if it is one of the forms which the
autoload facility handles specially (e.g., by conversion into an autoload call). The forms
which are not copied verbatim are the following:
Definitions for function or function-like objects:
defun and defmacro; also cl-defun and cl-defmacro (see Section “Argument
Lists” in Common Lisp Extensions), and define-overloadable-function (see
the commentary in mode-local.el).
Definitions for major or minor modes:
define-minor-mode, define-globalized-minor-mode, define-generic-
mode, define-derived-mode, easy-mmode-define-minor-mode,
easy-mmode-define-global-mode, define-compilation-mode, and
define-global-minor-mode.
Other definition types:
defcustom, defgroup, defclass (see EIEIO), and define-skeleton (see
Autotyping).
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)
Chapter 16: Loading 271
(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)
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 1156. 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.6 [Help Functions], page 517) 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
...)
You can use a non-default string as the autoload cookie and have the corresponding
autoload calls written into a file whose name is different from the default loaddefs.el.
Emacs provides two variables to control this:
generate-autoload-cookie [Variable]
The value of this variable should be a string whose syntax is a Lisp comment. M-x
update-file-autoloads copies the Lisp form that follows the cookie into the au-
toload file it generates. The default value of this variable is ";;;###autoload".
generated-autoload-file [Variable]
The value of this variable names an Emacs Lisp file where the autoload calls should
go. The default value is loaddefs.el, but you can override that, e.g., in the local
variables section of a .el file (see Section 12.12 [File Local Variables], page 191). The
autoload file is assumed to contain a trailer starting with a formfeed character.
The following function may be used to explicitly load the library specified by an autoload
object:
(unless foo-was-loaded
execute-first-time-only
(setq foo-was-loaded t))
16.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 idlwave.el, the definition for idlwave-complete-filename includes
the following code:
(defun idlwave-complete-filename ()
"Use the comint stuff to complete a file name."
(require 'comint)
(let* ((comint-file-name-chars "~/A-Za-z0-9+@:_.$#%={}\\-")
(comint-completion-addsuffix nil)
...)
(comint-dynamic-complete-filename)))
The expression (require 'comint) loads the file comint.el if it has not yet been loaded,
ensuring that comint-dynamic-complete-filename is defined. Features are normally
named after the files that provide them, so that require need not be given the file name.
(Note that it is important that the require statement be outside the body of the let.
Loading a library while its variables are let-bound can have unintended consequences,
namely the variables becoming unbound after the let exits.)
The comint.el file contains the following top-level expression:
(provide 'comint)
Chapter 16: Loading 274
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 17 [Byte Compilation], page 279) 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.
(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 16.5 [Autoload], page 268.
Chapter 16: Loading 275
(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.
(defface . face)
The face face was defined.
(require . feature)
The feature feature was required.
(provide . feature)
The feature feature was provided.
(cl-defmethod method specializers)
The named method was defined by using cl-defmethod, with specializers
as its specializers.
(define-type . type)
The type type was defined.
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 10.4 [Eval], page 136.
16.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:
If these measures are not sufficient to prevent malfunction, a library can define an ex-
plicit unloader named feature-unload-function. If that symbol is defined as a func-
tion, unload-feature calls it with no arguments before doing anything else. It can
do whatever is appropriate to unload the library. If it returns nil, unload-feature
proceeds to take the normal unload actions. Otherwise it considers the job to be
done.
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.
after-load-functions [Variable]
This abnormal hook is run after loading a file. Each function in the hook is called
with a single argument, the absolute filename of the file that was just loaded.
If you want code to be executed when a particular library is loaded, use the macro
with-eval-after-load:
17 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.
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; -*-
(silly-loop 50000000)
⇒ 10.235304117202759
(byte-compile 'silly-loop)
⇒ [Compiled code not shown]
(silly-loop 50000000)
⇒ 3.705854892730713
In this example, the interpreted code required 10 seconds to run, whereas the byte-
compiled code required less than 4 seconds. These results are representative, but actual
results may vary.
called *Compile-Log*, which uses Compilation mode. See Section “Compilation Mode” in
The GNU Emacs Manual. However, if the variable byte-compile-debug is non-nil, error
messages will be signaled as Lisp errors instead (see Section 11.7.3 [Errors], page 160).
Be careful when writing macro calls in files that you intend to byte-compile. Since macro
calls are expanded when they are compiled, the macros need to be loaded into Emacs or
the byte compiler will not do the right thing. The usual way to handle this is with require
forms which specify the files containing the needed macro definitions (see Section 16.7
[Named Features], page 273). Normally, the byte compiler does not evaluate the code that
it is compiling, but it handles require forms specially, by loading the specified libraries.
To avoid loading the macro definition files when someone runs the compiled program, write
eval-when-compile around the require calls (see Section 17.5 [Eval During Compile],
page 283). For more details, See Section 14.3 [Compiling Macros], page 238.
Inline (defsubst) functions are less troublesome; if you compile a call to such a function
before its definition is known, the call will still work right, it will just run slower.
(byte-compile 'factorial)
⇒
#[(integer)
"^H\301U\203^H^@\301\207\302^H\303^HS!\"\207"
[integer 1 * factorial]
4 "Compute factorial of INTEGER."]
If symbol’s definition is a byte-code function object, byte-compile does nothing and
returns nil. It does not compile the symbol’s definition again, since the original
(non-compiled) code has already been replaced in the symbol’s function cell by the
byte-compiled code.
The argument to byte-compile can also be a lambda expression. In that case, the
function returns the corresponding compiled code but does not store it anywhere.
(byte-compile-file "~/emacs/push.el")
⇒ t
$ ls -l push*
-rw-r--r-- 1 lewis lewis 791 Oct 5 20:31 push.el
-rw-rw-rw- 1 lewis lewis 638 Oct 8 20:25 push.elc
• If you alter the compiled file (such as by compiling a new version), then trying to load
any function not already loaded will usually yield nonsense results.
These problems will never happen in normal circumstances with installed Emacs files.
But they are quite likely to happen with Lisp files that you are changing. The easiest
way to prevent these problems is to reload the new compiled file immediately after each
recompilation.
The byte compiler uses the dynamic function loading feature if the variable
byte-compile-dynamic is non-nil at compilation time. Do not set this variable globally,
since dynamic loading is desirable only for certain files. Instead, enable the feature for
specific source files with file-local variable bindings. For example, you could do it by
writing this text in the source file’s first line:
-*-byte-compile-dynamic: t;-*-
byte-compile-dynamic [Variable]
If this is non-nil, the byte compiler generates compiled files that are set up for
dynamic function loading.
appears in the compiled program. If you load the source file, rather than compiling
it, body is evaluated normally.
If you have a constant that needs some calculation to produce, eval-when-compile
can do that at compile-time. For example,
(defvar my-regexp
(eval-when-compile (regexp-opt '("aaa" "aba" "abb"))))
If you’re using another package, but only need macros from it (the byte compiler will
expand those), then eval-when-compile can be used to load it for compiling, but
not executing. For example,
(eval-when-compile
(require 'my-macro-package))
The same sort of thing goes for macros and defsubst functions defined locally and
only for use within the file. They are needed for compiling the file, but in most cases
they are not needed for execution of the compiled file. For example,
(eval-when-compile
(unless (fboundp 'some-new-thing)
(defmacro 'some-new-thing ()
(compatibility code))))
This is often good for code that’s only a fallback for compatibility with other versions
of Emacs.
Common Lisp Note: At top level, eval-when-compile is analogous to the Common
Lisp idiom (eval-when (compile eval) ...). Elsewhere, the Common Lisp ‘#.’
reader macro (but not when interpreting) is closer to what eval-when-compile does.
The call to func must be in the then-form of the if, and func must appear quoted in
the call to fboundp. (This feature operates for cond as well.)
• Likewise, you can suppress the warning for a specific use of a variable variable by
conditionalizing it on a boundp test:
(if (boundp 'variable) ...variable...)
The reference to variable must be in the then-form of the if, and variable must appear
quoted in the call to boundp.
• You can tell the compiler that a function is defined using declare-function. See
Section 13.15 [Declaring Functions], page 232.
• Likewise, you can tell the compiler that a variable is defined using defvar with no
initial value. (Note that this marks the variable as special, i.e. dynamically bound, but
only within the current lexical scope, or file if at top-level.) See Section 12.5 [Defining
Variables], page 173.
You can also suppress any and all compiler warnings within a certain expression using
the construct with-no-warnings:
Byte compiler warnings can be controlled more precisely by setting the variable
byte-compile-warnings. See its documentation string for details.
Sometimes you may wish the byte-compiler warnings to be reported using error. If so,
set byte-compile-error-on-warn to a non-nil value.
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).
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.
(defun factorial (integer)
"Compute factorial of an integer."
(if (= 1 integer) 1
(* integer (factorial (1- integer)))))
⇒ factorial
(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)
;; (In effect, the sequence dup varset copies the top of the stack
;; into the value of n without popping it.)
The value can also be a list of error conditions (see Section 11.7.3.1 [Signaling Errors],
page 160). Then the debugger is called only for error conditions in this list (except
those also listed in debug-ignored-errors). For example, if you set debug-on-error
to the list (void-variable), the debugger is only called for errors about a variable
that has no value.
Note that eval-expression-debug-on-error overrides this variable in some cases;
see below.
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 38 [Processes], page 919.
debug-on-message [Variable]
If you set debug-on-message to a regular expression, Emacs will enter the debugger
if it displays a matching message in the echo area. For example, this can be useful
when trying to find the cause of a particular message.
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.
(i.e., those written in C) this way, but it only takes effect when the primitive is called
from Lisp code. Debug-on-entry is not allowed for special forms.
When debug-on-entry is called interactively, it prompts for function-name in
the minibuffer. If the function is already set up to invoke the debugger on entry,
debug-on-entry does nothing. debug-on-entry always returns function-name.
Here’s an example to illustrate use of this function:
(defun fact (n)
(if (zerop n) 1
(* n (fact (1- n)))))
⇒ fact
(debug-on-entry 'fact)
⇒ fact
(fact 3)
If a function name is underlined, that means the debugger knows where its source code
is located. You can click with the mouse 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.
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))
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.
Chapter 18: Debugging Lisp Programs 298
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.
This variable is obsolete and will be removed in future versions.
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 information on function calls and returns.
• 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 start using it.
When Edebug is about to instrument code for the first time in a session, it runs the hook
edebug-setup-hook, then sets it to nil. You can use this to load Edebug specifications
associated with a package you are using, but only when you use Edebug.
If Edebug detects a syntax error while instrumenting, it leaves point at the erroneous
code and signals an invalid-read-syntax error. Example:
error Invalid read syntax: "Expected lambda expression"
One potential reason for such a failure to instrument is that some macro definitions are
not yet known to Emacs. To work around this, load the file which defines the function you
are about to instrument.
To remove instrumentation from a definition, simply re-evaluate its definition in a way
that does not instrument. There are two ways of evaluating forms that never instrument
them: from a file with load, and from the minibuffer with eval-expression (M-:).
See Section 18.2.9 [Edebug Eval], page 306, for other evaluation functions available inside
of Edebug.
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.
When you enter a new Edebug level, Edebug will normally stop at the first instrumented
function it encounters. If you prefer to stop only at a break point, or not at all (for example,
when gathering coverage data), change the value of edebug-initial-mode from its default
step to go, or Go-nonstop, or one of its other values (see Section 18.2.16 [Edebug Options],
page 317). You can do this readily with C-x C-a C-m (edebug-set-initial-mode):
edebug-set-initial-mode [Command]
This command, bound to C-x C-a C-m, sets edebug-initial-mode. It prompts you
for a key to indicate the mode. You should enter one of the eight keys listed above,
which sets the corresponding 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.
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 in Section 18.2.16 [Edebug Options], page 317.
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 304, 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 (edebug-step-out).
i Step into the function or macro called by the form after point (edebug-step-
in).
Chapter 18: Debugging Lisp Programs 303
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 forward-sexp 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 forward-sexp 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
(edebug-where) 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.
Normally, the h, f, and o commands display “Break” and pause for edebug-sit-for-
seconds before showing the result of the form just evaluated. You can avoid this pause by
setting edebug-sit-on-break to nil. See Section 18.2.16 [Edebug Options], page 317.
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.
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.
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. Edebug
tries to be invisible to the expression’s evaluation and printing. Evaluation of expressions
that cause side effects will work as expected, except for changes to data that Edebug ex-
plicitly saves and restores. See Section 18.2.14 [The Outside Context], page 310, 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.
Chapter 18: Debugging Lisp Programs 307
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.
Other programs can also use custom printing; see cust-print.el for details.
edebug-tracing and edebug-trace insert lines in the trace buffer whenever they are
called, even if Edebug is not active. Adding text to the trace buffer also scrolls its window
to show the last lines inserted.
even if the execution mode is Go-nonstop, and regardless of whether coverage testing is
enabled.
Use C-x X = (edebug-display-freq-count) to display both the coverage information
and the frequency counts for a definition. Just = (edebug-temp-display-freq-count)
displays the same information temporarily, only until you type another key.
edebug-display-freq-count [Command]
This command displays the frequency count data for each line of the current definition.
It inserts frequency counts as comment lines after each line of code. 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.
on the stack. You could, however, still run out of stack space when using Edebug.
You can also enlarge the value of edebug-max-depth if Edebug reaches the limit of
recursion depth instrumenting code that contains very large quoted lists.
• The state of keyboard macro execution is saved and restored. While Edebug is active,
executing-kbd-macro is bound to nil unless edebug-continue-kbd-macro is non-
nil.
Edebug cannot save and restore the value of unread-command-events. Entering Ede-
bug while this variable has a nontrivial value can interfere with execution of the program
you are debugging.
• Complex commands executed while in Edebug are added to the variable
command-history. In rare cases this can alter execution.
• Within Edebug, the recursion depth appears one deeper than the recursion depth
outside Edebug. This is not true of the automatically updated evaluation list window.
• standard-output and standard-input are bound to nil by the recursive-edit, but
Edebug temporarily restores them during evaluations.
• The state of keyboard macro definition is saved and restored. While Edebug is active,
defining-kbd-macro is bound to edebug-continue-kbd-macro.
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 14.4 [Defining Macros], page 238, for more explanation of the declare form.
Take care to ensure that the specifications are known to Edebug when you instrument
code. If you are instrumenting a function which uses a macro defined in another file, you
may first need to either evaluate the require forms in the file containing your function,
or explicitly load the file containing the macro. If the definition of a macro is wrapped by
eval-when-compile, you may need to evaluate it.
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.
Chapter 18: Debugging Lisp Programs 313
place A generalized variable. See Section 12.17 [Generalized Variables], page 200.
body Short for &rest form. See &rest below. If your macro wraps its body of code
with lambda before it is evaluated, use def-body instead. See def-body 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. Edebug’s definition of a
defining form is a form containing one or more code forms which are saved and
executed later, after the execution of the 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 instru-
mented. 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
used to generate more specific syntax error messages. See Section 18.2.15.3
[Backtracking], page 316, for more details. Also see the let example.
Chapter 18: Debugging Lisp Programs 315
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 if the predicate returns nil, the specification fails and the
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.
: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.
Chapter 18: Debugging Lisp Programs 316
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 it is used 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 let
((&rest
&or symbolp (gate symbolp &optional form))
body))
Edebug uses the following specifications for defun and the associated argument list and
interactive specifications. It is necessary to handle interactive forms specially since an
expression argument is actually evaluated outside of the function body. (The specification
for defmacro is very similar to that for defun, but allows for the declare statement.)
(def-edebug-spec defun
(&define name lambda-list
[&optional stringp] ; Match the doc string, if present.
[&optional ("interactive" interactive)]
def-body))
(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 is a little different, and 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))
Edebug also has a coverage testing feature (see Section 18.2.13 [Coverage Testing],
page 309). These features partly duplicate each other, and it would be cleaner to com-
bine them.
Chapter 18: Debugging Lisp Programs 322
18.5 Profiling
If your program is working correctly, but not fast enough, and you want to make it run
more quickly or efficiently, the first thing to do is profile your code so that you know where
it spends most of the execution time. If you find that one particular function is responsible
for a significant portion of the execution time, you can start looking for ways to optimize
that piece.
Emacs has built-in support for this. To begin profiling, type M-x profiler-start. You
can choose to profile by processor usage, memory usage, or both. Then run the code you’d
like to speed up. After that, type M-x profiler-report to display a summary buffer
for each resource (cpu and memory) that you chose to profile. The names of the report
buffers include the times at which the reports were generated, so you can generate another
report later on without erasing previous results. When you have finished profiling, type M-x
profiler-stop (there is a small overhead associated with profiling, so we don’t recommend
leaving it active except when you are actually running the code you want to examine).
The profiler report buffer shows, on each line, a function that was called, followed by how
much resources (cpu or memory) it used in absolute and percentage terms since profiling
started. If a given line has a ‘+’ symbol at the left-hand side, you can expand that line by
typing RET, in order to see the function(s) called by the higher-level function. Use a prefix
argument (C-u RET) to see the whole call tree below a function. Pressing RET again will
collapse back to the original state.
Press j or mouse-2 to jump to the definition of a function at point. Press d to view a
function’s documentation. You can save a profile to a file using C-x C-w. You can compare
two profiles using =.
The elp library offers an alternative approach, which is useful when you know in ad-
vance which Lisp function(s) you want to profile. Using that library, you begin by setting
elp-function-list to the list of function symbols—those are the functions you want to
profile. Then type M-x elp-instrument-list RET nil RET to arrange for profiling those
functions. After running the code you want to profile, invoke M-x elp-results to display
the current results. See the file elp.el for more detailed instructions. This approach is
limited to profiling functions written in Lisp, it cannot profile Emacs primitives.
You can measure the time it takes to evaluate individual Emacs Lisp forms using
the benchmark library. See the macros benchmark-run and benchmark-run-compiled in
benchmark.el. You can also use the benchmark command for timing forms interactively.
323
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.
In the functions below, stream stands for an input stream (see the previous section). If
stream is nil or omitted, it defaults to the value of standard-input.
An end-of-file error is signaled if reading encounters an unterminated list, vector, or
string.
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.
read-circle [Variable]
If non-nil, this variable enables the reading of circular and shared structures. See
Section 2.5 [Circular Objects], page 28. Its default value is t.
When reading or writing from the standard input/output streams of the Emacs process
in batch mode, it is sometimes required to make sure any arbitrary binary data will be
read/written verbatim, and/or that no translation of newlines to or from CR-LF pairs is
performed. This issue does not exist on POSIX hosts, only on MS-Windows and MS-DOS.
The following function allows you to control the I/O mode of any standard stream of the
Emacs process.
Chapter 19: Reading and Printing Lisp Objects 327
buffer The output characters are inserted into buffer at point. Point advances as
characters are inserted.
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 72). 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.
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-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.
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.
See Section 2.5 [Circular Objects], page 28.
print-gensym [Variable]
If non-nil, this variable enables detection of uninterned symbols (see Section 9.3
[Creating Symbols], page 122) 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. The default is nil, mean-
ing use the shortest output that represents the number without losing information.
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.
334
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 39.4 [The Echo Area], page 969),
but only while it is in use for reading an argument.
local map according to the job to be done. See Section 20.2 [Text from Minibuffer], page 335,
for the non-completion minibuffer local maps. See Section 20.6.3 [Completion Commands],
page 347, for the minibuffer local maps for completion.
When a minibuffer is inactive, its major mode is minibuffer-inactive-mode, with
keymap minibuffer-inactive-mode-map. This is only really useful if the minibuffer is in
a separate frame. See Section 29.9 [Minibuffers and Frames], page 719.
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.
This supports only basic input: none of the special minibuffer features (history, completion,
etc.) are available in batch mode.
keymap. Specifying a keymap is the most important way to customize the minibuffer
for various applications such as completion.
The argument history specifies a history list variable to use for saving the input and for
history commands used in the minibuffer. It defaults to minibuffer-history. You
can optionally specify a starting position in the history list as well. See Section 20.4
[Minibuffer History], page 340.
If the variable minibuffer-allow-text-properties is non-nil, then the string that
is returned includes whatever text properties were present in the minibuffer. Other-
wise all the text properties are stripped when the value is returned.
The text properties in minibuffer-prompt-properties are applied to the prompt.
By default, this property list defines a face to use for the prompt. This face, if present,
is applied to the end of the face list and merged before display.
If the user wants to completely control the look of the prompt, the most convenient
way to do that is to specify the default face at the end of all face lists. For instance:
(read-from-minibuffer
(concat
(propertize "Bold" 'face '(bold default))
(propertize " and normal: " 'face '(default))))
If the argument inherit-input-method is non-nil, then the minibuffer inherits the
current input method (see Section 33.11 [Input Methods], page 862) and the setting of
enable-multibyte-characters (see Section 33.1 [Text Representations], page 835)
from whichever buffer was current before entering the minibuffer.
Use of initial is mostly deprecated; we recommend using a non-nil value only in
conjunction with specifying a cons cell for history. See Section 20.5 [Initial Input],
page 342.
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
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
The user can type RET immediately to use the initial input as a default, or can edit
the input.
Typing RET right away would exit the minibuffer and evaluate the expression, thus
moving point forward one word.
Chapter 20: Minibuffers 340
If you don’t specify history, then the default history list minibuffer-history is used.
For other standard history lists, see below. You can also create your own history list
variable; just initialize it to nil before the first use.
Both read-from-minibuffer and completing-read add new elements to the history
list automatically, and provide commands to allow the user to reuse items on the list. The
only thing your program needs to do to use a history list is to initialize it and to pass its
name to the input functions when you wish. But it is safe to modify the list by hand when
the minibuffer input functions are not using it.
Emacs functions that add a new element to a history list can also delete old elements
if the list gets too long. The variable history-length specifies the maximum length for
most history lists. To specify a different maximum length for a particular history list,
put the length in the history-length property of the history list symbol. The variable
history-delete-duplicates specifies whether to delete duplicates in history.
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. The default value is t.
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.
face-name-history [Variable]
A history list for arguments that are faces.
Chapter 20: Minibuffers 342
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.
(all-completions
"foo"
'(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
'test)
⇒ ("foobar1" "foobar2")
Normally completion operates on the whole string, so for all normal collections,
this will always return (0 . (length suffix)). But more complex completion
such as completion on files is done one field at a time. For example, completion
of "/usr/sh" will include "/usr/share/" but not "/usr/share/doc" even if
"/usr/share/doc" exists. Also all-completions on "/usr/sh" will not include
"/usr/share/" but only "share/". So if string is "/usr/sh" and suffix is "e/doc",
completion-boundaries will return (5 . 1) which tells us that the collection will
only return completion information that pertains to the area after "/usr/" and
before "/doc".
If you store a completion alist in a variable, you should mark the variable as risky
by giving it a non-nil risky-local-variable property. See Section 12.12 [File Local
Variables], page 191.
completion-ignore-case [Variable]
If the value of this variable is non-nil, case is not considered significant in
completion. Within read-file-name, this variable is overridden by read-file-
name-completion-ignore-case (see Section 20.6.5 [Reading File Names], page 351);
within read-buffer, it is overridden by read-buffer-completion-ignore-case
(see Section 20.6.4 [High-Level Completion], page 349).
completion-regexp-list [Variable]
This is a list of regular expressions. The completion functions only consider a com-
pletion acceptable if it matches all regular expressions in this list, with case-fold-
search (see Section 34.2 [Searching and Case], page 867) bound to the value of
completion-ignore-case.
There are several functions that take an existing completion table and return
a modified version. completion-table-case-fold returns a case-insensitive table.
completion-table-in-turn and completion-table-merge combine multiple input
tables in different ways. completion-table-subvert alters a table to use a different
initial prefix. completion-table-with-quoting returns a table suitable for operating on
quoted text. completion-table-with-predicate filters a table with a predicate function.
completion-table-with-terminator adds a terminating string.
completing-read-function [Variable]
The value of this variable must be a function, which is called by completing-read
to actually do its work. It should accept the same arguments as completing-read.
This can be bound to a different function to completely override the normal behavior
of completing-read.
minibuffer-completion-table [Variable]
The value of this variable is the completion table (see Section 20.6.1 [Basic Comple-
tion], page 342) 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]
This variable determines whether Emacs asks for confirmation before exit-
ing the minibuffer; completing-read binds this variable, and the function
minibuffer-complete-and-exit checks the value before exiting. If the value
is nil, confirmation is not required. If the value is confirm, the user may exit
with an input that is not a valid completion alternative, but Emacs asks for
confirmation. If the value is confirm-after-completion, the user may exit with
an input that is not a valid completion alternative, but Emacs asks for confirmation
Chapter 20: Minibuffers 348
if the user submitted the input right after any of the completion commands in
minibuffer-confirm-exit-commands.
minibuffer-confirm-exit-commands [Variable]
This variable holds a list of commands that cause Emacs to ask for confirmation
before exiting the minibuffer, if the require-match argument to completing-read is
confirm-after-completion. The confirmation is requested if the user attempts to
exit the minibuffer immediately after calling any command in this list.
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 892.
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*.
display-completion-list completions [Function]
This function displays completions to the stream in standard-output, usually a
buffer. (See Chapter 19 [Read and Print], page 323, for more information about
streams.) The argument completions is normally a list of completions just returned
by all-completions, but it does not have to be. Each element may be a symbol or
a string, either of which is simply printed. It can also be a list of two strings, which is
printed as if the strings were concatenated. The first of the two strings is the actual
completion, the second string serves as annotation.
This function is called by minibuffer-completion-help. A common way to use it
is together with with-output-to-temp-buffer, like this:
(with-output-to-temp-buffer "*Completions*"
(display-completion-list
(all-completions (buffer-string) my-alist)))
completion-auto-help [User Option]
If this variable is non-nil, the completion commands automatically display a list of
possible completions whenever nothing can be completed because the next character
is not uniquely determined.
Chapter 20: Minibuffers 349
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
TAB minibuffer-complete
and uses minibuffer-local-map as its parent keymap (see [Definition of minibuffer-
local-map], page 338).
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:
C-j minibuffer-complete-and-exit
RET minibuffer-complete-and-exit
and uses minibuffer-local-completion-map as its parent keymap.
minibuffer-local-filename-completion-map [Variable]
This is a sparse keymap that simply unbinds SPC; because filenames can
contain spaces. The function read-file-name combines this keymap with either
minibuffer-local-completion-map or minibuffer-local-must-match-map.
The optional argument predicate, if non-nil, specifies a function to filter the buffers
that should be considered: the function will be called with every potential candidate
as its argument, and should return nil to reject the candidate, non-nil to accept it.
In the following example, the user enters ‘minibuffer.t’, and then types RET. The
argument require-match 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:
The exact behavior when using a graphical file dialog is platform-dependent. Here,
we simply document the behavior when using the minibuffer.
read-file-name does not automatically expand the returned file name. You can call
expand-file-name yourself if an absolute file name is required.
The optional argument require-match has the same meaning as in completing-read.
See Section 20.6.2 [Minibuffer Completion], page 345.
The argument directory specifies the directory to use for completing relative file
names. It should be an absolute directory name. If the variable insert-default-
directory is 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 in a buffer visiting a file. 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 require-
match. However, if require-match 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 require-match. 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 alternatives. A file name is an acceptable value if
predicate returns non-nil for it.
Here is an example of using read-file-name:
Chapter 20: Minibuffers 353
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 argu-
ments instead of doing its usual work.
For example:
;; Here the minibuffer starts out with the default directory.
(let ((insert-default-directory t))
(read-file-name "The file is "))
completion-extra-properties [Variable]
This variable is used to specify extra properties of the current completion command.
It is intended to be let-bound by specialized completion commands. Its value should
be a list of property and value pairs. The following properties are supported:
:annotation-function
The value should be a function to add annotations in the completions
buffer. This function must accept one argument, a completion, and should
either return nil or a string to be displayed next to the completion.
Chapter 20: Minibuffers 356
:exit-function
The value should be a function to run after performing completion. The
function should accept two arguments, string and status, where string
is the text to which the field was completed, and status indicates what
kind of operation happened: finished if text is now complete, sole if
the text cannot be further completed but completion is not finished, or
exact if the text is a valid completion but may be further completed.
If the flag has any other value, the completion function should return nil.
The following is a list of metadata entries that a completion function may return in
response to a metadata flag argument:
category The value should be a symbol describing what kind of text the completion
function is trying to complete. If the symbol matches one of the keys in
completion-category-overrides, the usual completion behavior is overrid-
den. See Section 20.6.6 [Completion Variables], page 354.
annotation-function
The value should be a function for annotating completions. The function should
take one argument, string, which is a possible completion. It should return a
string, which is displayed after the completion string in the *Completions*
buffer.
display-sort-function
The value should be a function for sorting completions. The function should
take one argument, a list of completion strings, and return a sorted list of
completion strings. It is allowed to alter the input list destructively.
cycle-sort-function
The value should be a function for sorting completions, when
completion-cycle-threshold is non-nil and the user is cycling through
completion alternatives. See Section “Completion Options” in The GNU
Emacs Manual. Its argument list and return value are the same as for
display-sort-function.
completion-table-dynamic function &optional switch-buffer [Function]
This function is a convenient way to write a function that can act as a programmed
completion function. The argument function should be a function that takes one
argument, a string, and returns a completion table (see Section 20.6.1 [Basic Com-
pletion], page 342) containing all the possible completions. The table returned by
function can also include elements that don’t match the string argument; they are
automatically filtered out by completion-table-dynamic. In particular, function
can ignore its argument and return a full list of all possible completions. You can
think of completion-table-dynamic as a transducer between function and the in-
terface for programmed completion functions.
If the optional argument switch-buffer is non-nil, and completion is performed in the
minibuffer, function will be called with current buffer set to the buffer from which
the minibuffer was entered.
The return value of completion-table-dynamic is a function that can be used as
the 2nd argument to try-completion and all-completions. Note that this func-
tion will always return empty metadata and trivial boundaries (see Section 20.6.7
[Programmed Completion], page 356).
completion-table-with-cache function &optional ignore-case [Function]
This is a wrapper for completion-table-dynamic that saves the last argument-result
pair. This means that multiple lookups with the same argument only need to call
function once. This can be useful when a slow operation is involved, such as calling
an external process.
Chapter 20: Minibuffers 358
completion-at-point-functions [Variable]
The value of this abnormal hook should be a list of functions, which are used to
compute a completion table (see Section 20.6.1 [Basic Completion], page 342) for
completing the text at point. It can be used by major modes to provide mode-specific
completion tables (see Section 23.2.1 [Major Mode Conventions], page 456).
When the command completion-at-point runs, it calls the functions in the list one
by one, without any argument. Each function should return nil unless it can and
wants to take responsibility for the completion data for the text at point. Otherwise
it should return a list of the following form:
(start end collection . props)
start and end delimit the text to complete (which should enclose point). collection is
a completion table for completing that text, in a form suitable for passing as the sec-
ond argument to try-completion (see Section 20.6.1 [Basic Completion], page 342);
completion alternatives will be generated from this completion table in the usual way,
via the completion styles defined in completion-styles (see Section 20.6.6 [Comple-
tion Variables], page 354). props is a property list for additional information; any of
the properties in completion-extra-properties are recognized (see Section 20.6.6
[Completion Variables], page 354), as well as the following additional ones:
:predicate
The value should be a predicate that completion candidates need to sat-
isfy.
:exclusive
If the value is no, then if the completion table fails to match the text
at point, completion-at-point moves on to the next function in
completion-at-point-functions instead of reporting a completion
failure.
The functions on this hook should generally return quickly, since they may be called
very often (e.g., from post-command-hook). Supplying a function for collection is
strongly recommended if generating the list of completions is an expensive opera-
tion. Emacs may internally call functions in completion-at-point-functions many
times, but care about the value of collection for only some of these calls. By supply-
ing a function for collection, Emacs can defer generating completions until necessary.
You can use completion-table-dynamic to create a wrapper function:
;; Avoid this pattern.
(let ((beg ...) (end ...) (my-completions (my-make-completions)))
(list beg end my-completions))
(list beg
end
(completion-table-dynamic
(lambda (_)
(my-make-completions)))))
Additionally, the collection should generally not be pre-filtered based on the cur-
rent text between start and end, because that is the responsibility of the caller of
completion-at-point-functions to do that according to the completion styles it
decides to use.
A function in completion-at-point-functions may also return a function instead
of a list as described above. In that case, that returned function is called, with no
argument, and it is entirely responsible for performing the completion. We discourage
this usage; it is only intended to help convert old code to using completion-at-point.
The first function in completion-at-point-functions to return a non-nil value
is used by completion-at-point. The remaining functions are not called. The
exception to this is when there is an :exclusive specification, as described above.
look like a minibuffer and for that reason the user might try to use C-] to get out.
The answer is a single character, with no RET needed to terminate it. Upper and
lower case are equivalent.
“Asking the question” means printing prompt in the echo area, followed by the string
‘(y or n) ’. If the input is not one of the expected answers (y, n, SPC, DEL, or
something that quits), the function responds ‘Please answer y or n.’, and repeats
the request.
This function does not actually use the minibuffer, since it does not allow editing
of the answer. It actually uses the echo area (see Section 39.4 [The Echo Area],
page 969), which uses the same screen space as the minibuffer. The cursor moves to
the echo area while the question is being asked.
The answers and their meanings, even ‘y’ and ‘n’, are not hardwired, and are spec-
ified by the keymap query-replace-map (see Section 34.7 [Search and Replace],
page 887). In particular, if the user enters the special responses recenter, scroll-up,
scroll-down, scroll-other-window, or scroll-other-window-down (respectively
bound to C-l, C-v, M-v, C-M-v and C-M-S-v in query-replace-map), this function
performs the specified window recentering or scrolling operation, and poses the ques-
tion again.
We show successive lines of echo area messages, but only one actually appears on the
screen at a time.
You can use action-alist to specify additional possible answers and what they mean.
It is an alist of elements of the form (char function help), each of which defines
one additional answer. In this element, char is a character (the answer); function is
a function of one argument (an object from list); help is a string.
When the user responds with char, map-y-or-n-p calls function. If it returns non-
nil, the object is considered acted upon, and map-y-or-n-p advances to the next
object in list. If it returns nil, the prompt is repeated for the same object.
Normally, map-y-or-n-p binds cursor-in-echo-area while prompting. But if no-
cursor-in-echo-area is non-nil, it does not do that.
If map-y-or-n-p is called in a command that was invoked using the mouse—more
precisely, if last-nonmenu-event (see Section 21.5 [Command Loop Info], page 378)
is either nil or a list—then it uses a dialog box or pop-up menu to ask the question.
In this case, it does not use keyboard input or the echo area. You can force use either
of the mouse or of keyboard input by binding last-nonmenu-event to a suitable
value around the call.
The return value of map-y-or-n-p is the number of objects acted on.
If you need to ask the user a question that might have more than just 2 answers, use
read-answer.
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-event; see Section 21.5 [Command Loop Info],
page 378).
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.
previous-complete-history-element n [Command]
This command replaces the minibuffer contents with the value of the nth previous
(older) history element that completes the current contents of the minibuffer before
the point.
Chapter 20: Minibuffers 364
next-complete-history-element n [Command]
This command replaces the minibuffer contents with the value of the nth next (newer)
history element that completes the current contents of the minibuffer before the point.
The following function returns the window showing the currently active minibuffer.
active-minibuffer-window [Function]
This function returns the window of the currently active minibuffer, or nil if there
is no active minibuffer.
It is not sufficient to determine whether a given window shows the currently active
minibuffer by comparing it with the result of (minibuffer-window), because there can be
more than one minibuffer window if there is more than one frame.
The following two options control whether minibuffer windows are resized automatically
and how large they can get in the process.
the value is nil, a minibuffer window never changes size automatically. In that case
the window resizing commands (see Section 28.4 [Resizing Windows], page 608) can
be used to adjust its height.
max-mini-window-height [User Option]
This option provides a maximum height for resizing minibuffer windows automatically.
A floating-point number specifies a fraction of the frame’s height; an integer specifies
the maximum number of lines. The default value is 0.25.
Note that the values of the above two variables take effect at display time, so let-binding
them around code which produces echo-area messages will not work. If you want to prevent
resizing of minibuffer windows when displaying long messages, bind the message-truncate-
lines variable instead (see Section 39.4.4 [Echo Area Customization], page 973).
minibuffer-inactive-mode [Command]
This is the major mode used in inactive minibuffers. It uses keymap
minibuffer-inactive-mode-map. This can be useful if the minibuffer is in a
separate frame. See Section 29.9 [Minibuffers and Frames], page 719.
368
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.
all its body forms are executed; at this time, if the interactive form occurs within
the body, the form simply returns nil without even evaluating its argument.
By convention, you should put the interactive form in the function body, as the
first top-level form. If there is an interactive form in both the interactive-form
symbol property and the function body, the former takes precedence. The
interactive-form symbol property can be used to add an interactive form to an
existing function, or change how its arguments are processed interactively, without
redefining the function.
(see Chapter 20 [Minibuffers], page 334) or directly from the keyboard (see Section 21.8
[Reading Input], page 397).
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).
interactive-form function [Function]
This function returns the interactive form of function. If function is an interac-
tively callable function (see Section 21.3 [Interactive Call], page 375), the value is the
command’s interactive form (interactive spec), which specifies how to compute
its arguments. Otherwise, the value is nil. If function is a symbol, its function
definition is used.
Even though the code letter doesn’t use a prompt string, you must follow it
with a newline if it is not the last code character in the string.
Prompt A prompt immediately follows the code character. The prompt ends either with
the end of the string or with a newline.
Special This code character is meaningful only at the beginning of the interactive string,
and it does not look for a prompt or a newline. It is a single, isolated character.
Here are the code character descriptions for use with interactive:
‘*’ Signal an error if the current buffer is read-only. Special.
‘@’ Select the window mentioned in the first mouse event in the key sequence that
invoked this command. Special.
‘^’ If the command was invoked through shift-translation, set the mark and activate
the region temporarily, or extend an already active region, before the command
is run. If the command was invoked without shift-translation, and the region is
temporarily active, deactivate the region before the command is run. Special.
‘a’ A function name (i.e., a symbol satisfying fboundp). Existing, Completion,
Prompt.
‘b’ The name of an existing buffer. By default, uses the name of the current buffer
(see Chapter 27 [Buffers], page 581). Existing, Completion, Default, Prompt.
‘B’ A buffer name. The buffer need not exist. By default, uses the name of a re-
cently used buffer other than the current buffer. Completion, Default, Prompt.
‘c’ A character. The cursor does not move into the echo area. Prompt.
‘C’ A command name (i.e., a symbol satisfying commandp). Existing, Completion,
Prompt.
‘d’ The position of point, as an integer (see Section 30.1 [Point], page 742). No
I/O.
‘D’ A directory. The default is the current default directory of the current buffer,
default-directory (see Section 25.9.4 [File Name Expansion], page 550). Ex-
isting, Completion, Default, Prompt.
‘e’ The first or next non-keyboard 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.7 [Input Events], page 381. No I/O.
You use ‘e’ for mouse events and for special system events (see Section 21.7.10
[Misc Events], page 388). The event list that the command receives depends on
the event. See Section 21.7 [Input Events], page 381, which describes the forms
of the list for each event in the corresponding subsections.
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.
Chapter 21: Command Loop 373
‘f’ A file name of an existing file (see Section 25.9 [File Names], page 546). 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 415). 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.12 [Prefix Command
Arguments], page 408. 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. This will
signal an error if the mark is not set in the buffer which is current when the
command is invoked. No I/O.
‘s’ Arbitrary text, read in the minibuffer and returned as a string (see Section 20.2
[Text from Minibuffer], page 335). Terminate the input with either C-j or RET.
(C-q may be used to include either of these characters in the input.) Prompt.
Chapter 21: Command Loop 374
‘S’ An interned symbol whose name is read in the minibuffer. Terminate the input
with either C-j or RET. Other characters that normally terminate a symbol
(e.g., whitespace, 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
custom-variable-p). This reads the variable using read-variable. See
[Definition of read-variable], page 351. 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 338.
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 848. 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.
(delete-other-windows)
(split-window (selected-window) 8)
(switch-to-buffer b1)
(other-window 1)
(split-window (selected-window) 8)
(switch-to-buffer b2)
(other-window 1)
(switch-to-buffer b3))
⇒ three-b
(three-b "*scratch*" "declarations.texi" "*mail*")
⇒ nil
The argument special, if given, means to ignore the prefix argument and not clear it.
This is used for executing special events (see Section 21.9 [Special Events], page 405).
execute-extended-command prefix-argument [Command]
This function reads a command name from the minibuffer using completing-read
(see Section 20.6 [Completion], page 342). Then it uses command-execute to call
the specified command. Whatever that command returns becomes the value of
execute-extended-command.
If the command asks for a prefix argument, it receives the value prefix-argument. If
execute-extended-command is called interactively, the current raw prefix argument
is used for prefix-argument, and thus passed on to whatever command is run.
execute-extended-command is the normal definition of M-x, so it uses the string
‘M-x ’ as a prompt. (It would be better to take the prompt from the events used to
invoke execute-extended-command, but that is painful to implement.) A description
of the value of the prefix argument, if any, also becomes part of the prompt.
(execute-extended-command 3)
---------- Buffer: Minibuffer ----------
3 M-x forward-word RET
---------- Buffer: Minibuffer ----------
⇒ t
If in doubt, use any; the only known proper use of interactive is if you need to
decide whether to display a helpful message while a function is running.
A function is never considered to be called interactively if it was called via Lisp
evaluation (or with apply or funcall).
(foo)
⇒ nil
Here is another example that contrasts direct and indirect calls to called-interactively-
p.
(defun bar ()
(interactive)
(message "%s" (list (foo) (called-interactively-p 'any))))
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 Terminals], page 685.
real-last-command [Variable]
This variable is set up by Emacs just like last-command, but never altered by Lisp
programs.
Chapter 21: Command Loop 379
last-repeatable-command [Variable]
This variable stores the most recently executed command that was not part of an
input event. This is the command repeat will try to repeat, See Section “Repeating”
in The GNU Emacs Manual.
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 433). 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
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.8.1 [Key Sequence Input], page 397. The value is a string if
all events in the sequence were characters that fit in a string. See Section 21.7 [Input
Events], page 381.
(this-command-keys)
;; Now use C-u C-x C-e to evaluate that.
⇒ "^U^X^E"
Chapter 21: Command Loop 380
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.7.15 [Strings of Events], page 396).
clear-this-command-keys &optional keep-record [Function]
This function empties out the table of events for this-command-keys to return. Un-
less keep-record is non-nil, it also empties the records that the function recent-keys
(see Section 40.13.2 [Recording Input], page 1098) will subsequently return. This is
useful after reading a password, to prevent the password from echoing inadvertently
as part of the next command in certain cases.
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 359).
last-command-event [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.
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.10 [Input Focus], page 720.
If the last event came from a keyboard macro, the value is macro.
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.
super The 223 bit in the character event code indicates a character typed with the
super key held down.
alt The 222 bit in the character event code indicates a character typed with the alt
key held down. (The key labeled Alt on most keyboards is actually treated as
the meta key, not this.)
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.7.12 [Classifying
Events], page 391). 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 430). The function event-convert-list converts such a
list into an event type (see Section 21.7.12 [Classifying Events], page 391).
This symbol also serves as the event type of the event. Key bindings describe
events by their types; thus, if there is a key binding for mouse-1, that binding
would apply to all events whose event-type is mouse-1.
position This is a mouse position list specifying where the mouse click occurred; see
below for details.
click-count
This is the number of rapid repeated presses so far of the same mouse button.
See Section 21.7.7 [Repeat Events], page 386.
To access the contents of a mouse position list in the position slot of a click event,
you should typically use the functions documented in Section 21.7.13 [Accessing Mouse],
page 393. The explicit format of the list depends on where the click occurred. For clicks in
the text area, mode line, header line, or in the fringe or marginal areas, the mouse position
list has the form
(window pos-or-area (x . y) timestamp
object text-pos (col . row)
image (dx . dy) (width . height))
The meanings of these list elements are as follows:
window The window in which the click occurred.
pos-or-area
The buffer position of the character clicked on in the text area; or, if the click was
outside the text area, the window area where it occurred. It is one of the sym-
bols mode-line, header-line, vertical-line, left-margin, right-margin,
left-fringe, or right-fringe.
In one special case, pos-or-area 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 registered by Emacs. See Section 21.8.1 [Key Sequence
Input], page 397.
x, y The relative pixel coordinates of the click. For clicks in the text area of a
window, the coordinate origin (0 . 0) is taken to be the top left corner of the
text area. See Section 28.3 [Window Sizes], page 603. For clicks in a mode
line or header line, the coordinate origin is the top left corner of the window
itself. For fringes, margins, and the vertical border, x does not have meaningful
data. For fringes and margins, y is relative to the bottom edge of the header
line. In all cases, the x and y coordinates increase rightward and downward
respectively.
timestamp
The time at which the event occurred, as an integer number of milliseconds
since a system-dependent initial time.
object Either nil, which means the click occurred on buffer text, or a cons cell of the
form (string . string-pos) if there is a string from a text property or an overlay
at the click position.
string The string which was clicked on, including any properties.
Chapter 21: Command Loop 385
The event type of a double-click event contains the prefix ‘double-’. Thus, a double click
on the second mouse button with meta held down comes to the Lisp program as M-double-
mouse-2. If a double-click event has no binding, the binding of the corresponding ordinary
click event is used to execute it. Thus, you need not pay attention to the double click
feature unless you really want to.
When the user performs a double click, Emacs generates first an ordinary click event, and
then a double-click event. Therefore, you must design the command binding of the double
click event to assume that the single-click command has already run. It must produce the
desired results of a double click, starting from the results of a single click.
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.
(iconify-frame (frame))
This kind of event indicates that the user iconified frame using the window
manager. Its standard definition is ignore; since the frame has already been
iconified, Emacs has no work to do. The purpose of this event type is so that
you can keep track of such events if you want to.
(make-frame-visible (frame))
This kind of event indicates that the user deiconified frame using the window
manager. Its standard definition is ignore; since the frame has already been
made visible, Emacs has no work to do.
(wheel-up position)
(wheel-down position)
These kinds of event are generated by moving a mouse wheel. The position
element is a mouse position list (see Section 21.7.4 [Click Events], page 383),
specifying the position of the mouse cursor when the event occurred.
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 (see Section 21.7.4 [Click Events],
page 383), 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 809.
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. They can be useful for debugging (see Section 18.1.1
[Error Debugging], page 289).
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 422). The
command is called with no arguments, and the specific signal event is available
in last-input-event. For example:
(defun sigusr-handler ()
Chapter 21: Command Loop 390
(interactive)
(message "Caught signal %S" last-input-event))
language-change
This kind of event is generated on MS-Windows when the input language has
changed. This typically means that the keyboard keys will send to Emacs
characters from a different language. The generated event has this form:
(language-change frame codepage language-id)
Here frame is the frame which was current when the input language changed;
codepage is the new codepage number; and language-id is the numerical
ID of the new input language. The coding-system (see Section 33.10
[Coding Systems], page 848) that corresponds to codepage is cpcodepage or
windows-codepage. To convert language-id to a string (e.g., to use it for
various language-dependent features, such as set-language-environment),
use the w32-get-locale-info function, like this:
;; Get the abbreviated language name, such as "ENU" for English
(w32-get-locale-info language-id)
;; Get the full English name of the language,
;; such as "English (United States)"
(w32-get-locale-info language-id 4097)
;; Get the full localized name of the language
(w32-get-locale-info language-id t)
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.
While holding the control key down, the user might hold down the second mouse button,
and drag the mouse from one line to the next. That produces two events, as shown here:
(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
(#<window 18 on NEWS> 3510 (0 . 28) -729648))
While holding down the meta and shift keys, the user might press the second mouse
button on the window’s mode line, and then drag the mouse into another window. That
produces a pair of events like these:
(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
(#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)
-453816))
Chapter 21: Command Loop 391
The frame with input focus might not take up the entire screen, and the user might
move the mouse outside the scope of the frame. Inside the track-mouse special form, that
produces an event like this:
(mouse-movement (#<frame *ielm* 0x102849a30> nil (563 . 205) 532301936))
To handle a SIGUSR1 signal, define an interactive function, and bind it to the signal
usr1 event sequence:
(defun usr1-handler ()
(interactive)
(message "Got USR1 signal"))
(global-set-key [signal usr1] 'usr1-handler)
⇒ (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’. Similarly, the modifiers list for an ASCII control
character, such as ‘C-a’, contains control, even though reading such an event via
read-char will return the value 1 with the control modifier bit removed.
⇒ -134217727
(event-convert-list '(control super f1))
⇒ C-s-f1
These functions take a mouse position list as argument, 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.
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.
Chapter 21: Command Loop 397
The argument switch-frame-ok, if non-nil, means that this function should process
a switch-frame event if the user switches frames before typing anything. If the user
switches frames in the middle of a key sequence, or at the start of the sequence but
switch-frame-ok is nil, then the event will be put off until after the current key
sequence.
The argument command-loop, if non-nil, means that this key sequence is being read
by something that will read commands one after another. It should be nil if the
caller will read just one key sequence.
In the following example, Emacs displays the prompt ‘?’ in the echo area, and then
the user types C-x C-f.
(read-key-sequence "?")
⇒ "^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
Section 21.11 [Quitting], page 407.
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.
When reading input results in such a shift-translation, Emacs sets the variable
this-command-keys-shift-translated to a non-nil value. Lisp programs can examine
this variable if they need to modify their behavior when invoked by shift-translated keys.
For example, the function handle-shift-selection examines the value of this variable to
determine how to activate or deactivate the region (see Section 31.7 [The Mark], page 760).
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 trans-
lates 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.
Chapter 21: Command Loop 399
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.
If read-event gets an event that is defined as a help character, then in some cases
read-event processes the event directly without returning. See Section 24.6 [Help
Functions], page 517. Certain other events, called special events, are also processed
directly within read-event (see Section 21.9 [Special Events], page 405).
Here is what happens if you call read-event and then press the right-arrow function
key:
(read-event)
⇒ right
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 terminal-local 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 107), 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.
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 862). Use translation-table-
for-input (see Section 33.9 [Translation of Characters], page 847), if you want to
translate characters after input methods operate.
keyboard-translate from to [Function]
This function modifies keyboard-translate-table to translate character code from
into character code to. It creates the keyboard translate table if necessary.
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.
Chapter 21: Command Loop 403
See Section 22.14 [Translation Keymaps], page 434, 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.8.6
[Event Input Misc], page 404). 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.
If the input method function calls read-event or read-key-sequence, it should bind
input-method-function to nil first, to prevent recursion.
The input method function is not called when reading the second and subsequent
events of a key sequence. Thus, these characters are not subject to input method pro-
cessing. The input method function should test the values of overriding-local-map and
overriding-terminal-local-map; if either of these variables is non-nil, the input method
should put its argument into a list and return that list with no further processing.
In the following example, the user types in the octal number 177 (which is 127 in
decimal).
(read-quoted-char "What character")
⇒ 127
last-input-event [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
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
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)))
while-no-input-ignore-events [Variable]
This variable allow setting which special events while-no-input should ignore. It is
a list of symbols.
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
a numeric argument, they cannot be unread with unread-command-events, they may not
appear in a keyboard macro, and they are not recorded in a keyboard macro while you are
defining one.
Special events do, however, appear in last-input-event immediately after they are
read, and this is the way for the event’s definition to find the actual event.
The events types iconify-frame, make-frame-visible, delete-frame, drag-n-drop,
language-change, and user signals like sigusr1 are normally handled in this way. The
keymap which defines how to handle special events—and which events are special—is in the
variable special-event-map (see Section 22.7 [Active Keymaps], page 422).
See Section 40.5 [Time of Day], page 1086, for functions to get the current time.
21.11 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.
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)
Chapter 21: Command Loop 408
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.
keyboard-quit [Command]
This function signals the quit condition with (signal 'quit nil). This is the same
thing that quitting does. (See signal in Section 11.7.3 [Errors], page 160.)
You can specify a character other than C-g to use for quitting. See the function
set-input-mode in Section 40.13.1 [Input Modes], page 1098.
We illustrate these possibilities by calling the following function with various prefixes:
(defun display-prefix (arg)
"Display the value of the raw prefix arg."
(interactive "P")
(message "%s" arg))
Here are the results of calling display-prefix with various raw prefix arguments:
M-x display-prefix a nil
current-prefix-arg [Variable]
This variable holds the raw prefix argument for the current command. Commands
may examine it directly, but the usual method for accessing it is with (interactive
"P").
prefix-arg [Variable]
The value of this variable is the raw prefix argument for the next editing command.
Commands such as universal-argument that specify prefix arguments for the fol-
lowing command work by setting this variable.
last-prefix-arg [Variable]
The raw prefix argument value used by the previous command.
The following commands exist to set up prefix arguments for the following command.
Do not call them for any other reason.
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 special commands for exiting are always available, but they do nothing when recursive
editing is not in progress.)
All command loops, including recursive ones, set up all-purpose error handlers so that
an error in a command run from the command loop will not exit the loop.
Minibuffer input is a special kind of recursive editing. It has a few special wrinkles, such
as enabling display of the minibuffer and the minibuffer window, but fewer than you might
suppose. Certain keys behave differently in the minibuffer, but that is only because of the
minibuffer’s local map; if you switch windows, you get the usual Emacs commands.
To invoke a recursive editing level, call the function recursive-edit. This function
contains the command loop; it also contains a call to catch with tag exit, which makes it
possible to exit the recursive editing level by throwing to exit (see Section 11.7.1 [Catch
and Throw], page 158). If you throw a value other than t, then recursive-edit returns
normally to the function that called it. The command C-M-c (exit-recursive-edit) does
this. Throwing a t value causes recursive-edit to quit, so that control returns to the
command loop one level up. This is called aborting, and is done by C-] (abort-recursive-
edit).
Most applications should not use recursive editing, except as part of using the minibuffer.
Usually it is more convenient for the user if you change the major mode of the current
buffer temporarily to a special major mode, which should have a command to go back to
the previous mode. (The e command in Rmail uses this technique.) Or, if you wish to give
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 [Command]
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))
Chapter 21: Command Loop 412
⇒ 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.11 [Quitting], page 407.
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.
disabled-command-function [Variable]
The value of this variable should be a function. When the user invokes a disabled
command interactively, this function is called instead of the disabled command. It
can use this-command-keys to determine what the user typed to run the command,
and thus find the command itself.
The value may also be nil. Then all commands work normally, even disabled ones.
By default, the value is a function that asks the user whether to proceed.
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.
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 Terminals], page 685.
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 Terminals], page 685.
kbd-macro-termination-hook [Variable]
This normal hook 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 prema-
turely).
415
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.7.12 [Classifying Events], page 391. In this kind of
binding, binding is a command.
Chapter 22: Keymaps 417
This conversion applies only to characters, not to function keys or other input events;
thus, M-end has nothing to do with ESC end.
Here as an example is the local keymap for Lisp mode, a sparse keymap. It defines
bindings for DEL, C-c C-z, C-M-q, and C-M-x (the actual value also contains a menu binding,
which is omitted here for the sake of brevity).
lisp-mode-map
⇒
(keymap
(3 keymap
;; C-c C-z
(26 . run-lisp))
(27 keymap
;; C-M-x, treated as ESC C-x
(24 . lisp-send-defun))
;; This part is inherited from lisp-mode-shared-map.
keymap
;; DEL
(127 . backward-delete-char-untabify)
(27 keymap
;; C-M-q, treated as ESC C-q
(17 . indent-sexp)))
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
menu or a keyboard menu if it is active for looking up the next input event. Don’t
specify an overall prompt string for the main map of a major or minor mode, because
that would cause the command loop to present a keyboard menu every time.
make-keymap &optional prompt [Function]
This function creates and returns a new full keymap. That keymap contains a char-
table (see Section 6.6 [Char-Tables], page 107) with slots for all characters without
modifiers. The new keymap initially binds all these characters to nil, and does not
bind any other kind of event. The argument prompt specifies a prompt string, as in
make-sparse-keymap.
(make-keymap)
⇒ (keymap #^[nil nil keymap nil nil nil ...])
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. This is almost never needed. If you want a
keymap that’s like another yet with a few changes, you should use map inheritance
rather than copying. I.e., something like:
(let ((map (make-sparse-keymap)))
(set-keymap-parent map <theirmap>)
(define-key map ...)
...)
When performing copy-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))
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.
Sometimes you want to make a keymap that inherits from more than one map. You can
use the function make-composed-keymap for this.
For example, here is how Emacs sets the parent of help-mode-map, such that it inherits
from both button-buffer-map and special-mode-map:
(defvar help-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map
(make-composed-keymap button-buffer-map special-mode-map))
... map) ... )
Chapter 22: Keymaps 421
(key-binding "\C-p6")
⇒ nil
Apart from the above usual keymaps, Emacs provides special ways for programs to make
other keymaps active. Firstly, the variable overriding-local-map specifies a keymap
that replaces the usual active keymaps, except for the global keymap. Secondly, the
terminal-local variable overriding-terminal-local-map specifies a keymap that takes
precedence over all other keymaps (including overriding-local-map); this is normally
used for modal/transient keybindings (the function set-transient-map provides a conve-
nient interface for this). See Section 22.9 [Controlling Active Maps], page 424, for details.
Making keymaps active is not the only way to use them. Keymaps are also used in
other ways, such as for translating events within read-key-sequence. See Section 22.14
[Translation Keymaps], page 434.
See Appendix G [Standard Keymaps], page 1196, for a list of some standard keymaps.
(find-in overriding-local-map)
(or (find-in (get-char-property (point) 'keymap))
(find-in-any emulation-mode-map-alists)
(find-in-any minor-mode-overriding-map-alist)
(find-in-any minor-mode-map-alist)
(if (get-text-property (point) 'local-map)
(find-in (get-char-property (point) 'local-map))
(find-in (current-local-map)))))
(find-in (current-global-map)))
Here, find-in and find-in-any are pseudo functions that search in one keymap and in an
alist of keymaps, respectively. Note that the set-transient-map function works by setting
overriding-terminal-local-map (see Section 22.9 [Controlling Active Maps], page 424).
In the above pseudo-code, if a key sequence starts with a mouse event (see Section 21.7.3
[Mouse Events], page 383), that event’s position is used instead of point, and the event’s
buffer is used instead of the current buffer. In particular, this affects how the keymap and
local-map properties are looked up. If a mouse event occurs on a string embedded with a
display, before-string, or after-string property (see Section 32.19.4 [Special Proper-
ties], page 808), and the string has a non-nil keymap or local-map property, that overrides
the corresponding property in the underlying buffer text (i.e., the property specified by the
underlying text is ignored).
When a key binding is found in one of the active keymaps, and that binding is a com-
mand, the search is over—the command is executed. However, if the binding is a symbol
with a value or a string, Emacs replaces the input key sequences with the variable’s value or
the string, and restarts the search of the active keymaps. See Section 22.10 [Key Lookup],
page 427.
The command which is finally found might also be remapped. See Section 22.13 [Remap-
ping Commands], page 433.
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. The return value is a reference, not
a copy; if you use define-key or other functions on it you will alter global bindings.
(current-global-map)
⇒ (keymap [set-mark-command beginning-of-line ...
delete-backward-char])
Chapter 22: Keymaps 425
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-local-map returns a reference to the local keymap, not a copy of it; if you use
define-key or other functions on it you will alter local bindings.
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)
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 473.
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 473, for more information about
minor modes. See also minor-mode-key-binding (see Section 22.11 [Functions for
Key Lookup], page 428).
Chapter 22: Keymaps 426
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 Terminals], page 685. 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.
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.9 [Special Events], page 405.
emulation-mode-map-alists [Variable]
This variable holds a list of keymap alists to use for emulation 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.
set-transient-map keymap &optional keep-pred on-exit [Function]
This function adds keymap as a transient keymap, which takes precedence over other
keymaps for one (or more) subsequent keys.
Chapter 22: Keymaps 427
Normally, keymap is used just once, to look up the very next key. If the optional
argument keep-pred is t, the map stays active as long as the user types keys defined
in keymap; when the user types a key that is not in keymap, the transient keymap is
deactivated and normal key lookup continues for that key.
The keep-pred argument can also be a function. In that case, the function is called
with no arguments, prior to running each command, while keymap is active; it should
return non-nil if keymap should stay active.
The optional argument on-exit, if non-nil, specifies a function that is called, with no
arguments, after keymap is deactivated.
This function works by adding and removing keymap from the variable
overriding-terminal-local-map, which takes precedence over all other active
keymaps (see Section 22.8 [Searching Keymaps], page 423).
If the string or vector key is not a valid key sequence according to the prefix keys
specified in keymap, it must be too long and have extra events at the end that do not
fit into a single key sequence. Then the value is a number, the number of events at
the front of key that compose a complete key.
If accept-defaults is non-nil, then lookup-key considers default bindings as well as
bindings for the specific events in key. Otherwise, lookup-key reports only bindings
for the specific sequence key, ignoring default bindings except when you explicitly ask
about them. (To do this, supply t as an element of key; see Section 22.3 [Format of
Keymaps], page 416.)
If key contains a meta character (not a function key), that character is implicitly
replaced by a two-character sequence: the value of meta-prefix-char, followed by
the corresponding non-meta character. Thus, the first example below is handled by
conversion into the second example.
(lookup-key (current-global-map) "\M-f")
⇒ forward-word
(lookup-key (current-global-map) "\ef")
⇒ forward-word
Unlike read-key-sequence, this function does not modify the specified events in
ways that discard information (see Section 21.8.1 [Key Sequence Input], page 397).
In particular, it does not convert letters to lower case and it does not change drag
events to clicks.
undefined [Command]
Used in keymaps to undefine keys. It calls ding, but does not cause an error.
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 function (see Section 22.1 [Key Sequences], page 415) is a
convenient way to specify the key sequence.
define-key keymap key binding [Function]
This function sets the binding for key in keymap. (If key is more than one event long,
the change is actually made in another keymap reached from keymap.) The argument
binding can be any Lisp object, but only certain types are meaningful. (For a list of
meaningful types, see Section 22.10 [Key Lookup], page 427.) The value returned by
define-key is binding.
If key is [t], this sets the default binding in keymap. When an event has no binding
of its own, the Emacs command loop uses the keymap’s default binding, if there is
one.
Every prefix of key must be a prefix key (i.e., bound to a keymap) or undefined;
otherwise an error is signaled. If some prefix of key is undefined, then define-key
defines it as a prefix key so that the rest of key can be defined as specified.
If there was previously no binding for key in keymap, the new binding is added at
the beginning of keymap. The order of bindings in a keymap makes no difference
for keyboard input, but it does matter for menu keymaps (see Section 22.17 [Menu
Keymaps], page 439).
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
map
⇒ (keymap (6 . forward-char))
map
⇒ (keymap ; Note foo in ctl-x-map.
(16 keymap [nil ... foo ... backward-kill-sentence])
(24 keymap
(102 . forward-word))
(6 . forward-char))
Note that storing a new binding for C-p C-f actually works by changing an entry in ctl-x-
map, and this has the effect of changing the bindings of both C-p C-f and C-x C-f in the
default global map.
The function substitute-key-definition scans a keymap for keys that have a certain
binding and rebinds them with a different binding. Another feature which is cleaner and
can often produce the same results is to remap one command into another (see Section 22.13
[Remapping Commands], page 433).
input-decode-map [Variable]
This variable holds a keymap that describes the character sequences sent by function
keys on an ordinary character terminal.
The value of input-decode-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 input-decode-map beyond those that
can be deduced from Termcap and Terminfo. See Section 40.1.3 [Terminal-Specific],
page 1076.
local-function-key-map [Variable]
This variable holds a keymap similar to input-decode-map except that it describes
key sequences which should be translated to alternative interpretations that are usu-
ally preferred. It applies after input-decode-map and before key-translation-map.
Entries in local-function-key-map are ignored if they conflict with bindings made
in the minor mode, local, or global keymaps. I.e., the remapping only applies if the
original key sequence would otherwise not have any binding.
Chapter 22: Keymaps 435
key-translation-map [Variable]
This variable is another keymap used just like input-decode-map to translate input
events into other events. It differs from input-decode-map in that it goes to work
after local-function-key-map is finished rather than before; it receives the results
of translation by local-function-key-map.
Just like input-decode-map, but unlike local-function-key-map, this keymap
is applied regardless of whether the input key-sequence has a normal binding.
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 local-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.
or
(global-set-key [?\C-x ?\C-\\] 'next-line)
or
(global-set-key [(control ?x) (control ?\\)] 'next-line)
redefines the first (leftmost) mouse button, entered with the Meta key, to set point where
you click.
Be careful when using non-ASCII text characters in Lisp specifications of keys to bind.
If these are read as multibyte text, as they usually will be in a Lisp file (see Section 16.4
[Loading Non-ASCII], page 268), you must type the keys as multibyte too. For instance, if
you use this:
(global-set-key "ö" 'my-function) ; bind o-umlaut
or
(global-set-key ?ö 'my-function) ; bind o-umlaut
and your language environment is multibyte Latin-1, these commands actually bind the
multibyte character with code 246, not the byte code 246 (M-v) sent by a Latin-1 terminal.
In order to use this binding, you need to teach Emacs how to decode the keyboard by using
an appropriate input method (see Section “Input Methods” in The GNU Emacs Manual).
Chapter 22: Keymaps 437
(accessible-keymaps (current-local-map))
⇒(([] keymap
(27 keymap ; Note this keymap for ESC is repeated below.
(83 . center-paragraph)
(115 . center-line))
(9 . tab-to-tab-stop))
("^[" 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.
If firstonly is non-ascii, then the value is a single vector representing the first key
sequence found, rather than a list of all possible key sequences. If firstonly is t, then
the value is the first key sequence, except that key sequences consisting entirely of
ASCII characters (or meta variants of ASCII characters) are preferred to all other key
sequences and that the return value can never be a menu binding.
If noindirect is non-nil, where-is-internal doesn’t look inside menu-items to find
their commands. This makes it possible to search for a menu-item itself.
The fifth argument, no-remap, determines how this function treats command remap-
pings (see Section 22.13 [Remapping Commands], page 433). There are two cases of
interest:
If a command other-command is remapped to command:
If no-remap is nil, find the bindings for other-command and treat them
as though they are also bindings for command. If no-remap is non-nil,
include the vector [remap other-command] in the list of possible key
sequences, instead of finding those bindings.
If command is remapped to other-command:
If no-remap is nil, return the bindings for other-command rather than
command. If no-remap is non-nil, return the bindings for command,
ignoring the fact that it is remapped.
describe-bindings &optional prefix buffer-or-name [Command]
This function creates a listing of all current key bindings, and displays it in a buffer
named *Help*. The text is grouped by modes—minor modes first, then the major
mode, then global bindings.
If prefix is non-nil, it should be a prefix key; then the listing includes only keys that
start with prefix.
When several characters with consecutive ASCII codes have the same definition, they
are shown together, as ‘firstchar..lastchar’. In this instance, you need to know
the ASCII codes to understand which characters this means. For example, in the
default global map, the characters ‘SPC .. ~’ are described by a single line. SPC is
ASCII 32, ~ is ASCII 126, and the characters between them include all the normal
printing characters, (e.g., letters, digits, punctuation, etc.); all these characters are
bound to self-insert-command.
If buffer-or-name is non-nil, it should be a buffer or a buffer name. Then
describe-bindings lists that buffer’s bindings, instead of the current buffer’s.
should describe the purpose of the menu’s commands. Emacs displays the overall prompt
string as the menu title in some cases, depending on the toolkit (if any) used for displaying
menus.1 Keyboard menus also display the overall prompt string.
The easiest way to construct a keymap with a prompt string is to specify the string
as an argument when you call make-keymap, make-sparse-keymap (see Section 22.4 [Cre-
ating Keymaps], page 418), or define-prefix-command (see [Definition of define-prefix-
command], page 422). 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 450).
The menu bar does not recalculate which items are enabled every time you look at a
menu. This is because the X toolkit requires the whole tree of menus in advance. To force
recalculation of the menu bar, call force-mode-line-update (see Section 23.4 [Mode Line
Format], page 476).
: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.
In the simplest case, separator-type consists of only dashes. That specifies the default
kind of separator. (For compatibility, "" and - also count as separators.)
Certain other values of separator-type specify a different style of separator. Here is a
table of them:
"--no-line"
"--space"
An extra vertical space, with no actual line.
"--single-line"
A single line in the menu’s foreground color.
"--double-line"
A double line in the menu’s foreground color.
"--single-dashed-line"
A single dashed line in the menu’s foreground color.
"--double-dashed-line"
A double dashed line in the menu’s foreground color.
"--shadow-etched-in"
A single line with a 3D sunken appearance. This is the default, used separators
consisting of dashes only.
"--shadow-etched-out"
A single line with a 3D raised appearance.
"--shadow-etched-in-dash"
A single dashed line with a 3D sunken appearance.
"--shadow-etched-out-dash"
A single dashed line with a 3D raised appearance.
"--shadow-double-etched-in"
Two lines with a 3D sunken appearance.
"--shadow-double-etched-out"
Two lines with a 3D raised appearance.
"--shadow-double-etched-in-dash"
Two dashed lines with a 3D sunken appearance.
"--shadow-double-etched-out-dash"
Two dashed lines with a 3D raised appearance.
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".
You can use a longer form to specify keywords such as :enable and :visible for a
menu separator:
(menu-item separator-type nil . item-property-list)
For example:
(menu-item "--" nil :visible (boundp 'foo))
Chapter 22: Keymaps 444
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.
is displayed on a text terminal, menu panes are not used; in that case, a ‘@’ at the beginning
of an item string is omitted when the menu label is displayed, and has no other effect.
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 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 vari-
able 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)
Here, edit is the symbol produced by a fake function key, it is used by the global map for
the ‘Edit’ menu bar item. The main reason to suppress a global menu bar item is to regain
space for mode-specific items.
menu-bar-final-items [Variable]
Normally the menu bar shows global items followed by items defined by the local
maps.
This variable holds a list of fake function keys for items to display at the end of the
menu bar rather than in normal sequence. The default value is (help-menu); thus,
the ‘Help’ menu item normally appears at the end of the menu bar, following local
menu items.
menu-bar-update-hook [Variable]
This normal hook is run by redisplay to update the menu bar contents, before redis-
playing the menu bar. You can use it to update menus whose contents should vary.
Since this hook is run frequently, we advise you to ensure that the functions it calls
do not take much time in the usual case.
Next to every menu bar item, Emacs displays a key binding that runs the same command
(if such a key binding exists). This serves as a convenient hint for users who do not know
the key binding. If a command has multiple bindings, Emacs normally displays the first one
it finds. You can specify one particular key binding by assigning an :advertised-binding
symbol property to the command. See Section 24.3 [Keys in Documentation], page 513.
In addition, you should use the :image property; this is how you specify the image to
display in the tool bar:
:image image
image is either a single image specification (see Section 39.17 [Images],
page 1034) or a vector of four image specifications. If you use a vector of four,
one of them is used, depending on circumstances:
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.
The GTK+ and NS versions of Emacs ignores items 1 to 3, because disabled and/or
deselected images are autocomputed from item 0.
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 :rtl property specifies an alternative image to use for right-to-left languages. Only
the GTK+ version of Emacs supports this at present.
Like the menu bar, the tool bar can display separators (see Section 22.17.1.3 [Menu
Separators], page 442). Tool bar separators are vertical rather than horizontal, though, and
only a single style is supported. They are represented in the tool bar keymap by (menu-item
"--") entries; properties like :visible are not supported for tool bar separators. Separators
are rendered natively in GTK+ and Nextstep tool bars; in the other cases, they are rendered
using an image of a vertical line.
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.1
[Major Mode Conventions], page 456). 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 ,(purecopy "tool bar") ignore
:filter tool-bar-make-keymap))
The function tool-bar-make-keymap, in turn, derives the actual tool bar map dy-
namically from the value of the variable tool-bar-map. Hence, you should normally
adjust the default (global) tool bar by changing that map. Some major modes, such
as Info mode, completely replace the global tool bar by making tool-bar-map buffer-
local and setting it to a different keymap.
There are two convenience functions for defining tool bar items, as follows.
Chapter 22: Keymaps 449
auto-resize-tool-bars [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.
If Emacs is built with GTK+ or Nextstep, the tool bar can only show one line, so this
variable has no effect.
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.
Chapter 22: Keymaps 450
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.
tool-bar-border [Variable]
This variable specifies the height of the border drawn below the tool bar area. An
integer 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.7.2 [Function Keys], page 382, for more information about how to add
modifiers to function keys.
:key-sequence keys
keys is a hint for speeding up Emacs’s first display of the menu. It should
be nil if you know that the menu item has no keyboard equivalent;
otherwise it should be a string or vector specifying a keyboard equivalent
for the menu item.
:active enable
enable is an expression; if it evaluates to nil, the item is make unse-
lectable.. :enable is an alias for :active.
:visible include
include is an expression; if it evaluates to nil, the item is made invisible.
:included is an alias for :visible.
:label form
form is an expression that is evaluated to obtain a value which serves as
the menu item’s label (the default is name).
:suffix form
form is an expression that is dynamically evaluated and whose value is
concatenated with the menu entry’s label.
:style style
style is a symbol describing the type of menu item; it should be toggle
(a checkbox), or radio (a radio button), or anything else (meaning an
ordinary menu item).
:selected selected
selected is an expression; the checkbox or radio button is selected when-
ever the expression’s value is non-nil.
:help help
help is a string describing the menu item.
Alternatively, a menu item can be a string. Then that string appears in the menu
as unselectable text. A string consisting of dashes is displayed as a separator (see
Section 22.17.1.3 [Menu Separators], page 442).
Alternatively, a menu item can be a list with the same format as menu. This is a
submenu.
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 40.1.2 [Init File], page 1075), but Lisp
programs can set them also. See Appendix H [Standard Hooks], page 1199, for a list of
some 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 command is supposed to run a normal hook called the mode hook
as 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 40.2.2 [Suspending Emacs], page 1080).
The recommended way to add a hook function to a hook is by calling add-hook (see
Section 23.1.2 [Setting Hooks], page 454). The hook functions may be any of the valid kinds
of functions that funcall accepts (see Section 13.1 [What Is a Function], page 203). 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’.
If the variable’s name ends in ‘-function’, then its value is just a single function, not a
list of functions. add-hook cannot be used to modify such a single function hook, and you
have to use add-function instead (see Section 13.11 [Advising Functions], page 222).
For a normal hook, hook functions should be designed so that the order in which they
are executed does not matter. Any dependence on the order is asking for trouble.
However, the order is predictable: normally, function goes at the front of the hook
list, so it is executed first (barring another add-hook call). If the optional argument
append is non-nil, the new hook function goes at the end of the hook list and is
executed last.
add-hook can handle the cases where hook is void or its value is a single function; it
sets or changes the value to a list of functions.
If local is non-nil, that says to add function to the buffer-local hook list instead of to
the global hook list. This makes the hook buffer-local and adds t to the 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.
fundamental-mode [Command]
This is the major mode command for Fundamental mode. Unlike other mode com-
mands, it does not run any mode hooks (see Section 23.2.1 [Major Mode Conventions],
page 456), since you are not supposed to customize this mode.
The easiest way to write a major mode is to use the macro define-derived-mode, which
sets up the new mode as a variant of an existing major mode. See Section 23.2.4 [Derived
Modes], page 462. We recommend using define-derived-mode even if the new mode is not
an obvious derivative of another mode, as it automatically enforces many coding conventions
for you. See Section 23.2.5 [Basic Major Modes], page 464, for common modes to derive
from.
The standard GNU Emacs Lisp directory tree contains the code for several major modes,
in files such as text-mode.el, texinfo.el, lisp-mode.el, and rmail.el. You can study
these libraries to see how modes are written.
Chapter 23: Major and Minor Modes 456
• Since all global names are in the same name space, all the global variables, constants,
and functions that are part of the mode should have names that start with the major
mode name (or with an abbreviation of it if the name is long). See Section D.1 [Coding
Conventions], page 1142.
• In a major mode for editing some kind of structured text, such as a programming
language, indentation of text according to structure is probably useful. So the mode
should set indent-line-function to a suitable function, and probably customize other
variables for indentation. See Section 23.7 [Auto-Indentation], page 499.
• 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 422, 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 12.6 [Tips for Defining], page 175, 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. The recommended way of tailoring C-M-a to the needs of a major mode is
to set beginning-of-defun-function (see Section 30.2.6 [List Motion], page 750) to
invoke the function specific to the mode.
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 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 892.
Chapter 23: Major and Minor Modes 458
• If the mode handles a language that has a syntax for comments, it should set the vari-
ables 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.2 [Defining Abbrevs],
page 909.
• 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 487).
• Each face that the mode defines should, if possible, inherit from an existing Emacs
face. See Section 39.12.8 [Basic Faces], page 1010, and Section 23.6.7 [Faces for Font
Lock], page 495.
• 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 485).
• The mode can specify a local value for eldoc-documentation-function to tell ElDoc
mode how to handle this mode.
• The mode can specify how to complete various keywords by adding one or more buffer-
local entries to the special hook completion-at-point-functions. See Section 20.6.8
[Completion in Buffers], page 358.
• 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 12.11 [Buffer-Local Variables], page 185.
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 normal hook change-major-mode-after-body-hook, the mode hook,
the function hack-local-variables (when the buffer is visiting a file), and then
the normal hook after-change-major-mode-hook. See Section 23.2.6 [Mode Hooks],
page 465.
• 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 the
define-derived-mode macro, 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.4 [Derived Modes], page 462, and
Section 23.2.6 [Mode Hooks], page 465.
Chapter 23: Major and Minor Modes 459
• 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 12.11.2 [Creating Buffer-Local], page 186).
• If this mode is appropriate only for specially-prepared text produced by the mode
itself (rather than by the user typing at the keyboard or by an external file), 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 be put in Funny mode, even though the default value of major-mode is nil.
By default, the value of nil for major-mode means to use the current buffer’s major
mode when creating new buffers (see Section 23.2.2 [Auto Major Mode], page 459), but
with such special modes, Fundamental mode is used instead. Modes such as Dired,
Rmail, and Buffer List use this feature.
The function view-buffer does not enable View mode in buffers whose mode-class is
special, because such modes usually provide their own View-like bindings.
The define-derived-mode macro automatically marks the derived mode as special
if the parent mode is special. Special mode is a convenient parent for such modes to
inherit from; See Section 23.2.5 [Basic Major Modes], page 464.
• 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
Section 23.2.2 [Auto Major Mode], page 459). If you define the mode command to
autoload, 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 270). If you do not autoload
the mode command, it is sufficient to add the element in the file that contains the mode
definition.
• 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. For instance, use defvar
or defcustom to set mode-related variables, so that they are not reinitialized if they
already have a value (see Section 12.5 [Defining Variables], page 173).
whether to do so. See Section “Local Variables in Files” in The GNU Emacs Manual,
for the syntax of the local variables section of a file.
If you run normal-mode interactively, the argument find-file is normally nil. In this
case, normal-mode unconditionally processes any file local variables.
The function calls set-auto-mode to choose and set a major mode. If this does not
specify a mode, the buffer stays in the major mode determined by the default value
of major-mode (see below).
normal-mode uses condition-case around the call to the major mode command, so
errors are caught and reported as a ‘File mode specification error’, followed by
the original error message.
interpreter-mode-alist [Variable]
This variable specifies major modes to use for scripts that specify a command in-
terpreter in a ‘#!’ line. Its value is an alist with elements of the form (regexp .
Chapter 23: Major and Minor Modes 461
mode); this says to use mode mode if the file specifies an interpreter which matches
\\`regexp\\'. For example, one of the default elements is ("python[0-9.]*" .
python-mode).
magic-mode-alist [Variable]
This variable’s value is an alist with elements of the form (regexp . function),
where regexp is a regular expression and function is a function or nil. After visiting
a file, set-auto-mode calls function if the text at the beginning of the buffer matches
regexp and function is non-nil; if function is nil, auto-mode-alist gets to decide
the mode.
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.9.4 [File Name Expan-
sion], page 550), with version numbers and backup suffixes removed using file-name-
sans-versions (see Section 25.9.1 [File Name Components], page 546), 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 call-
ing 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 uncompression
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))
Chapter 23: Major and Minor Modes 462
that if parent is a special mode, then variant is also a special mode (see Section 23.2.1
[Major Mode Conventions], page 456).
You can also specify nil for parent. This gives the new mode no parent. Then
define-derived-mode behaves as described above, but, of course, omits all actions
connected with parent.
The argument docstring specifies the documentation string for the new mode.
define-derived-mode adds some general information about the mode’s hook,
followed by the mode’s keymap, at the end of this documentation string. If you omit
docstring, define-derived-mode generates a documentation string.
The keyword-args are pairs of keywords and values. The values, except for
:after-hook’s, are evaluated. The following keywords are currently supported:
:syntax-table
You can use this to explicitly specify a syntax table for the new mode.
If you specify a nil value, the new mode uses the same syntax table as
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.) The command customize-mode
uses this. define-derived-mode does not automatically define the spec-
ified customization group.
:after-hook
This optional keyword specifies a single Lisp form to evaluate as the final
act of the mode function, after the mode hooks have been run. It should
not be quoted. Since the form might be evaluated after the mode function
has terminated, it should not access any element of the mode function’s
local state. An :after-hook form is useful for setting up aspects of the
mode which depend on the user’s settings, which in turn may have been
changed in a mode hook.
Here is a hypothetical example:
(defvar hypertext-mode-map
(let ((map (make-sparse-keymap)))
(define-key map [down-mouse-3] 'do-hyper-link)
map))
(define-derived-mode hypertext-mode
text-mode "Hypertext"
"Major mode for hypertext."
(setq-local case-fold-search nil))
Chapter 23: Major and Minor Modes 464
Tabulated List mode provides facilities for pretty-printing rows and columns, and sorting
the rows according to the values in each column. It is derived from Special mode (see
Section 23.2.5 [Basic Major Modes], page 464).
Tabulated List mode is intended to be used as a parent mode by a more specialized
major mode. Examples include Process Menu mode (see Section 38.6 [Process Information],
page 932) and Package Menu mode (see Section “Package Menu” in The GNU Emacs
Manual).
Such a derived mode should use define-derived-mode in the usual way, specifying
tabulated-list-mode as the second argument (see Section 23.2.4 [Derived Modes],
page 462). The body of the define-derived-mode form should specify the format of the
tabulated data, by assigning values to the variables documented below; optionally, it can
then call the function tabulated-list-init-header, which will populate a header with
the names of the columns.
The derived mode should also define a listing command. This, not the mode command,
is what the user calls (e.g., M-x list-processes). The listing command should create or
switch to a buffer, turn on the derived mode, specify the tabulated data, and finally call
tabulated-list-print to populate the buffer.
tabulated-list-format [Variable]
This buffer-local variable specifies the format of the Tabulated List data. Its value
should be a vector. Each element of the vector represents a data column, and should
be a list (name width sort), where
• name is the column’s name (a string).
• width is the width to reserve for the column (an integer). This is meaningless
for the last column, which runs to the end of each line.
• sort specifies how to sort entries by the column. If nil, the column cannot be
used for sorting. If t, the column is sorted by comparing string values. Otherwise,
this should be a predicate function for sort (see Section 5.6.3 [Rearrangement],
page 80), which accepts two arguments with the same form as the elements of
tabulated-list-entries (see below).
tabulated-list-entries [Variable]
This buffer-local variable specifies the entries displayed in the Tabulated List buffer.
Its value should be either a list, or a function.
If the value is a list, each list element corresponds to one entry, and should have the
form (id contents), where
• id is either nil, or a Lisp object that identifies the entry. If the latter, the cursor
stays on the same entry when re-sorting entries. Comparison is done with equal.
• contents is a vector with the same number of elements as tabulated-list-
format. Each vector element is either a string, which is inserted into the buffer as-
is, or a list (label . properties), which means to insert a text button by calling
insert-text-button with label and properties as arguments (see Section 39.19.3
[Making Buttons], page 1051).
There should be no newlines in any of these strings.
Otherwise, the value should be a function which returns a list of the above form when
called with no arguments.
Chapter 23: Major and Minor Modes 467
tabulated-list-revert-hook [Variable]
This normal hook is run prior to reverting a Tabulated List buffer. A derived mode
can add a function to this hook to recompute tabulated-list-entries.
tabulated-list-printer [Variable]
The value of this variable is the function called to insert an entry at point, including
its terminating newline. The function should accept two arguments, id and contents,
having the same meanings as in tabulated-list-entries. The default value is a
function which inserts an entry in a straightforward way; a mode which uses Tabulated
List mode in a more complex way can specify another function.
tabulated-list-sort-key [Variable]
The value of this variable specifies the current sort key for the Tabulated List buffer. If
it is nil, no sorting is done. Otherwise, it should have the form (name . flip), where
name is a string matching one of the column names in tabulated-list-format, and
flip, if non-nil, means to invert the sort order.
tabulated-list-init-header [Function]
This function computes and sets header-line-format for the Tabulated List buffer
(see Section 23.4.7 [Header Lines], page 484), and assigns a keymap to the header line
to allow sorting entries by clicking on column headers.
Modes derived from Tabulated List mode should call this after setting the above
variables (in particular, only after setting tabulated-list-format).
tabulated-list-delete-entry [Function]
This function deletes the entry at point.
It returns a list (id cols), where id is the ID of the deleted entry and cols is a vector
of its column descriptors. It moves point to the beginning of the current line. It
returns nil if there is no entry at point.
Note that this function only changes the buffer contents; it does not alter
tabulated-list-entries.
Chapter 23: Major and Minor Modes 468
Here is how the Lisp mode syntax and abbrev tables are defined:
;; Create mode-specific table variables.
(define-abbrev-table 'lisp-mode-abbrev-table ()
"Abbrev table for Lisp mode.")
(defvar lisp-mode-syntax-table
(let ((table (make-syntax-table lisp--mode-syntax-table)))
(modify-syntax-entry ?\[ "_ " table)
(modify-syntax-entry ?\] "_ " table)
(modify-syntax-entry ?# "' 14" table)
(modify-syntax-entry ?| "\" 23bn" table)
table)
"Syntax table used in `lisp-mode'.")
The three modes for Lisp share much of their code. For instance, each calls the following
function to set various variables:
(defun lisp-mode-variables (&optional syntax keywords-case-insensitive elisp)
(when syntax
(set-syntax-table lisp-mode-syntax-table))
...
Amongst other things, this function sets up the comment-start variable to handle Lisp
comments:
(setq-local comment-start ";")
...
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 lisp-mode-shared-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map prog-mode-map)
(define-key map "\e\C-q" 'indent-sexp)
(define-key map "\177" 'backward-delete-char-untabify)
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
(let ((map (make-sparse-keymap))
(menu-map (make-sparse-keymap "Lisp")))
(set-keymap-parent map lisp-mode-shared-map)
(define-key map "\e\C-x" 'lisp-eval-defun)
(define-key map "\C-c\C-z" 'run-lisp)
...
map)
"Keymap for ordinary Lisp mode.
All commands in `lisp-mode-shared-map' are inherited by this map.")
Finally, here is the major mode command for Lisp mode:
(define-derived-mode lisp-mode prog-mode "Lisp"
"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."
Chapter 23: Major and Minor Modes 471
(lisp-mode-variables nil t)
(setq-local find-tag-default-function 'lisp-find-tag-default)
(setq-local comment-start-skip
"\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
(setq imenu-case-fold-search t))
In addition, several major mode conventions (see Section 23.2.1 [Major Mode Conven-
tions], page 456) apply to minor modes as well: those regarding the names of global symbols,
the use of a hook at the end of the initialization function, and the use of keymaps and other
tables.
The minor mode should, if possible, support enabling and disabling via Custom (see
Chapter 15 [Customization], page 244). To do this, the mode variable should be defined
with defcustom, usually with :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. Also, mark the definition with an autoload
Chapter 23: Major and Minor Modes 473
cookie (see [autoload cookie], page 270), and specify a :require so that customizing the
variable will load the library that defines 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 string lighter says what to display in the mode line when the mode is enabled; if
it is nil, the mode is not displayed in the mode line.
The optional argument keymap specifies the keymap for the minor mode. If non-nil,
it should be a variable name (whose value is a keymap), a keymap, or an alist of the
form
(key-sequence . definition)
where each key-sequence and definition are arguments suitable for passing to
define-key (see Section 22.12 [Changing Key Bindings], page 430). If keymap is a
keymap or an alist, this also defines the variable mode-map.
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 15.2 [Group Definitions], page 246.
: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 Customize
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.
:variable place
This replaces the default variable mode, used to store the state of the
mode. If you specify this, the mode variable is not defined, and any init-
value argument is unused. place can be a different named variable (which
you must define yourself), or anything that can be used with the setf
function (see Section 12.17 [Generalized Variables], page 200). place can
also be a cons (get . set), where get is an expression that returns the
current state, and set is a function of one argument (a state) that sets it.
Chapter 23: Major and Minor Modes 475
:after-hook after-hook
This defines a single Lisp form which is evaluated after the mode hooks
have run. It should not be quoted.
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 then runs the
mode hook variable mode-hook and finishes by evaluating any form in :after-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.
Interactively with no argument, this command toggles the mode.
A positive prefix argument enables the mode, any other prefix
argument disables it. From Lisp, argument omitted or nil enables
the mode, `toggle' toggles the state.
. (lambda ()
(interactive)
(hungry-electric-delete t))))
:group 'hunger)
the window configuration, switch buffers, narrow or widen the buffer, scroll, or modify the
buffer. If you alter any of the variables referenced by mode-line-format or header-line-
format (see Section 23.4.4 [Mode Line Variables], page 479), or any other data structures
that affect how text is displayed (see Chapter 39 [Display], page 967), you should use the
function force-mode-line-update to update the display.
force-mode-line-update &optional all [Function]
This function forces Emacs to update the current buffer’s mode line and header line,
based on the latest values of all relevant variables, during its next redisplay cycle.
If the optional argument all is non-nil, it forces an update for all mode lines and
header lines.
This function also forces an update of the menu bar and frame title.
The selected window’s mode line is usually displayed in a different color using the face
mode-line. Other windows’ mode lines appear in the face mode-line-inactive instead.
See Section 39.12 [Faces], page 997.
(string rest...)
(list rest...)
A list whose first element is a string or list means to process all the elements
recursively and concatenate the results. This is the most common form of mode
line construct.
(:eval form)
A list whose first element is the symbol :eval says to evaluate form, and use
the result as a string to display. Make sure this evaluation cannot load any
files, as doing so could cause infinite recursion.
(:propertize elt props...)
A list whose first element is the symbol :propertize says to process the mode
line construct elt recursively, then add the text properties specified by props
to the result. The argument props should consist of zero or more pairs text-
property value. If elt is or produces a string with text properties, all the
characters of that string should have the same properties, or else some of them
might be removed by :propertize.
(symbol then else)
A list whose first element is a symbol that is not a keyword specifies a condi-
tional. Its meaning depends on the value of symbol. If symbol has a non-nil
value, the second element, then, is processed recursively as a mode line con-
struct. Otherwise, the third element, else, is processed recursively. You may
omit else; then the mode line construct displays nothing if the value of symbol
is nil or void.
(width rest...)
A list whose first element is an integer specifies truncation or padding of the
results of rest. The remaining elements rest are processed recursively as mode
line constructs and concatenated together. When width is positive, the result is
space filled on the right if its width is less than width. When width is negative,
the result is truncated on the right to −width columns if its width exceeds
−width.
For example, the usual way to show what percentage of a buffer is above the
top of the window is to use a list like this: (-3 "%p").
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 val-
ues of the variables mode-name and minor-mode-alist). Very few modes need to alter
Chapter 23: Major and Minor Modes 479
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 479), 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 a hypothetical example of a mode-line-format that might be useful for Shell
mode (in reality, Shell mode does not set mode-line-format):
(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))
'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 835.
mode-line-modified [Variable]
This variable holds the value of the mode line construct that displays whether the
current buffer is modified. Its default value 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. Its default value displays " " 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
displays the buffer name, padded with spaces to at least 12 columns.
mode-line-position [Variable]
This variable indicates the position in the buffer. Its default value displays the buffer
percentage and, optionally, 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. Its default value also
displays the recursive editing level, information on the process status, and whether
narrowing is in effect.
mode-line-remote [Variable]
This variable is used to show whether default-directory for the current buffer is
remote.
mode-line-client [Variable]
This variable is used to identify emacsclient frames.
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. The value does not have to be a string, but can use any of the
data types valid in a mode-line construct (see Section 23.4.2 [Mode Line Data],
page 477). To compute the string that will identify the mode name in the mode
line, use format-mode-line (see Section 23.4.8 [Emulating Mode Line], page 484).
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.
mode-line-front-space [Variable]
This variable is displayed at the front of the mode line. By default, this construct is
displayed right at the beginning of the mode line, except that if there is a memory-full
message, it is displayed first.
mode-line-end-spaces [Variable]
This variable is displayed at the end of the mode line.
mode-line-misc-info [Variable]
Mode line construct for miscellaneous information. By default, this shows the infor-
mation specified by global-mode-string.
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 construct. 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. Convention-
ally, the 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 construct 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.
Chapter 23: Major and Minor Modes 482
Here is a simplified version of the default value of 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))
"-%-")
%o The degree of travel of the window through (the visible portion of) the buffer,
i.e. the size of the text above the top of the window expressed as a percentage
of all the text outside the window, or ‘Top’, ‘Bottom’ or ‘All’.
%p The percentage of the buffer text above the top of window, or ‘Top’, ‘Bottom’
or ‘All’. Note that the default mode line construct 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’.
%q The percentages of text above both the top and the bottom of the window,
separated by ‘-’, or ‘All’.
%s The status of the subprocess belonging to the current buffer, obtained with
process-status. See Section 38.6 [Process Information], page 932.
%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 587.
%+ ‘*’ 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 587.
%& ‘*’ 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.13 [Recursive Editing],
page 410.
%] 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.
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.
2. Put a text property on a mode line %-construct such as ‘%12b’; then the expansion of
the %-construct will have that same text property.
3. Use a (:propertize elt props...) construct to give elt a text property specified by
props.
4. Use a list containing :eval form in the mode line data structure, and make form
evaluate to a string that has a text property.
You can use the keymap property to specify a keymap. This keymap only takes real
effect for mouse clicks; binding character keys and function keys to it has no effect, since it
is impossible to move point into the mode line.
When the mode line refers to a variable which does not have a non-nil risky-local-
variable property, any text properties given or specified within that variable’s values are
ignored. This is because such properties could otherwise specify functions to be called, and
those functions could come from file local variables.
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 477). 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.
is nil or omitted, that stands for the default face. If face is an integer, the value
returned by this function will have no text properties.
You can also specify other valid faces as the value of face. If specified, that face
provides the face property for characters whose face is not specified by format.
Note that using mode-line, mode-line-inactive, or header-line as face will actu-
ally redisplay the mode line or the header line, respectively, using the current defini-
tions of the corresponding face, in addition to returning the formatted string. (Other
faces do not cause redisplay.)
For example, (format-mode-line header-line-format) returns the text that
would appear in the selected window’s header line ("" if it has no header line).
(format-mode-line header-line-format 'header-line) returns the same text,
with each character carrying the face that it will have in the header line itself, and
also redraws the header line.
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.
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 868); anything in the buffer that it matches is considered a
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...)
Chapter 23: Major and Minor Modes 486
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 897).
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:
imenu-prev-index-position-function [Variable]
If this variable is non-nil, its value should be a function that finds the next definition
to put in the buffer index, scanning backward in the buffer from point. It should
Chapter 23: Major and Minor Modes 487
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.
[syntax-alist other-vars...]]])
The first element, keywords, indirectly specifies the value of font-lock-keywords
which directs search-based fontification. It can be a symbol, a variable or a function
whose value is the list to use for font-lock-keywords. It can also be a list of several
such symbols, one for each possible level of fontification. The first symbol specifies
the ‘mode default’ level of fontification, the next symbol level 1 fontification, the
next level 2, and so on. The ‘mode default’ level is normally the same as level 1. It
is used when font-lock-maximum-decoration has a nil value. See Section 23.6.5
[Levels of Font Lock], page 495.
The second element, keywords-only, specifies the value of the variable font-lock-
keywords-only. If this is omitted or nil, syntactic fontification (of strings and com-
ments) is also performed. If this is non-nil, syntactic fontification is not performed.
See Section 23.6.8 [Syntactic Font Lock], page 496.
The third element, case-fold, specifies the value of font-lock-keywords-case-fold-
search. If it is non-nil, Font Lock mode ignores case during search-based fontifica-
tion.
If the fourth element, syntax-alist, is non-nil, it should be a list of cons cells of
the form (char-or-string . string). These are used to set up a syntax table for
syntactic fontification; the resulting syntax table is stored in font-lock-syntax-
table. If syntax-alist is omitted or nil, syntactic fontification uses the syntax table
returned by the syntax-table function. See Section 35.3 [Syntax Table Functions],
page 897.
All the remaining elements (if any) are collectively called other-vars. Each of these
elements should have the form (variable . value)—which means, make variable
buffer-local and then set it to value. You can use these other-vars to set other variables
that affect fontification, aside from those you can control with the first five elements.
See Section 23.6.4 [Other Font Lock Variables], page 493.
If your mode fontifies text explicitly by adding font-lock-face properties, it can specify
(nil t) for font-lock-defaults to turn off all automatic fontification. However, this is
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.
of the text has been fontified already, this cannot be overridden by a subsequent match
in the same text; but you can specify different behavior using the override element of a
subexp-highlighter.
Each element of font-lock-keywords should have one of these forms:
regexp Highlight all matches for regexp using font-lock-keyword-face. For example,
;; Highlight occurrences of the word ‘foo’
;; using font-lock-keyword-face.
"\\<foo\\>"
Be careful when composing these regular expressions; a poorly written
pattern can dramatically slow things down! The function regexp-opt (see
Section 34.3.3 [Regexp Functions], page 877) is useful for calculating optimal
regular expressions to match several keywords.
function Find text by calling function, and highlight the matches it finds using
font-lock-keyword-face.
When function is called, it receives one argument, the limit of the search; it
should begin searching at point, and not search beyond the limit. It should
return non-nil if it succeeds, and set the match data to describe the match
that was found. Returning nil indicates failure of the search.
Fontification will call function repeatedly with the same limit, and with point
where the previous invocation left it, until function fails. On failure, function
need not reset point in any particular way.
(matcher . subexp)
In this kind of element, matcher is either a regular expression or a function, as
described above. The cdr, subexp, specifies which subexpression of matcher
should be highlighted (instead of the entire text that matcher matched).
;; Highlight the ‘bar’ in each occurrence of ‘fubar’,
;; using font-lock-keyword-face.
("fu\\(bar\\)" . 1)
If you use regexp-opt to produce the regular expression matcher, you can
use regexp-opt-depth (see Section 34.3.3 [Regexp Functions], page 877) to
calculate the value for subexp.
(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
Chapter 23: Major and Minor Modes 491
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.
(matcher highlighters...)
This sort of element specifies several highlighter lists for a single matcher. A
highlighter list can be of the type subexp-highlighter or anchored-highlighter
as described above.
For example,
;; Highlight occurrences of the word ‘anchor’ in the value
;; of anchor-face, and subsequent occurrences of the word
;; ‘item’ (on the same line) in the value of item-face.
("\\<anchor\\>" (0 anchor-face)
("\\<item\\>" nil nil (0 item-face)))
(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.
Warning: Do not design an element of font-lock-keywords to match text which spans
lines; this does not work reliably. For details, see Section 23.6.9 [Multiline Font Lock],
page 497.
You can use case-fold in font-lock-defaults to specify the value of font-lock-
keywords-case-fold-search which says whether search-based fontification should be case-
insensitive.
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.
For example, the following code adds two fontification patterns for C mode: one to
fontify the word ‘FIXME’, even in comments, and another to fontify the words ‘and’, ‘or’
and ‘not’ as keywords.
(font-lock-add-keywords 'c-mode
'(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))
This 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 489.
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.
font-lock-flush-function [Variable]
Function to use for declaring that a region’s fontification is out of date. It takes two
arguments, the beginning and end of the region. The default value of this variable is
font-lock-after-change-function.
font-lock-ensure-function [Variable]
Function to use for making sure a region of the current buffer has been fontified. It
is called with two arguments, the beginning and end of the region. The default value
of this variable is a function that calls font-lock-default-fontify-buffer if the
buffer is not fontified; the effect is to make sure the entire accessible portion of the
buffer is fontified.
jit-lock-register function &optional contextual [Function]
This function tells Font Lock mode to run the Lisp function function any time it
has to fontify or refontify part of the current buffer. It calls function before calling
Chapter 23: Major and Minor Modes 495
the default fontification functions, and gives it two arguments, start and end, which
specify the region to be fontified or refontified.
The optional argument contextual, if non-nil, forces Font Lock mode to always re-
fontify a syntactically relevant part of the buffer, and not just the modified lines. This
argument can usually be omitted.
jit-lock-unregister function [Function]
If function was previously registered as a fontification function using jit-lock-
register, this function unregisters it.
Each of these symbols is both a face name, and a variable whose default value is the
symbol itself. Thus, the default value of font-lock-comment-face is font-lock-comment-
face.
The faces are listed with descriptions of their typical usage, and in order of greater to
lesser prominence. If a mode’s syntactic categories do not fit well with the usage descrip-
tions, the faces can be assigned using the ordering as a guide.
font-lock-warning-face
for a construct that is peculiar, or that greatly changes the meaning of other
text, like ‘;;;###autoload’ in Emacs Lisp and ‘#error’ in C.
font-lock-function-name-face
for the name of a function being defined or declared.
font-lock-variable-name-face
for the name of a variable being defined or declared.
font-lock-keyword-face
for a keyword with special syntactic significance, like ‘for’ and ‘if’ in C.
font-lock-comment-face
for comments.
font-lock-comment-delimiter-face
for comments delimiters, like ‘/*’ and ‘*/’ in C. On most terminals, this inherits
from font-lock-comment-face.
font-lock-type-face
for the names of user-defined data types.
font-lock-constant-face
for the names of constants, like ‘NULL’ in C.
font-lock-builtin-face
for the names of built-in functions.
font-lock-preprocessor-face
for preprocessor commands. This inherits, by default, from font-lock-
builtin-face.
font-lock-string-face
for string constants.
font-lock-doc-face
for documentation strings in the code. This inherits, by default, from
font-lock-string-face.
font-lock-negation-char-face
for easily-overlooked negation characters.
which syntactic constructs to highlight. There are several variables that affect syntactic
fontification; you should set them by means of font-lock-defaults (see Section 23.6.1
[Font Lock Basics], page 488).
Whenever Font Lock mode performs syntactic fontification on a stretch of text, it first
calls the function specified by syntax-propertize-function. Major modes can use this to
apply syntax-table text properties to override the buffer’s syntax table in special cases.
See Section 35.4 [Syntax Properties], page 899.
font-lock-keywords-only [Variable]
If the value of this variable is non-nil, Font Lock does not do syntactic fontification,
only search-based fontification based on font-lock-keywords. It is normally set by
Font Lock mode based on the keywords-only element in font-lock-defaults.
font-lock-syntax-table [Variable]
This variable holds the syntax table to use for fontification of comments and strings.
It is normally set by Font Lock mode based on the syntax-alist element in font-lock-
defaults. If this value is nil, syntactic fontification uses the buffer’s syntax table
(the value returned by the function syntax-table; see Section 35.3 [Syntax Table
Functions], page 897).
font-lock-syntactic-face-function [Variable]
If this variable is non-nil, it should be a function to determine which face to use for
a given syntactic element (a string or a comment). The value is normally set through
an other-vars element in font-lock-defaults.
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
(see Section 23.6.7 [Faces for Font Lock], page 495).
• Somehow identify the multiline construct right when it gets inserted into the buffer (or
at any point after that but before font-lock tries to highlight it), and mark it with a
font-lock-multiline which will instruct font-lock not to start or end the scan in the
middle of the construct.
There are three ways to do rehighlighting of multiline constructs:
• Place a font-lock-multiline property on the construct. This will rehighlight the
whole construct if any part of it is changed. In some cases you can do this automatically
by setting the font-lock-multiline variable, which see.
• Make sure jit-lock-contextually is set and rely on it doing its job. This will only
rehighlight the part of the construct that follows the actual change, and will do it after
a short delay. This only works if the highlighting of the various parts of your multiline
construct never depends on text in subsequent lines. Since jit-lock-contextually
is activated by default, this can be an attractive solution.
• Place a jit-lock-defer-multiline property on the construct. This works only if
jit-lock-contextually is used, and with the same delay before rehighlighting, but
like font-lock-multiline, it also handles the case where highlighting depends on
subsequent lines.
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 universal 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.
since the highlighting of those constructs which are found will be properly updated from
then on. But that does not work reliably.
To find multiline constructs reliably, you must either manually place the font-lock-
multiline property on the text before Font Lock mode looks at it, or use font-lock-
fontify-region-function.
font-lock-extend-after-change-region-function [Variable]
This buffer-local variable is either nil or a function for Font Lock mode 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.30 [Change Hooks], page 832). It should
return either 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.
A good indentation function will usually need to actually parse the text, according to
the syntax of the language. Luckily, it is not necessary to parse the text in as much detail
as would be needed for a compiler, but on the other hand, the parser embedded in the
indentation code will want to be somewhat friendly to syntactically incorrect code.
Good maintainable indentation functions usually fall into two categories: either parsing
forward from some safe starting point until the position of interest, or parsing backward from
the position of interest. Neither of the two is a clearly better choice than the other: parsing
backward is often more difficult than parsing forward because programming languages are
designed to be parsed forward, but for the purpose of indentation it has the advantage of
not needing to guess a safe starting point, and it generally enjoys the property that only
a minimum of text will be analyzed to decide the indentation of a line, so indentation will
tend to be less affected by syntax errors in some earlier unrelated piece of code. Parsing
forward on the other hand is usually easier and has the advantage of making it possible to
reindent efficiently a whole region at a time, with a single parse.
Rather than write your own indentation function from scratch, it is often preferable to
try and reuse some existing ones or to rely on a generic indentation engine. There are sadly
few such engines. The CC-mode indentation code (used with C, C++, Java, Awk and a few
other such modes) has been made more generic over the years, so if your language seems
somewhat similar to one of those languages, you might try to use that engine. Another
one is SMIE which takes an approach in the spirit of Lisp sexps and adapts it to non-Lisp
languages.
bnf is a list of nonterminal definitions of the form (nonterm rhs1 rhs2 ...) where
each rhs is a (non-empty) list of terminals (aka tokens) or non-terminals.
Not all grammars are accepted:
• An rhs cannot be an empty list (an empty list is never needed, since SMIE allows
all non-terminals to match the empty string anyway).
• An rhs cannot have 2 consecutive non-terminals: each pair of non-terminals needs
to be separated by a terminal (aka token). This is a fundamental limitation of
operator precedence grammars.
Additionally, conflicts can occur:
• The returned prec2 table holds constraints between pairs of tokens, and for any
given pair only one constraint can be present: T1 < T2, T1 = T2, or T1 > T2.
• A token can be an opener (something similar to an open-paren), a closer (like
a close-paren), or neither of the two (e.g., an infix operator, or an inner token
like "else").
Precedence conflicts can be resolved via resolvers, which is a list of precs tables (see
smie-precs->prec2): for each precedence conflict, if those precs tables specify a
particular constraint, then the conflict is resolved by using this constraint instead,
else a conflict is reported and one of the conflicting constraints is picked arbitrarily
and the others are simply ignored.
• The grammar category id has no right hand side: this does not mean that it can match
only the empty string, since as mentioned any sequence of sexps can appear anywhere
anyway.
• Because non terminals cannot appear consecutively in the BNF grammar, it is difficult
to correctly handle tokens that act as terminators, so the above grammar treats ";"
as a statement separator instead, which SMIE can handle very well.
• Separators used in sequences (such as "," and ";" above) are best defined with BNF
rules such as (foo (foo "separator" foo) ...) which generate precedence conflicts
which are then resolved by giving them an explicit (assoc "separator").
• The ("(" exps ")") rule was not needed to pair up parens, since SMIE will pair up
any characters that are marked as having paren syntax in the syntax table. What this
rule does instead (together with the definition of exps) is to make it clear that ","
should not appear outside of parentheses.
• Rather than have a single precs table to resolve conflicts, it is preferable to have several
tables, so as to let the BNF part of the grammar specify relative precedences where
possible.
• Unless there is a very good reason to prefer left or right, it is usually preferable to
mark operators as associative, using assoc. For that reason "+" and "*" are defined
above as assoc, although the language defines them formally as left associative.
(defun sample-smie-backward-token ()
(forward-comment (- (point)))
(cond
((looking-back sample-keywords-regexp (- (point) 2) t)
(goto-char (match-beginning 0))
(match-string-no-properties 0))
(t (buffer-substring-no-properties
(point)
(progn (skip-syntax-backward "w_")
(point))))))
Notice how those lexers return the empty string when in front of parentheses. This
is because SMIE automatically takes care of the parentheses defined in the syntax table.
More specifically if the lexer returns nil or an empty string, SMIE tries to handle the
corresponding text as a sexp according to syntax tables.
...)
(else (insts "ELSE" insts))
(cases (cases "|" cases) (caselabel ":" insts) (else))
...
Reworking the grammar to try and solve conflicts has its downsides, tho, because SMIE
assumes that the grammar reflects the logical structure of the code, so it is preferable to
keep the BNF closer to the intended abstract syntax tree.
Other times, after careful consideration you may conclude that those conflicts are not
serious and simply resolve them via the resolvers argument of smie-bnf->prec2. Usually
this is because the grammar is simply ambiguous: the conflict does not affect the set of
programs described by the grammar, but only the way those programs are parsed. This is
typically the case for separators and associative infix operators, where you want to add a
resolver like '((assoc "|")). Another case where this can happen is for the classic dangling
else problem, where you will use '((assoc "else" "then")). It can also happen for cases
where the conflict is real and cannot really be resolved, but it is unlikely to pose a problem
in practice.
Finally, in many cases some conflicts will remain despite all efforts to restructure the
grammar. Do not despair: while the parser cannot be made more clever, you can make
the lexer as smart as you want. So, the solution is then to look at the tokens involved
in the conflict and to split one of those tokens into 2 (or more) different tokens. E.g., if
the grammar needs to distinguish between two incompatible uses of the token "begin",
make the lexer return different tokens (say "begin-fun" and "begin-plain") depending
on which kind of "begin" it finds. This pushes the work of distinguishing the different cases
to the lexer, which will thus have to look at the surrounding text to find ad-hoc clues.
token. backward-sexp stops with point before the parent token if that is the opener of the
token of interest, and otherwise it stops with point after the parent token.
SMIE indentation rules are specified using a function that takes two arguments method
and arg where the meaning of arg and the expected return value depend on method.
method can be:
• :after, in which case arg is a token and the function should return the offset to use
for indentation after arg.
• :before, in which case arg is a token and the function should return the offset to use
to indent arg itself.
• :elem, in which case the function should return either the offset to use to indent
function arguments (if arg is the symbol arg) or the basic indentation step (if arg is
the symbol basic).
• :list-intro, in which case arg is a token and the function should return non-nil if
the token is followed by a list of expressions (not separated by any token) rather than
an expression.
When arg is a token, the function is called with point just before that token. A return
value of nil always means to fallback on the default behavior, so the function should return
nil for arguments it does not expect.
offset can be:
• nil: use the default indentation rule.
• (column . column): indent to column column.
• number: offset by number, relative to a base token which is the current token for
:after and its parent for :before.
smie-rule-bolp [Function]
Return non-nil if the current token is the first on the line.
smie-rule-hanging-p [Function]
Return non-nil if the current token is hanging. A token is hanging if it is the last
token on the line and if it is preceded by other tokens: a lone token on a line is not
hanging.
smie-rule-sibling-p [Function]
Return non-nil if the current token’s parent is actually a sibling. This is the case for
example when the parent of a "," is just the previous ",".
• The rule for indentation before "begin" is an example of the use of virtual indentation:
This rule is used only when "begin" is hanging, which can happen only when "begin"
is not at the beginning of a line. So this is not used when indenting "begin" itself but
only when indenting something relative to this "begin". Concretely, this rule changes
the indentation from:
if x > 0 then begin
dosomething(x);
end
to
if x > 0 then begin
dosomething(x);
end
• The rule for indentation before "if" is similar to the one for "begin", but where the
purpose is to treat "else if" as a single unit, so as to align a sequence of tests rather
than indent each test further to the right. This function does this only in the case
where the "if" is not placed on a separate line, hence the smie-rule-bolp test.
If we know that the "else" is always aligned with its "if" and is always at the
beginning of a line, we can use a more efficient rule:
((equal token "if")
(and (not (smie-rule-bolp))
(smie-rule-prev-p "else")
(save-excursion
(sample-smie-backward-token)
(cons 'column (current-column)))))
The advantage of this formulation is that it reuses the indentation of the previous
"else", rather than going all the way back to the first "if" of the sequence.
smie-config-guess [Command]
This command tries to work out appropriate settings to produce your preferred style
of indentation. Simply call the command while visiting a file that is indented with
your style.
smie-config-save [Command]
Call this command after using smie-config-guess, to save your settings for future
sessions.
Chapter 23: Major and Minor Modes 509
smie-config-set-indent [Command]
This command adds a local rule to adjust the indentation of the current line.
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.
510
24 Documentation
GNU Emacs has convenient built-in help facilities, most of which derive their information
from documentation strings associated with functions and variables. This chapter describes
how to access documentation strings in Lisp programs.
The contents of a documentation string should follow certain conventions. In particular,
its first line should be a complete sentence (or two complete sentences) that briefly describes
what the function or variable does. See Section D.6 [Documentation Tips], page 1148, for
how to write good documentation strings.
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.
C-h f on the command to trigger autoloading. (This is needed for correctly setting up the
hyperlinks in the *Help* buffer.)
The describe-symbols function works like apropos, but provides more information.
(describe-symbols "goal")
minibuffer-temporary-goal-position Variable
not documented
(fn ARG)
temporary-goal-column Variable
Current goal column for vertical motion.
It is the column where point was at the start of the current run
of vertical motion commands.
doc-directory [Variable]
This variable holds the name of the directory which should contain the file "DOC" 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 519.
\[command]
stands for a key sequence that will invoke command, or ‘M-x command’ if com-
mand has no key bindings.
Chapter 24: Documentation 514
\{mapvar}
stands for a summary of the keymap which is the value of the variable mapvar.
The summary is made using describe-bindings.
\<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.
` (grave accent) stands for a left quote. This generates a left single
quotation mark, an apostrophe, or a grave accent depending on the value of
text-quoting-style. See Section 24.4 [Text Quoting Style], page 515.
' (apostrophe) stands for a right quote. This generates a right single quotation
mark or an apostrophe depending on the value of text-quoting-style.
\= quotes the following character and is discarded; thus, ‘\=`’ puts ‘`’ into the
output, ‘\=\[’ 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
"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 1148, for details.
This option is useful on platforms that have problems with curved quotes. You can
customize it freely according to your personal preference.
characters in buffers). Characters with modifier bits will cause this function to sig-
nal an error (ASCII characters with the Control modifier are an exception, they are
represented as control characters).
(text-char-description ?\C-c)
⇒ "^C"
(text-char-description ?\M-m)
error Wrong type argument: characterp, 134217837
help-map [Variable]
The value of this variable is a local keymap for characters following the Help key, C-h.
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, read-char-choice, 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 366).
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 [Command]
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.
Chapter 24: Documentation 519
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.
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.
help-buffer [Function]
This function returns the name of the help buffer, which is normally *Help*; if such
a buffer does not exist, it is first created.
25 Files
This chapter describes the Emacs Lisp functions and variables to find, create, view, save, and
otherwise work with files and directories. A few other file-related functions are described in
Chapter 27 [Buffers], page 581, and those related to backups and auto-saving are described
in Chapter 26 [Backups and Auto-Saving], page 569.
Many of the file functions take one or more arguments that are file names. A file
name is a string. Most of these functions expand file name arguments using the function
expand-file-name, so that ~ is handled correctly, as are relative file names (including ../
and the empty string). See Section 25.9.4 [File Name Expansion], page 550.
In addition, certain magic file names are handled specially. For example, when a remote
file name is specified, Emacs accesses the file over the network via an appropriate protocol.
See Section “Remote Files” in The GNU Emacs Manual. This handling is done at a very low
level, so you may assume that all the functions described in this chapter accept magic file
names as file name arguments, except where noted. See Section 25.12 [Magic File Names],
page 559, for details.
When file I/O functions signal Lisp errors, they usually use the condition file-error
(see Section 11.7.3.3 [Handling Errors], page 163). The error message is in most cases ob-
tained from the operating system, according to locale system-messages-locale, and de-
coded using coding system locale-coding-system (see Section 33.12 [Locales], page 863).
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.
Chapter 25: Files 524
find-file-literally [Variable]
This buffer-local variable, if set to a non-nil value, makes save-buffer behave as
if the buffer were visiting its file literally, i.e., without conversions of any kind. The
command find-file-literally sets this variable’s local value, but other equivalent
functions and commands can do that as well, e.g., to avoid automatic addition of a
newline at the end of the file. This variable is permanent local, so it is unaffected by
changes of major modes.
If nomodes is non-nil, that means don’t alter the buffer’s major mode, don’t process
local variables specifications in the file, and don’t run find-file-hook. This feature
is used by revert-buffer in some cases.
The last thing after-find-file does is call all the functions in the list find-file-
hook.
of this work by calling set-visited-file-name (see Section 27.4 [Buffer File Name],
page 585) and save-buffer.
If confirm is non-nil, that means to ask for confirmation before overwriting an existing
file. Interactively, confirmation is required, unless the user supplies a prefix argument.
If filename is a directory name (see Section 25.9.3 [Directory Names], page 549),
write-file uses the name of the visited file, in directory filename. If the buffer is
not visiting a file, it uses the buffer name instead.
Saving a buffer runs several hooks. It also performs format conversion (see Section 25.13
[Format Conversion], page 563). Note that these hooks, described below, are only run by
save-buffer, they are not run by other primitives and functions that write buffer text to
files, and in particular auto-saving (see Section 26.2 [Auto-Saving], page 574) doesn’t run
these hooks.
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))
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 569.
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 851), perform the encoding (see
Section 33.10.7 [Explicit Encoding], page 859), and set last-coding-system-used to
the coding system that was used (see Section 33.10.2 [Encoding and I/O], page 850).
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 453.
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, and can be
used to create arbitrary save processes for buffers that aren’t visiting files at all. 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.
Chapter 25: Files 527
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.
When using this hook to save buffers that are not visiting files (for instance, special-
mode buffers), keep in mind that, if the function fails to save correctly and returns a
nil value, save-buffer will go on to prompt the user for a file to save the buffer in.
If this is undesirable, consider having the function fail by raising an error.
See also the function set-visited-file-name (see Section 27.4 [Buffer File Name],
page 585).
If you want to pass a file name to another process so that another program can read the
file, use the function file-local-copy; see Section 25.12 [Magic File Names], page 559.
write-region-inhibit-fsync [Variable]
If this variable’s value is nil, write-region uses the fsync system call after writing
a file. Although this slows Emacs down, it lessens the risk of data loss after power
failure. If the value is t, Emacs does not use fsync. The default value is nil when
Emacs is interactive, and t when Emacs runs in batch mode. See Section 25.8 [Files
and Storage], page 545.
with-temp-file file body. . . [Macro]
The with-temp-file macro evaluates the body forms with a temporary buffer as
the current buffer; then, at the end, it writes the buffer contents into file file. It kills
the temporary buffer when finished, restoring the buffer that was current before the
with-temp-file form. Then it returns the value of the last form in body.
The current buffer is restored even in case of an abnormal exit via throw or error (see
Section 11.7 [Nonlocal Exits], page 158).
See also with-temp-buffer in [The Current Buffer], page 583.
unlock-buffer [Function]
This function unlocks the file being visited in the current buffer, if the buffer is
modified. If the buffer is not modified, then the file should not be locked, so this
function does nothing. It also does nothing if the current buffer is not visiting a file,
or is not locked.
(On GNU and other POSIX-like systems, this is true if the file exists and you have
execute permission on the containing directories, regardless of the permissions of the
file itself.)
If the file does not exist, or if access control policies prevent you from finding its
attributes, this function returns nil.
Directories are files, so file-exists-p can return t when given a directory. However,
because file-exists-p follows symbolic links, it 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-executable-p filename [Function]
This function returns t if a file named filename exists and you can execute it. It re-
turns nil otherwise. On GNU and other POSIX-like systems, if the file is a directory,
execute permission means you can check the existence and attributes of files inside
the directory, 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 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 "~/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).
For example, from the following we deduce that any attempt to read a file in /foo/
will give an error:
(file-accessible-directory-p "/foo")
⇒ nil
access-file filename string [Function]
This function opens file filename for reading, then closes it and returns nil. However,
if the open fails, it signals an error using string as the error message text.
file-ownership-preserved-p filename &optional group [Function]
This function returns t if deleting the file filename and then creating it anew would
keep the file’s owner unchanged. It also returns t for nonexistent files.
If the optional argument group is non-nil, this function also checks that the file’s
group would be unchanged.
This function does not follow symbolic links.
Chapter 25: Files 533
$ ls -l diffs
-rw-rw-rw- 1 lewis lewis 3063 Oct 30 16:00 diffs
MS-DOS note: On MS-DOS, there is no such thing as an executable file mode bit.
So file-modes 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 POSIX-standard ‘#!’ signature, such as shell and Perl scripts, are also con-
sidered executable. Directories are also reported as executable, for compatibility with
POSIX. These conventions are also followed by file-attributes (see Section 25.6.4
[File Attributes], page 536).
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.
form (high . low), where low holds the low 16 bits. If the inode number is too
wide for even that, the value is of the form (high middle . low), where high
holds the high bits, middle the middle 24 bits, and low the low 16 bits.
11. The filesystem number of the device that the file is on file-attribute-device-
number). Depending on the magnitude of the value, this can be either an integer
or a cons cell, in the same manner as the inode number. This element and the
file’s inode number together 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"
(20614 64019 50040 152000)
(20000 23 0 0)
(20614 64555 902289 872000)
122295 "-rw-rw-rw-"
t (5888 2 . 43978)
(15479 . 46724))
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’.
(20614 64019 50040 152000)
was last accessed on October 23, 2012, at 20:12:03.050040152 UTC.
(20000 23 0 0)
was last modified on July 15, 2001, at 08:53:43 UTC.
(20614 64555 902289 872000)
last had its status changed on October 23, 2012, at 20:20:59.902289872
UTC.
122295 is 122295 bytes long. (It may not contain 122295 characters, though, if
some of the bytes belong to multibyte sequences, and also if the end-of-
line format is CR-LF.)
"-rw-rw-rw-"
has a mode of read and write access for the owner, group, and world.
t is merely a placeholder; it carries no information.
(5888 2 . 43978)
has an inode number of 6473924464520138.
(15479 . 46724)
is on the file-system device whose number is 1014478468.
Chapter 25: Files 539
(file-nlinks "foo")
⇒ 2
(file-nlinks "doesnt-exist")
⇒ nil
$ ls -li fo*
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo2
84302 -rw-rw-rw- 1 rms 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 rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo2
81908 -rw-rw-rw- 3 rms 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 536.
If time is non-nil, then this function gives the new file the same last-modified time
that the old one has. (This works on only some operating systems.) If setting the
time gets an error, copy-file signals a file-date-error error. In an interactive
call, a prefix argument specifies a non-nil value for time.
If argument preserve-uid-gid is nil, we let the operating system decide the user and
group ownership of the new file (this is usually set to the user running Emacs). If
preserve-uid-gid is non-nil, we attempt to copy the user and group ownership of the
file. This works only on some operating systems, and only if you have the correct
permissions to do so.
If the optional argument preserve-permissions is non-nil, this function copies the file
modes (or “permissions”) of oldname to newname, as well as the Access Control List
and SELinux context (if any). See Section 25.6 [Information about Files], page 531.
Otherwise, the file modes of newname are left unchanged if it is an existing file, and
set to those of oldname, masked by the default file permissions (see set-default-
file-modes below), if newname is to be newly created. The Access Control List or
SELinux context are not copied over in either case.
If called non-interactively, mode must be an integer. Only the lowest 12 bits of the
integer are used; on most systems, only the lowest 9 bits are meaningful. You can use
the Lisp construct for octal numbers to enter mode. For example,
(set-file-modes #o644)
specifies that the file should be readable and writable for its owner, readable for group
members, and readable for all other users. See Section “File permissions” in The gnu
Coreutils Manual, for a description of mode bit specifications.
Interactively, mode is read from the minibuffer using read-file-modes (see below),
which lets the user type in either an integer or a string representing the permissions
symbolically.
See Section 25.6.4 [File Attributes], page 536, for the function file-modes, which
returns the permissions of a file.
default-file-modes [Function]
This function returns the default file permissions, as an integer.
the specification is based are taken from the mode bits of base-file. If base-file is
omitted or nil, the function uses 0 as the base mode bits. The complete and relative
specifications can be combined, as in "u+r,g+rx,o+r,g-w". See Section “File permis-
sions” in The gnu Coreutils Manual, for a description of file mode specifications.
file-modes-symbolic-to-number modes &optional base-modes [Function]
This function converts a symbolic file mode specification in modes into the equivalent
integer. If the symbolic specification is based on an existing file, that file’s mode bits
are taken from the optional argument base-modes; if that argument is omitted or nil,
it defaults to 0, i.e., no access rights at all.
set-file-times filename &optional time [Function]
This function sets the access and modification times of filename to time. The return
value is t if the times are successfully set, otherwise it is nil. time defaults to the
current time and must be a time value (see Section 40.5 [Time of Day], page 1086).
set-file-extended-attributes filename attribute-alist [Function]
This function sets the Emacs-recognized extended file attributes for filename. The
second argument attribute-alist should be an alist of the same form returned by
file-extended-attributes. The return value is t if the attributes are successfully
set, otherwise it is nil. See Section 25.6.5 [Extended Attributes], page 539.
set-file-selinux-context filename context [Function]
This function sets the SELinux security context for filename to context. The context
argument should be a list (user role type range), where each element is a string.
See Section 25.6.5 [Extended Attributes], page 539.
The function returns t if it succeeds in setting the SELinux context of filename. It
returns nil if the context was not set (e.g., if SELinux is disabled, or if Emacs was
compiled without SELinux support).
set-file-acl filename acl [Function]
This function sets the Access Control List for filename to acl. The acl argument
should have the same form returned by the function file-acl. See Section 25.6.5
[Extended Attributes], page 539.
The function returns t if it successfully sets the ACL of filename, nil otherwise.
(file-name-nondirectory "foo")
⇒ "foo"
(file-name-nondirectory "lewis/")
⇒ ""
Given a possibly relative file name, you can expand any leading ‘~’ and convert the result
to an absolute name using expand-file-name (see Section 25.9.4 [File Name Expansion],
page 550). This function converts absolute file names to relative names:
won’t work properly, and ‘$’ in an environment variable’s value could lead to repeated
substitution. Therefore, programs that call this function and put the output where it
will be passed to this function need to double all ‘$’ characters to prevent subsequent
incorrect results.
Here we assume that the environment variable HOME, which holds the user’s home
directory, has value ‘/xcssun/users/rms’.
(substitute-in-file-name "$HOME/foo")
⇒ "/xcssun/users/rms/foo"
After substitution, if a ‘~’ or a ‘/’ appears immediately after another ‘/’, the function
discards everything before it (up through the immediately preceding ‘/’).
(substitute-in-file-name "bar/~/foo")
⇒ "~/foo"
(substitute-in-file-name "/usr/local/$HOME/foo")
⇒ "/xcssun/users/rms/foo"
;; /usr/local/ has been discarded.
Sometimes, it is not desired to expand file names. In such cases, the file name can be
quoted to suppress the expansion, and to handle the file name literally. Quoting happens
by prefixing the file name with ‘/:’.
file-name-quote name [Macro]
This macro adds the quotation prefix ‘/:’ to the file name. For a local file name, it
prefixes name with ‘/:’. If name is a remote file name, the local part of name (see
Section 25.12 [Magic File Names], page 559) is quoted. If name is already a quoted
file name, name is returned unchanged.
(substitute-in-file-name (file-name-quote "bar/~/foo"))
⇒ "/:bar/~/foo"
(expand-file-name prefix
(or small-temporary-file-directory
temporary-file-directory)))
temporary-file-directory [Function]
The directory for writing temporary files via make-nearby-temp-file. In case of a
remote default-directory, this is a directory for temporary files on that remote
host. If such a directory does not exist, or default-directory ought to be lo-
cated on a mounted file system (see mounted-file-systems), the function returns
default-directory. For a non-remote and non-mounted default-directory, the
value of the variable temporary-file-directory is returned.
In order to extract the local part of the file’s name of a temporary file, use file-local-
name (see Section 25.12 [Magic File Names], page 559).
The argument partial-filename must be a file name containing no directory part and
no slash (or backslash on some systems). The current buffer’s default directory is
prepended to directory, if directory is not absolute.
In the following example, suppose that ~rms/lewis is the current default directory,
and has five files whose names begin with ‘f’: foo, file~, file.c, file.c.~1~, and
file.c.~2~.
(file-name-all-completions "f" "")
⇒ ("foo" "file~" "file.c.~2~"
"file.c.~1~" "file.c")
The fourth argument parents says whether to create parent directories if they don’t
exist. Interactively, this happens by default.
The fifth argument copy-contents, if non-nil, means to copy the contents of dirname
directly into newname if the latter is a directory name, instead of copying dirname
into it as a subdirectory.
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-directory, copy-file,
delete-directory, delete-file,
diff-latest-backup-file,
directory-file-name,
directory-files,
directory-files-and-attributes,
dired-compress-file, dired-uncache,
expand-file-name,
file-accessible-directory-p,
file-acl,
file-attributes,
file-directory-p,
file-equal-p,
file-executable-p, file-exists-p,
file-in-directory-p,
file-local-copy,
file-modes, file-name-all-completions,
file-name-as-directory,
file-name-case-insensitive-p,
file-name-completion,
file-name-directory,
file-name-nondirectory,
file-name-sans-versions, file-newer-than-file-p,
file-notify-add-watch, file-notify-rm-watch,
file-notify-valid-p,
file-ownership-preserved-p,
file-readable-p, file-regular-p,
file-remote-p, file-selinux-context,
file-symlink-p, file-truename, file-writable-p,
find-backup-file-name,
get-file-buffer,
insert-directory,
insert-file-contents,
load,
make-auto-save-file-name,
make-directory,
make-directory-internal,
make-symbolic-link,
process-file,
Chapter 25: Files 561
When a handler function decides to call the ordinary Emacs primitive for the operation
at hand, it needs to prevent the primitive from calling the same handler once again, thus
leading to an infinite recursion. The example above shows how to do this, with the vari-
ables inhibit-file-name-handlers and inhibit-file-name-operation. Be careful to
use them exactly as shown above; the details are crucial for proper behavior in the case of
multiple handlers, and for operations that have two file names that may each have handlers.
Handlers that don’t really do anything special for actual access to the file—such as the
ones that implement completion of host names for remote file names—should have a non-
nil safe-magic property. For instance, Emacs normally protects directory names it finds
in PATH from becoming magic, if they look like magic file names, by prefixing them with
‘/:’. 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.
Chapter 25: Files 562
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 &optional identification connected [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 /sudo::/some/file is /sudo:root@localhost:.
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. Implementers of file handlers need to ensure
this principle is valid.
identification specifies which part of the identifier shall be returned as string. identi-
fication can be the symbol method, user or host; any other value is handled like nil
and means to return the complete identifier string. In the example above, the remote
user identifier string would be root.
If connected is non-nil, this function returns nil even if filename is remote, if Emacs
has no network connection to its host. This is useful when you want to avoid the
delay of making connections when they don’t exist.
Chapter 25: Files 563
25.13.1 Overview
The function insert-file-contents:
• initially, inserts bytes from the file into the buffer;
• decodes bytes to characters as appropriate;
• processes formats as defined by entries in format-alist; and
• calls functions in after-insert-file-functions.
The function write-region:
• initially, calls functions in write-region-annotate-functions;
• processes formats as defined by entries in format-alist;
• encodes characters to bytes as appropriate; and
• modifies the file with the bytes.
This shows the symmetry of the lowest-level operations; reading and writing handle
things in opposite order. The rest of this section describes the two facilities surrounding
the three variables named above, as well as some related functions. Section 33.10 [Coding
Systems], page 848, for details on character encoding and decoding.
format-alist [Variable]
This list contains one format definition for each defined file format. Each format
definition is a list of this form:
(name doc-string regexp from-fn to-fn modify mode-fn preserve)
One responsibility of from-fn is to make sure that the beginning of the file no
longer matches regexp. Otherwise it is likely to get called again. Also, from-fn
must not involve buffers or files other than the one being decoded, otherwise
the internal buffer used for formatting might be overwritten.
to-fn A shell command or function to encode data in this format—that is, to convert
the usual Emacs data representation into this format.
If to-fn is a string, it is a shell command; Emacs runs the command as a filter
to perform the conversion.
If to-fn is a function, it is called with three arguments: begin and end, which
specify the part of the buffer it should convert, and buffer, which specifies which
buffer. There are two ways it can do the conversion:
• By editing the buffer in place. In this case, to-fn should return the end-
position of the range of text, as modified.
• By returning a list of annotations. This is a list of elements of the form
(position . string), where position is an integer specifying the relative
position in the text to be written, and string is the annotation to add there.
The list must be sorted in order of position when to-fn returns it.
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.
to-fn must not involve buffers or files other than the one being encoded, other-
wise the internal buffer used for formatting might be overwritten.
modify A flag, t if the encoding function modifies the buffer, and nil if it works by
returning a list of annotations.
mode-fn A minor-mode function to call after visiting a file converted from this format.
The function is called with one argument, the integer 1; that tells a minor-mode
function to enable the mode.
preserve A flag, t if format-write-file should not remove this format from
buffer-file-format.
The function insert-file-contents automatically recognizes file formats when it reads
the specified file. It checks the text of the beginning of the file against the regular expressions
of the format definitions, and if it finds a match, it calls the decoding function for that
format. Then it checks all the known formats over again. It keeps checking them until none
of them is applicable.
Visiting a file, with find-file-noselect or the commands that use it, performs conver-
sion likewise (because it calls insert-file-contents); it also calls the mode function for
each format that it decodes. It stores a list of the format names in the buffer-local variable
buffer-file-format.
buffer-file-format [Variable]
This variable states the format of the visited file. More precisely, this is a list of the
file format names that were decoded in the course of visiting the current buffer’s file.
It is always buffer-local in all buffers.
Chapter 25: Files 566
When write-region writes data into a file, it first calls the encoding functions for the
formats listed in buffer-file-format, in the order of appearance in the list.
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.
that changes the character at position 42 from ‘X’ to ‘F’. The next conversion will start
with the wrong data straight away.
To avoid conflict, cooperative conversions do not modify the buffer, but instead spec-
ify annotations, a list of elements of the form (position . string), sorted in order of
increasing position.
If there is more than one conversion, write-region merges their annotations destruc-
tively into one sorted list. Later, when the text from the buffer is actually written to the
file, it intermixes the specified annotations at the corresponding positions. All this takes
place without modifying the buffer.
In contrast, when reading, the annotations intermixed with the text are handled imme-
diately. insert-file-contents sets point to the beginning of some text to be converted,
then calls the conversion functions with the length of that text. These functions should al-
ways return with point at the beginning of the inserted text. This approach makes sense for
reading because annotations removed by the first converter can’t be mistakenly processed
by a later converter. Each conversion function should scan for the annotations it recognizes,
remove the annotation, modify the buffer text (to set a text property, for example), and
return the updated length of the text, as it stands after those changes. The value returned
by one function becomes the argument to the next function.
write-region-annotate-functions [Variable]
A list of functions for write-region to call. 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 annotations.
As a special case, a function may return with a different buffer current. Emacs takes
this to mean that the current buffer contains altered text to be output. It therefore
changes the start and end arguments of the write-region call, giving them the
values of point-min and point-max in the new buffer, respectively. It also discards
all previous annotations, because they should have been dealt with by this function.
write-region-post-annotation-function [Variable]
The value of this variable, if non-nil, should be a function. This function is called,
with no arguments, after write-region has completed.
If any function in write-region-annotate-functions returns with a different buffer
current, Emacs calls write-region-post-annotation-function more than once.
Emacs calls it with the last buffer that was current, and again with the buffer before
that, and so on back to the original buffer.
Thus, a function in write-region-annotate-functions can create a buffer, give this
variable the local value of kill-buffer in that buffer, set up the buffer with altered
text, and make the buffer current. The buffer will be killed after write-region is
done.
after-insert-file-functions [Variable]
Each function in this list is called by insert-file-contents with one argument, the
number of characters inserted, and with point at the beginning of the inserted text.
Each function should leave point unchanged, and return the new character count
describing the inserted text as modified by the function.
568
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.
569
Backup files and auto-save files are two methods by which Emacs tries to protect the user
from the consequences of crashes or of the user’s own errors. Auto-saving preserves the text
from earlier in the current editing session; backup files preserve file contents prior to the
current session.
backup-buffer [Function]
This function makes a backup of the file visited by the current buffer, if appropriate.
It is called by save-buffer before saving the buffer the first time.
If a backup was made by renaming, the return value is a cons cell of the form
(modes extra-alist backupname), where modes are the mode bits of the original file,
as returned by file-modes (see Section 25.6.1 [Testing Accessibility], page 531),
extra-alist is an alist describing the original file’s extended attributes, as returned
by file-extended-attributes (see Section 25.6.5 [Extended Attributes], page 539),
and backupname is the name of the backup.
In all other cases (i.e., if a backup was made by copying or if no backup was made),
this function returns nil.
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.
Chapter 26: Backups and Auto-Saving 570
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.
This could be buffer-local to do something special for specific files. If you change it,
you may need to change backup-file-name-p and file-name-sans-versions too.
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 573) 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.
files whose deletion is proposed. The value can also be nil, which means not to make
a backup.
Two variables, kept-old-versions and kept-new-versions, determine which
backup versions should be kept. This function keeps those versions by excluding
them from the cdr of the value. See Section 26.1.3 [Numbered Backups], page 572.
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#"
auto-save-mode arg [Command]
This is the mode command for Auto Save mode, a buffer-local minor mode. When
Auto Save mode is enabled, auto-saving is enabled in the buffer. The calling conven-
tion is the same as for other minor mode commands (see Section 23.3.1 [Minor Mode
Conventions], page 471).
Unlike most minor modes, there is no auto-save-mode variable. Auto Save mode
is enabled if buffer-auto-save-file-name is non-nil and buffer-saved-size (see
below) is non-zero.
auto-save-file-name-p filename [Function]
This function returns a non-nil value if filename is a string that could be the name
of an auto-save file. It assumes the usual naming convention for auto-save files: a
name that begins and ends with hash marks (‘#’) is a possible auto-save file name.
The argument filename should not contain a directory part.
(make-auto-save-file-name)
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
Chapter 26: Backups and Auto-Saving 575
(auto-save-file-name-p "#backups.texi#")
⇒ 0
(auto-save-file-name-p "backups.texi")
⇒ nil
The standard definition of this function is as follows:
(defun auto-save-file-name-p (filename)
"Return non-nil if FILENAME can be yielded by..."
(string-match "^#.*#$" filename))
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.
Note that setting this variable to a non-nil value does not change the fact that auto-
saving is different from saving the buffer; e.g., the hooks described in Section 25.2
[Saving Buffers], page 525, are not run when a buffer is auto-saved.
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-hook [Variable]
This normal hook is run whenever an auto-save is about to happen.
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
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.
If it is −2, that means this buffer should disregard changes in buffer size; in particular,
it should not shut off auto-saving temporarily due to changes in buffer size.
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.
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.
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.
revert-buffer-in-progress-p [Variable]
revert-buffer binds this variable to a non-nil value while it is working.
You can customize how revert-buffer does its work by setting the variables described
in the rest of this section.
revert-without-query [User Option]
This variable holds a list of files that should be reverted without query. The value
is a list of regular expressions. If the visited file name matches one of these regular
expressions, and the file has changed on disk but the buffer is not modified, then
revert-buffer reverts the file without asking the user for confirmation.
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. 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 re-
ceived.
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 special function to regenerate the contents.
revert-buffer-insert-file-contents-function [Variable]
The value of this variable 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 change 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.
Chapter 26: Backups and Auto-Saving 579
before-revert-hook [Variable]
This normal hook is run by the default revert-buffer-function before inserting
the modified contents. A custom revert-buffer-function may or may not run this
hook.
after-revert-hook [Variable]
This normal hook is run by the default revert-buffer-function after inserting the
modified contents. A custom revert-buffer-function may or may not run this
hook.
Emacs can revert buffers automatically. It does that by default for buffers visiting files.
The following describes how to add support for auto-reverting new types of buffers.
First, such buffers must have a suitable revert-buffer-function and buffer-stale-
function defined.
buffer-stale-function [Variable]
The value of this variable specifies a function to call to check whether a buffer needs
reverting. The default value only handles buffers that are visiting files, by checking
their modification time. Buffers that are not visiting files require a custom function
of one optional argument noconfirm. The function should return non-nil if the buffer
should be reverted. The buffer is current when this function is called.
While this function is mainly intended for use in auto-reverting, it could be used for
other purposes as well. For instance, if auto-reverting is not enabled, it could be
used to warn the user that the buffer needs reverting. The idea behind the noconfirm
argument is that it should be t if the buffer is going to be reverted without asking the
user and nil if the function is just going to be used to warn the user that the buffer
is out of date. In particular, for use in auto-reverting, noconfirm is t. If the function
is only going to be used for auto-reverting, you can ignore the noconfirm argument.
If you just want to automatically auto-revert every auto-revert-interval seconds
(like the Buffer Menu), use:
(setq-local buffer-stale-function
#'(lambda (&optional noconfirm) 'fast))
in the buffer’s mode function.
The special return value ‘fast’ tells the caller that the need for reverting was not
checked, but that reverting the buffer is fast. It also tells Auto Revert not to print
any revert messages, even if auto-revert-verbose is non-nil. This is important, as
getting revert messages every auto-revert-interval seconds can be very annoying.
The information provided by this return value could also be useful if the function is
consulted for purposes other than auto-reverting.
Once the buffer has a suitable revert-buffer-function and buffer-stale-function,
several problems usually remain.
The buffer will only auto-revert if it is marked unmodified. Hence, you will have to make
sure that various functions mark the buffer modified if and only if either the buffer contains
information that might be lost by reverting, or there is reason to believe that the user might
be inconvenienced by auto-reverting, because he is actively working on the buffer. The user
can always override this by manually adjusting the modified status of the buffer. To support
580
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.
When an editing command returns to the editor command loop, Emacs automatically
calls set-buffer on the buffer shown in the selected window. This is to prevent confusion:
it ensures that the buffer that the cursor is in, when Emacs reads a command, is the buffer
to which that command applies (see Chapter 21 [Command Loop], page 368). Thus, you
should not use set-buffer to switch visibly to a different buffer; for that, use the functions
described in Section 28.12 [Switching Buffers], page 628.
When writing a Lisp function, do not rely on this behavior of the command loop to
restore the current buffer after an operation. Editing commands can also be called as Lisp
functions by other programs, not just 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).
To operate temporarily on another buffer, put the set-buffer within a save-current-
buffer form. Here, as an example, is a simplified version of the command append-to-
buffer:
(defun append-to-buffer (buffer start end)
"Append the text of the region to BUFFER."
(interactive "BAppend to buffer: \nr")
(let ((oldbuf (current-buffer)))
(save-current-buffer
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
Here, we bind a local variable to record the current buffer, and then save-current-buffer
arranges to make it current again later. Next, set-buffer makes the specified buffer
current, and insert-buffer-substring copies the string from the original buffer to the
specified (and now current) buffer.
Alternatively, we can use the with-current-buffer macro:
(defun append-to-buffer (buffer start end)
"Append the text of the region to BUFFER."
(interactive "BAppend to buffer: \nr")
(let ((oldbuf (current-buffer)))
(with-current-buffer (get-buffer-create buffer)
(insert-buffer-substring oldbuf start end))))
In either case, if the buffer appended to happens to be displayed in some window, the
next redisplay will show how its text has changed. If it is not displayed in any window,
you will not see the change immediately on the screen. The command causes the buffer to
become current temporarily, but 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
Chapter 27: Buffers 583
and at the end of the local binding’s scope. Otherwise you might bind it in one buffer and
unbind it in another!
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. For instance, in the previous
example, it would have been wrong to do this:
(let ((oldbuf (current-buffer)))
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end)
(set-buffer oldbuf))
Using save-current-buffer or with-current-buffer, as we did, correctly handles quit-
ting, errors, and throw, as well as ordinary evaluation.
See also the function get-buffer-create in Section 27.9 [Creating Buffers], page 593.
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 593.
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 536, 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 no-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 588). 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.
Sometimes there’s a need for modifying buffer in a way that doesn’t really change its text,
like if only its text properties are changed. If your program needs to modify a buffer without
triggering any hooks and features that react to buffer modifications, use the with-silent-
modifications macro.
It always returns t for buffers that are not visiting a file, even if visited-file-
modtime returns a non-zero value. For instance, it always returns t for dired buffers.
It returns t for buffers that are visiting a file that does not exist and never existed,
but nil for file-visiting buffers whose file has been deleted.
clear-visited-file-modtime [Function]
This function clears out the record of the last modification time of the file being
visited by the current buffer. As a result, the next attempt to save this buffer will
not complain of a discrepancy in file modification times.
This function is called in set-visited-file-name and other exceptional places where
the usual test to avoid overwriting a changed file should not be done.
visited-file-modtime [Function]
This function returns the current buffer’s recorded last file modification time, as
a list of the form (high low microsec picosec). (This is the same format that
file-attributes uses to return time values; see Section 25.6.4 [File Attributes],
page 536.)
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 explic-
itly 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.
If the buffer is visiting a file that doesn’t exist, this function returns −1.
set-visited-file-modtime &optional time [Function]
This function updates the buffer’s record of the last modification time of the visited
file, to the value specified by time if time is not nil, and otherwise to the last
modification time of the visited file.
If time is neither nil nor an integer flag returned by visited-file-modtime,
it should have the form (high low microsec picosec), the format used by
current-time (see Section 40.5 [Time of Day], page 1086).
This function is useful if the buffer was not read from the file normally, or if the file
itself has been changed for some known benign reason.
ask-user-about-supersession-threat filename [Function]
This function is used to ask a user how to proceed after an attempt to modify a buffer
visiting file filename when the file is newer than the buffer text. Emacs detects this
because the modification time of the file on disk is newer than the last save-time and
its contents have changed. This means some other program has probably altered the
file.
Depending on the user’s answer, the function may return normally, in which case the
modification of the buffer proceeds, or it may signal a file-supersession error with
data (filename), in which case the proposed buffer modification is not allowed.
This function is called automatically by Emacs on the proper occasions. It exists so
you can customize Emacs by redefining it. See the file userlock.el for the standard
definition.
Chapter 27: Buffers 590
See also the file locking mechanism in Section 25.5 [File Locks], page 530.
(while new-list
(bury-buffer (car new-list))
(setq new-list (cdr new-list))))
With this method, you can specify any order for the list, but there is no danger of losing
a buffer or adding something that is not a valid live buffer.
To change the order or value of a specific frame’s buffer list, set that frame’s
buffer-list parameter with modify-frame-parameters (see Section 29.4.1 [Parameter
Access], page 700).
window is dedicated (see Section 28.15 [Dedicated Windows], page 650) and there are
other windows on its frame, the window is deleted. If it is the only window on its
frame and that frame is not the only frame on its terminal, the frame is dismissed
by calling the function specified by frame-auto-hide-function (see Section 28.16
[Quitting Windows], page 651). Otherwise, it calls switch-to-prev-buffer (see
Section 28.14 [Window History], page 649) to show another buffer in that window. If
buffer-or-name is displayed in some other window, it remains displayed there.
To replace a buffer in all the windows that display it, use replace-buffer-in-
windows, See Section 28.11 [Buffers and Windows], page 626.
unbury-buffer [Command]
This command switches to the last buffer in the local buffer list of the selected frame.
More precisely, it calls the function switch-to-buffer (see Section 28.12 [Switching
Buffers], page 628), to display the buffer returned by last-buffer (see above), in the
selected window.
buffer-list-update-hook [Variable]
This is a normal hook run whenever the buffer list changes. Functions (implicitly)
running this hook are get-buffer-create (see Section 27.9 [Creating Buffers],
page 593), rename-buffer (see Section 27.3 [Buffer Names], page 584), kill-buffer
(see Section 27.10 [Killing Buffers], page 594), bury-buffer (see above) and
select-window (see Section 28.9 [Selecting Windows], page 622).
Functions run by this hook should avoid calling select-window with a nil norecord
argument or with-temp-buffer since either may lead to infinite recursion.
tively. To prevent the request for confirmation, clear the modified flag before calling
kill-buffer. See Section 27.5 [Buffer Modification], page 587.
This function calls replace-buffer-in-windows for cleaning up all windows cur-
rently displaying the buffer to be killed.
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]
Before 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 453. This variable is a permanent
local, so its local binding is not cleared by changing major modes.
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.
This could be implemented with multiple buffers (kept in sync when the user edits the
text), or with narrowing (see Section 30.4 [Narrowing], page 753). But these alternatives
might sometimes become tedious or prohibitively expensive, especially if each type of text
requires expensive buffer-global operations in order to provide correct display and editing
commands.
Emacs provides another facility for such modes: you can quickly swap buffer text between
two buffers with buffer-swap-text. This function is very fast because it doesn’t move any
text, it only changes the internal data structures of the buffer object to point to a different
chunk of text. Using it, you can pretend that a group of two or more buffers are actually a
single virtual buffer that holds the contents of all the individual buffers together.
If you use buffer-swap-text on a file-visiting buffer, you should set up a hook to save
the buffer’s original text rather than what it was swapped with. write-region-annotate-
functions works for this purpose. You should probably set buffer-saved-size to −2 in
the buffer, so that changes in the text it is swapped with will not interfere with auto-saving.
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.
598
28 Windows
This chapter describes the functions and variables related to Emacs windows. See
Chapter 29 [Frames], page 683, for how windows are assigned an area of screen available
for Emacs to use. See Chapter 39 [Display], page 967, for information on how text is
displayed in windows.
In each frame, at any time, exactly one Emacs window is designated as selected within
the frame. For the selected frame, that window is called the selected window—the one in
which most editing takes place, and in which the cursor for selected windows appears (see
Section 29.4.3.9 [Cursor Parameters], page 713). Keyboard input that inserts or deletes text
is also normally directed to this window. The selected window’s buffer is usually also the
current buffer, except when set-buffer has been used (see Section 27.2 [Current Buffer],
page 581). As for non-selected frames, the window selected within the frame becomes
the selected window if the frame is ever selected. See Section 28.9 [Selecting Windows],
page 622.
selected-window [Function]
This function returns the selected window (which is always a live window).
Sometimes several windows collectively and cooperatively display a buffer, for example,
under the management of Follow Mode (see Section “Follow Mode” in emacs), where the
windows together display a bigger portion of the buffer than one window could alone. It is
often useful to consider such a window group as a single entity. Several functions such as
window-group-start (see Section 28.20 [Window Start and End], page 661) allow you to
do this by supplying, as an argument, one of the windows as a stand in for the whole group.
selected-window-group [Function]
When the selected window is a member of a group of windows, this function returns
a list of the windows in the group, ordered such that the first window in the list is
displaying the earliest part of the buffer, and so on. Otherwise the function returns
a list containing just the selected window.
The selected window is considered part of a group when the buffer local
variable selected-window-group-function is set to a function. In this case,
selected-window-group calls it with no arguments and returns its result (which
should be the list of windows in the group).
Windows in the same frame are organized into a window tree, whose leaf nodes are the
live windows. The internal nodes of a window tree are not live; they exist for the purpose
of organizing the relationships between live windows. The root node of a window tree is
called the root window. It can be either a live window (if the frame has just one window),
or an internal window.
A minibuffer window (see Section 20.11 [Minibuffer Windows], page 364) that is not
alone on its frame does not have a parent window, so it strictly speaking is not part of its
frame’s window tree. Nonetheless, it is a sibling window of the frame’s root window, and
thus can be reached via window-next-sibling. Also, the function window-tree described
at the end of this section lists the minibuffer window alongside the actual window tree.
When a window is split, there are two live windows where previously there was one. One
of these is represented by the same Lisp window object as the original window, and the other
is represented by a newly-created Lisp window object. Both of these live windows become
leaf nodes of the window tree, as child windows of a single internal window. If necessary,
Emacs automatically creates this internal window, which is also called the parent window,
and assigns it to the appropriate position in the window tree. A set of windows that share
the same parent are called siblings.
Each internal window always has at least two child windows. If this number falls to one
as a result of window deletion, Emacs automatically deletes the internal window, and its
sole remaining child window takes its place in the window tree.
Each child window can be either a live window, or an internal window (which in turn
would have its own child windows). Therefore, each internal window can be thought of as
occupying a certain rectangular screen area—the union of the areas occupied by the live
windows that are ultimately descended from it.
For each internal window, the screen areas of the immediate children are arranged either
vertically or horizontally (never both). If the child windows are arranged one above the
other, they are said to form a vertical combination; if they are arranged side by side, they
are said to form a horizontal combination. Consider the following example:
Chapter 28: Windows 601
______________________________________
| ______ ____________________________ |
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| ||| |||
|| |||____________W4____________|||
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| |||____________W5____________|||
||__W2__||_____________W3_____________ |
|__________________W1__________________|
The root window of this frame is an internal window, W1. Its child windows form a
horizontal combination, consisting of the live window W2 and the internal window W3.
The child windows of W3 form a vertical combination, consisting of the live windows W4
and W5. Hence, the live windows in this window tree are W2, W4, and W5.
The following functions can be used to retrieve a child window of an internal window,
and the siblings of a child window.
Don’t use this function to check whether there is no window in direction. Calling
window-at-side-p described above is a much more efficient way to do that.
The following function allows the entire window tree of a frame to be retrieved:
window-tree &optional frame [Function]
This function returns a list representing the window tree for frame frame. If frame is
omitted or nil, it defaults to the selected frame.
The return value is a list of the form (root mini), where root represents the window
tree of the frame’s root window, and mini is the frame’s minibuffer window.
If the root window is live, root is that window itself. Otherwise, root is a list (dir
edges w1 w2 ...) where dir is nil for a horizontal combination and t for a vertical
combination, edges gives the size and position of the combination, and the remaining
elements are the child windows. Each child window may again be a window object
(for a live window) or a list with the same format as above (for an internal window).
The edges element is a list (left top right bottom), similar to the value returned
by window-edges (see Section 28.24 [Coordinates and Windows], page 671).
At the center of the window is the text area, or body, where the buffer text is displayed.
The text area can be surrounded by a series of optional areas. On the left and right, from
innermost to outermost, these are the left and right fringes, denoted by LF and RF (see
Section 39.13 [Fringes], page 1019); the left and right margins, denoted by LM and RM in
the schematic (see Section 39.16.5 [Display Margins], page 1033); the left or right vertical
scroll bar, only one of which is present at any time, denoted by LS and RS (see Section 39.14
[Scroll Bars], page 1025); and the right divider, denoted by RD (see Section 39.15 [Window
Dividers], page 1027). At the top of the window is the header line (see Section 23.4.7
[Header Lines], page 484). At the bottom of the window are the horizontal scroll bar (see
Section 39.14 [Scroll Bars], page 1025); the mode line (see Section 23.4 [Mode Line Format],
page 476); and the bottom divider (see Section 39.15 [Window Dividers], page 1027).
Emacs provides miscellaneous functions for finding the height and width of a window.
The return value of many of these functions can be specified either in units of pixels or in
units of lines and columns. On a graphical display, the latter actually correspond to the
height and width of a default character specified by the frame’s default font as returned by
Chapter 28: Windows 604
frame-char-height and frame-char-width (see Section 29.3.2 [Frame Font], page 694).
Thus, if a window is displaying text with a different font or size, the reported line height and
column width for that window may differ from the actual number of text lines or columns
displayed within it.
The total height of a window is the number of lines comprising the window’s body, the
header line, the horizontal scroll bar, the mode line and the bottom divider (if any).
The total width of a window is the number of lines comprising the window’s body, its
margins, fringes, scroll bars and a right divider (if any).
The following two functions can be used to return the total size of a window in units of
pixels.
The following functions can be used to determine whether a given window has any
adjacent windows.
The body height of a window is the height of its text area, which does not include a
mode or header line, a horizontal scroll bar, or a bottom divider.
Chapter 28: Windows 606
The body width of a window is the width of its text area, which does not include the
scroll bar, fringes, margins or a right divider. Note that when one or both fringes are
removed (by setting their width to zero), the display engine reserves two character cells,
one on each side of the window, for displaying the continuation and truncation glyphs,
which leaves 2 columns less for text display. (The function window-max-chars-per-line,
described below, takes this peculiarity into account.)
The return value makes sure that all components of window remain fully visible if
window’s size were actually set to it. With horizontal nil it includes the mode
and header line, the horizontal scroll bar and the bottom divider, if present. With
horizontal non-nil it includes the margins and fringes, the vertical scroll bar and the
right divider, if present.
The optional argument ignore, if non-nil, means ignore restrictions imposed by
fixed size windows, window-min-height or window-min-width settings. If ignore
equals safe, live windows may get as small as window-safe-min-height lines and
window-safe-min-width columns. If ignore is a window, ignore restrictions for that
window only. Any other non-nil value means ignore all of the above restrictions for
all windows.
The optional argument pixelwise non-nil means to return the minimum size of win-
dow counted in pixels.
buffer. The optional argument max-height, if non-nil, specifies the maximum total
height that this function can give window. The optional argument min-height, if
non-nil, specifies the minimum total height that it can give, which overrides the
variable window-min-height. Both max-height and min-height are specified in lines
and include mode and header line and a bottom divider, if any.
If window is part of a horizontal combination and the value of the option fit-window-
to-buffer-horizontally (see below) is non-nil, this function adjusts window’s
width. The new width of window is calculated from the maximum length of its buffer’s
lines that follow the current start position of window. The optional argument max-
width specifies a maximum width and defaults to the width of window’s frame. The
optional argument min-width specifies a minimum width and defaults to window-min-
width. Both max-width and min-width are specified in columns and include fringes,
margins and scrollbars, if any.
The optional argument preserve-size, if non-nil, will install a parameter to preserve
the size of window during future resize operations (see Section 28.5 [Preserving Win-
dow Sizes], page 612).
If the option fit-frame-to-buffer (see below) is non-nil, this function will try to
resize the frame of window to fit its contents by calling fit-frame-to-buffer (see
below).
If you have a frame that displays only one window, you can fit that frame to its buffer
using the command fit-frame-to-buffer.
The behavior of fit-frame-to-buffer can be controlled with the help of the two options
listed next.
balance-windows-area [Command]
This function attempts to give all windows on the selected frame approximately the
same share of the screen area. Full-width or full-height windows are not given more
space than other windows.
window-size-fixed [Variable]
If this buffer-local variable is non-nil, the size of any window displaying the buffer
cannot normally be changed. Deleting a window or changing the frame’s size may
still change the window’s size, if there is no 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.
If this variable is nil, this does not necessarily mean that any window showing the
buffer can be resized in the desired direction. To determine that, use the function
window-resizable. See Section 28.4 [Resizing Windows], page 608.
display-buffer
If the alist argument of that function (see Section 28.13.1 [Choosing Window],
page 630) contains a preserve-size entry, the size of the window produced by
that function is preserved.
window-preserve-size installs a window parameter (see Section 28.27 [Window Param-
eters], page 678) called window-preserved-size which is consulted by the window resizing
functions. This parameter will not prevent resizing the window when the window shows
another buffer than the one when window-preserve-size was invoked or if its size has
changed since then.
The following function can be used to check whether the height of a particular window
is preserved:
As an example, here is a sequence of split-window calls that yields the window config-
uration discussed in Section 28.2 [Windows and Frames], page 599. This example demon-
strates splitting a live window as well as splitting an internal window. We begin with a
frame containing a single window (a live root window), which we denote by W4. Calling
(split-window W4) yields this window configuration:
______________________________________
| ____________________________________ |
|| ||
|| ||
|| ||
||_________________W4_________________||
| ____________________________________ |
|| ||
|| ||
|| ||
||_________________W5_________________||
|__________________W3__________________|
The split-window call has created a new live window, denoted by W5. It has also created
a new internal window, denoted by W3, which becomes the root window and the parent of
both W4 and W5.
Next, we call (split-window W3 nil 'left), passing the internal window W3 as the
argument. The result:
Chapter 28: Windows 615
______________________________________
| ______ ____________________________ |
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| ||| |||
|| |||____________W4____________|||
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| |||____________W5____________|||
||__W2__||_____________W3_____________ |
|__________________W1__________________|
A new live window W2 is created, to the left of the internal window W3. A new internal
window W1 is created, becoming the new root window.
For interactive use, Emacs provides two commands which always split the selected win-
dow. These call split-window internally.
side windows (see Section 28.17 [Side Windows], page 654), an error is signaled. If
window is part of an atomic window (see Section 28.18 [Atomic Windows], page 658),
this function tries to delete the root of that atomic window instead.
By default, the space taken up by window is given to one of its adjacent sibling
windows, if any. However, if the variable window-combination-resize is non-nil,
the space is proportionally distributed among any remaining windows in the same
window combination. See Section 28.8 [Recombining Windows], page 617.
The behavior of this function may be altered by the window parameters of window,
so long as the variable ignore-window-parameters is nil. If the value of the
delete-window window parameter is t, this function ignores all other window pa-
rameters. Otherwise, if the value of the delete-window window parameter is a func-
tion, that function is called with the argument window, in lieu of the usual action of
delete-window. See Section 28.27 [Window Parameters], page 678.
Note that this argument does not have the same meaning as in other functions which
scan all live windows (see Section 28.10 [Cyclic Window Ordering], page 624). Specif-
ically, the meanings of t and nil here are the opposite of what they are in those other
functions.
Deleting W5 in this configuration normally causes the deletion of W3 and W4. The remain-
ing live windows W2, W6 and W7 are recombined to form a new horizontal combination
with parent W1.
Sometimes, however, it makes sense to not delete a parent window like W4. In partic-
ular, a parent window should not be removed when it was used to preserve a combination
embedded in a combination of the same type. Such embeddings make sense to assure that
when you split a window and subsequently delete the new window, Emacs reestablishes the
layout of the associated frame as it existed before the splitting.
Consider a scenario starting with two live windows W2 and W3 and their parent W1.
______________________________________
| ____________________________________ |
|| ||
|| ||
|| ||
|| ||
|| ||
|| ||
||_________________W2_________________||
| ____________________________________ |
|| ||
|| ||
||_________________W3_________________||
|__________________W1__________________|
______________________________________
| ____________________________________ |
|| ||
|| ||
||_________________W2_________________||
| ____________________________________ |
|| ||
|| ||
||_________________W4_________________||
| ____________________________________ |
|| ||
|| ||
||_________________W3_________________||
|__________________W1__________________|
Now, when enlarging a window vertically, Emacs tries to obtain the corresponding space
from its lower sibling, provided such a window exists. In our scenario, enlarging W4 will
steal space from W3.
______________________________________
| ____________________________________ |
|| ||
|| ||
||_________________W2_________________||
| ____________________________________ |
|| ||
|| ||
|| ||
|| ||
||_________________W4_________________||
| ____________________________________ |
||_________________W3_________________||
|__________________W1__________________|
Deleting W4 will now give its entire space to W2, including the space earlier stolen from
W3.
______________________________________
| ____________________________________ |
|| ||
|| ||
|| ||
|| ||
|| ||
|| ||
|| ||
|| ||
||_________________W2_________________||
| ____________________________________ |
||_________________W3_________________||
|__________________W1__________________|
This can be counterintuitive, in particular if W4 were used for displaying a buffer only
temporarily (see Section 39.8 [Temporary Displays], page 981), and you want to continue
working with the initial layout.
The behavior can be fixed by making a new parent window when splitting W2. The
variable described next allows that to be done.
Chapter 28: Windows 619
nil This means that the new live window is allowed to share the existing par-
ent window, if one exists, provided the split occurs in the same direction
as the existing window combination (otherwise, a new internal window is
created anyway).
window-size
This means that display-buffer makes a new parent window when it
splits a window and is passed a window-height or window-width entry in
the alist argument (see Section 28.13.2 [Buffer Display Action Functions],
page 632). Otherwise, window splitting behaves as for a value of nil.
temp-buffer-resize
In this case with-temp-buffer-window makes a new parent window
when it splits a window and temp-buffer-resize-mode is enabled (see
Section 39.8 [Temporary Displays], page 981). Otherwise, window split-
ting behaves as for nil.
temp-buffer
In this case with-temp-buffer-window always makes a new parent win-
dow when it splits an existing window (see Section 39.8 [Temporary Dis-
plays], page 981). Otherwise, window splitting behaves as for nil.
display-buffer
This means that when display-buffer (see Section 28.13.1 [Choosing
Window], page 630) splits a window it always makes a new parent window.
Otherwise, window splitting behaves as for nil.
t This means that splitting a window always creates a new parent window.
Thus, if the value of this variable is at all times t, then at all times every
window tree is a binary tree (a tree where each window except the root
window has exactly one sibling).
The default is window-size. Other values are reserved for future use.
If, as a consequence of this variable’s setting, split-window makes a new parent win-
dow, it also calls set-window-combination-limit (see below) on the newly-created
internal window. This affects how the window tree is rearranged when the child
windows are deleted (see below).
______________________________________
| ____________________________________ |
|| __________________________________ ||
||| |||
|||________________W2________________|||
|| __________________________________ ||
||| |||
|||________________W4________________|||
||_________________W5_________________||
| ____________________________________ |
|| ||
|| ||
||_________________W3_________________||
|__________________W1__________________|
A new internal window W5 has been created; its children are W2 and the new live window
W4. Now, W2 is the only sibling of W4, so enlarging W4 will try to shrink W2, leaving W3
unaffected. Observe that W5 represents a vertical combination of two windows embedded
in the vertical combination W1.
Alternatively, the problems sketched above can be avoided by always resizing all windows
in the same combination whenever one of its windows is split or deleted. This also permits
splitting windows that would be otherwise too small for such an operation.
The default is nil. Other values are reserved for future use. A specific split op-
eration may ignore the value of this variable if it is affected by a non-nil value of
window-combination-limit.
Deleting any of the live windows W2, W3 or W4 will distribute its space proportionally
among the two remaining live windows.
For historical reasons, Emacs does not run a separate hook whenever a window gets
selected. Applications and internal routines often temporarily select a window to perform
a few actions on it. They do that either to simplify coding—because many functions by
default operate on the selected window when no window argument is specified—or because
some functions did not (and still do not) take a window as argument and always operate(d)
on the selected window instead. Running a hook every time a window gets selected for a
short time and once more when the previously selected window gets restored is not useful.
However, when its norecord argument is nil, select-window updates the buffer list and
thus indirectly runs the normal hook buffer-list-update-hook (see Section 27.8 [Buffer
List], page 591). Consequently, that hook provides a reasonable way to run a function
whenever a window gets selected more “permanently”.
Since buffer-list-update-hook is also run by functions that are not related to window
management, it will usually make sense to save the value of the selected window somewhere
and compare it with the value of selected-window while running that hook. Also, to
avoid false positives when using buffer-list-update-hook, it is good practice that every
select-window call supposed to select a window only temporarily passes a non-nil norecord
argument. If possible, the macro with-selected-window (see below) should be used in such
cases.
The sequence of calls to select-window with a non-nil norecord argument determines
an ordering of windows by their selection time. The function get-lru-window can be
Chapter 28: Windows 623
used to retrieve the least recently selected live window (see Section 28.10 [Cyclic Window
Ordering], page 624).
This function does not select a window that has a non-nil no-other-window win-
dow parameter (see Section 28.27 [Window Parameters], page 678), provided that
ignore-window-parameters is nil.
If the other-window parameter of the selected window is a function, and
ignore-window-parameters is nil, that function will be called with the arguments
count and all-frames instead of the normal operation of this function.
walk-windows fun &optional minibuf all-frames [Function]
This function calls the function fun once for each live window, with the window as
the argument.
It follows the cyclic ordering of windows. The optional arguments minibuf and all-
frames specify the set of windows included; these have the same arguments as in
next-window. If all-frames specifies a frame, the first window walked is the first
window on that frame (the one returned by frame-first-window), not necessarily
the selected window.
If fun changes the window configuration by splitting or deleting windows, that does
not alter the set of windows walked, which is determined prior to calling fun for the
first time.
one-window-p &optional no-mini all-frames [Function]
This function returns t if the selected window is the only live window, and nil
otherwise.
If the minibuffer window is active, it is normally considered (so that this function
returns nil). However, if the optional argument no-mini is non-nil, the minibuffer
window is ignored even if active. The optional argument all-frames has the same
meaning as for next-window.
The following functions return a window which satisfies some criterion, without selecting
it:
get-lru-window &optional all-frames dedicated not-selected [Function]
This function returns a live window which is heuristically the least recently used. The
optional argument all-frames has the same meaning as in next-window.
If any full-width windows are present, only those windows are considered. A minibuf-
fer window is never a candidate. A dedicated window (see Section 28.15 [Dedicated
Windows], page 650) is never a candidate unless the optional argument dedicated
is non-nil. The selected window is never returned, unless it is the only candidate.
However, if the optional argument not-selected is non-nil, this function returns nil
in that case.
get-mru-window &optional all-frames dedicated not-selected [Function]
This function is like get-lru-window, but it returns the most recently used window
instead. The meaning of the arguments is the same as described for get-lru-window.
get-largest-window &optional all-frames dedicated not-selected [Function]
This function returns the window with the largest area (height times width). The op-
tional argument all-frames specifies the windows to search, and has the same meaning
as in next-window.
Chapter 28: Windows 626
buffer-display-count [Variable]
This buffer-local variable records the number of times a buffer has been displayed in
a window. It is incremented each time set-window-buffer is called for the buffer.
buffer-display-time [Variable]
This buffer-local variable records the time at which a buffer was last displayed in
a window. The value is nil if the buffer has never been displayed. It is updated
each time set-window-buffer is called for the buffer, with the value returned by
current-time (see Section 40.5 [Time of Day], page 1086).
The next two commands are similar to switch-to-buffer, except for the described
features.
The above commands use the function pop-to-buffer, which flexibly displays a
buffer in some window and selects that window for editing. In turn, pop-to-buffer
uses display-buffer for displaying the buffer. Hence, all the variables affecting
display-buffer will affect it as well. See Section 28.13.1 [Choosing Window], page 630,
for the documentation of display-buffer.
If that window is on a different graphical frame, that frame is given input focus if
possible (see Section 29.10 [Input Focus], page 720).
If buffer-or-name is nil, it defaults to the buffer returned by other-buffer (see
Section 27.8 [Buffer List], page 591). If buffer-or-name is a string that is not the
name of any existing buffer, this function creates a new buffer with that name; the
new buffer’s major mode is determined by the variable major-mode (see Section 23.2
[Major Modes], page 455). In any case, that buffer is made current and returned,
even when no suitable window was found to display it.
If action is non-nil, it should be a display action to pass to display-buffer (see
Section 28.13.1 [Choosing Window], page 630). Alternatively, a non-nil, non-list
value means to pop to a window other than the selected one—even if the buffer is
already displayed in the selected window.
Like switch-to-buffer, this function updates the buffer list unless norecord is non-
nil.
An action function accepts two arguments: the buffer to display and an action alist. It
attempts to display the buffer in some window, picking or creating a window according to
its own criteria. If successful, it returns the window; otherwise, it returns nil.
display-buffer works by combining display actions from several sources, and calling
the action functions in turn, until one of them manages to display the buffer and returns a
non-nil value.
display-buffer buffer-or-name &optional action frame [Command]
This command makes buffer-or-name appear in some window, without selecting the
window or making the buffer current. The argument buffer-or-name must be a buffer
or the name of an existing buffer. The return value is the window chosen to display
the buffer, or nil if no suitable window was found.
The optional argument action, if non-nil, should normally be a display action (de-
scribed above). display-buffer builds a list of action functions and an action alist,
by consolidating display actions from the following sources (in order of their prece-
dence, from highest to lowest):
• The variable display-buffer-overriding-action.
• The user option display-buffer-alist.
• The action argument.
• The user option display-buffer-base-action.
• The constant display-buffer-fallback-action.
In practice this means that display-buffer builds a list of all action functions
specified by these display actions. The first element of this list is the first ac-
tion function specified by display-buffer-overriding-action, if any. Its last
element is display-buffer-pop-up-frame—the last action function specified by
display-buffer-fallback-action. Duplicates are not removed from this list—
hence one and the same action function may be called multiple times during one call
of display-buffer.
display-buffer calls the action functions specified by this list in turn, passing the
buffer as the first argument and the combined action alist as the second argument,
until one of the functions returns non-nil. See Section 28.13.5 [Precedence of Action
Functions], page 641, for examples how display actions specified by different sources
are processed by display-buffer.
Note that the second argument is always the list of all action alist entries specified
by the sources named above. Hence, the first element of that list is the first action
alist entry specified by display-buffer-overriding-action, if any. Its last element
is the last alist entry of display-buffer-base-action, if any (the action alist of
display-buffer-fallback-action is empty).
Note also, that the combined action alist may contain duplicate entries and entries
for the same key with different values. As a rule, action functions always use the first
association of a key they find. Hence, the association an action function uses is not
necessarily the association provided by the display action that specified that action
function,
The argument action can also have a non-nil, non-list value. This has the special
meaning that the buffer should be displayed in a window other than the selected one,
Chapter 28: Windows 632
even if the selected window is already displaying it. If called interactively with a
prefix argument, action is t. Lisp programs should always supply a list value.
The optional argument frame, if non-nil, specifies which frames to check when de-
ciding whether the buffer is already displayed. It is equivalent to adding an element
(reusable-frames . frame) to the action alist of action (see Section 28.13.3 [Buffer
Display Action Alists], page 635). The frame argument is provided for compatibility
reasons, Lisp programs should not use it.
display-buffer-overriding-action [Variable]
The value of this variable should be a display action, which is treated with the highest
priority by display-buffer. The default value is an empty display action, i.e.,
(nil . nil).
display-buffer-fallback-action [Constant]
This display action specifies the fallback behavior for display-buffer if no other
display actions are given.
If this function chooses a window on another frame, it makes that frame visible and,
unless alist contains an inhibit-switch-frame entry, raises that frame if necessary.
If this function chooses a window on another frame, it makes that frame visible and,
unless alist contains an inhibit-switch-frame entry, raises that frame if necessary.
If alist has a non-nil frame-predicate entry, its value is a function taking one
argument (a frame), returning non-nil if the frame is a candidate; this function
replaces the default predicate.
If alist has a non-nil inhibit-same-window entry, the selected window is not used;
thus if the selected frame has a single window, it is not used.
inhibit-same-window
If the value is non-nil, this signals that the selected window must not be used
for displaying the buffer. All action functions that (re-)use an existing window
should respect this entry.
Chapter 28: Windows 636
previous-window
The value must specify a window that may have displayed the buffer previously.
display-buffer-in-previous-window will give preference to such a window
provided it is still live and not dedicated to another buffer.
mode The value is either a major mode or a list of major modes. display-buffer-
reuse-mode-window may reuse a window whenever the value specified by this
entry matches the major mode of that window’s buffer. Other action functions
ignore such entries.
frame-predicate
The value must be a function taking one argument (a frame), supposed to
return non-nil if that frame is a candidate for displaying the buffer. This entry
is used by display-buffer-use-some-frame.
reusable-frames
The value specifies the set of frames to search for a window that can be reused
because it already displays the buffer. It can be set as follows:
• nil means consider only windows on the selected frame. (Actually, the
last frame used that is not a minibuffer-only frame.)
• t means consider windows on all frames.
• visible means consider windows on all visible frames.
• 0 means consider windows on all visible or iconified frames.
• A frame means consider windows on that frame only.
Note that the meaning of nil differs slightly from that of the all-frames argu-
ment to next-window (see Section 28.10 [Cyclic Window Ordering], page 624).
A major client of this is display-buffer-reuse-window, but all other action
functions that try to reuse a window are affected as well. display-buffer-
in-previous-window consults it when searching for a window that previosuly
displayed the buffer on another frame.
inhibit-switch-frame
A non-nil value prevents another frame from being raised or selected, if the
window chosen by display-buffer is displayed there. Primarily affected by
this are display-buffer-use-some-frame and display-buffer-reuse-
window. display-buffer-pop-up-frame should be affected as well, but there
is no guarantee that the window manager will comply.
window-parameters
The value specifies an alist of window parameters to give the chosen window.
All action functions that choose a window should process this entry.
window-height
The value specifies whether and how to adjust the height of the chosen window
and can be one of the following:
• nil means to leave the height of the chosen window alone.
• An integer number specifies the desired total height of the chosen window
in lines.
Chapter 28: Windows 637
child-frame-parameters
The value specifies an alist of frame parameters to use when the buffer is dis-
played on a child frame. This entry is used only by display-buffer-in-child-
frame.
side The value denotes the side of the frame or window where a new window dis-
playing the buffer shall be created. This entry is used by display-buffer-in-
side-window to indicate the side of the frame where a new side window shall
be placed (see Section 28.17.1 [Displaying Buffers in Side Windows], page 654).
It is also used by display-buffer-in-atom-window to indicate the side of
an existing window where the new window shall be located (see Section 28.18
[Atomic Windows], page 658).
slot If non-nil, the value specifies the slot of the side window supposed to display
the buffer. This entry is used only by display-buffer-in-side-window.
window The value specifies a window that is in some way related to the window chosen
by display-buffer. This entry is currently used by display-buffer-in-
atom-window to indicate the window on whose side the new window shall be
created.
allow-no-window
If the value is non-nil, display-buffer does not necessarily have to display
the buffer and the caller is prepared to accept that. This entry is not intended
for user customizations, since there is no guarantee that an arbitrary caller of
display-buffer will be able to handle the case that no window will display
the buffer. display-buffer-no-window is the only action function that cares
about this entry.
By convention, the entries window-height, window-width and preserve-size are ap-
plied after the chosen window’s buffer has been set up and if and only if that window never
showed another buffer before. More precisely, the latter means that the window must have
been either created by the current display-buffer call or the window was created earlier
by display-buffer to show the buffer and never was used to show another buffer until it
was reused by the current invocation of display-buffer.
A non-nil value also means that when display-buffer is looking for a window
already displaying buffer-or-name, it can search any visible or iconified frame, not
just the selected frame.
This variable is provided mainly for backward compatibility. It is obeyed by
display-buffer via a special mechanism in display-buffer-fallback-action,
which calls the action function display-buffer-pop-up-frame (see Section 28.13.2
[Buffer Display Action Functions], page 632) if the value is non-nil. (This is
done before attempting to split a window.) This variable is not consulted by
display-buffer-pop-up-frame itself, which the user may specify directly in
display-buffer-alist etc.
Many efforts in the design of display-buffer have been given to maintain compatibility
with code that uses older options like pop-up-windows, pop-up-frames, pop-up-frame-
alist, same-window-buffer-names and same-window-regexps. Lisp Programs and users
should refrain from using these options. Above we already warned against customizing
pop-up-frame-alist. Here we describe how to convert the remaining options to use display
actions instead.
pop-up-windows
This variable is t by default. Instead of customizing it to nil and thus telling
display-buffer what not to do, it’s much better to list in display-buffer-
base-action the action functions it should try instead as, for example:
Chapter 28: Windows 641
(customize-set-variable
'display-buffer-base-action
'((display-buffer-reuse-window display-buffer-same-window
display-buffer-in-previous-window
display-buffer-use-some-window)))
pop-up-frames
Instead of customizing this variable to t, customize display-buffer-base-
action, for example, as follows:
(customize-set-variable
'display-buffer-base-action
'((display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . 0)))
same-window-buffer-names
same-window-regexps
Instead of adding a buffer name or a regular expression to one of these op-
tions use a display-buffer-alist entry for that buffer specifying the action
function display-buffer-same-window.
(customize-set-variable
'display-buffer-alist
(cons '("\\*foo\\*" (display-buffer-same-window))
display-buffer-alist))
Let’s assume you did not type C-x o and *foo* is shown in the lower window. Type
C-x o to get there followed by C-x left and evaluate the form again. This should display
*foo* in the same, lower window because that window had already shown *foo* previously
and was therefore chosen instead of some other window.
So far we have only observed the default behavior in an uncustomized Emacs session. To
see how this behavior can be customized, let’s consider the option display-buffer-base-
action. It provides a very coarse customization which conceptually affects the display
of any buffer. It can be used to supplement the actions supplied by display-buffer-
fallback-action by reordering them or by adding actions that are not present there but
fit more closely the user’s editing practice. However, it can also be used to change the
default behavior in a more profound way.
Let’s consider a user who, as a rule, prefers to display buffers on another frame. Such a
user might provide the following customization:
(customize-set-variable
'display-buffer-base-action
'((display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . 0)))
This setting will cause display-buffer to first try to find a window showing the buffer on a
visible or iconified frame and, if no such frame exists, pop up a new frame. You can observe
this behavior on a graphical system by typing C-x 1 in the window showing *scratch* and
evaluating our canonical display-buffer form. This will usually create (and give focus to)
a new frame whose root window shows *foo*. Iconify that frame and evaluate the canonical
form again: display-buffer will reuse the window on the new frame (usually raising the
frame and giving it focus too).
Only if creating a new frame fails, display-buffer will apply the actions supplied by
display-buffer-fallback-action which means to again try reusing a window, popping
up a new window and so on. A trivial way to make frame creation fail is supplied by the
following form:
(let ((pop-up-frame-function 'ignore))
(display-buffer (get-buffer-create "*foo*")))
We will forget about that form immediately after observing that it fails to create a new
frame and uses a fallback action instead.
Note that display-buffer-reuse-window appears redundant in the customization of
display-buffer-base-action because it is already part of display-buffer-fallback-
action and should be tried there anyway. However, that would fail because due to the
precedence of display-buffer-base-action over display-buffer-fallback-action, at
that time display-buffer-pop-up-frame would have already won the race. In fact, this:
(customize-set-variable
'display-buffer-base-action
'(display-buffer-pop-up-frame (reusable-frames . 0)))
would cause display-buffer to always pop up a new frame which is probably not what
our user wants.
So far, we have only shown how users can customize the default behavior
of display-buffer. Let us now see how applications can change the course of
Chapter 28: Windows 643
The above example would allow the conclusion that users customize display-buffer-
alist for the sole purpose to overrule the action argument chosen by applications. Such a
conclusion would be incorrect. display-buffer-alist is the standard option for users to
direct the course of display of specific buffers in a preferred way regardless of whether the
display is also guided by an action argument.
We can, however, reasonably conclude that customizing display-buffer-alist dif-
fers from customizing display-buffer-base-action in two major aspects: it is stronger
because it overrides the action argument of display-buffer, and it allows to explicitly
specify the affected buffers. In fact, displaying other buffers is not affected in any way by a
customization for *foo*. For example,
(display-buffer (get-buffer-create "*bar*"))
continues being governed by the settings of display-buffer-base-action and
display-buffer-fallback-action only.
We could stop with our examples here but Lisp programs still have an ace up their sleeves
which they can use to overrule any customization of display-buffer-alist. It’s the vari-
able display-buffer-overriding-action which they can bind around display-buffer
calls as follows:
(let ((display-buffer-overriding-action
'((display-buffer-same-window))))
(display-buffer
(get-buffer-create "*foo*")
'((display-buffer-below-selected display-buffer-at-bottom))))
Evaluating this form will usually display *foo* in the selected window regardless of the
action argument and any user customizations. (Usually, an application will not bother
to also provide an action argument. Here it just serves to illustrate the fact that it gets
overridden.)
It might be illustrative to look at the list of action functions display-buffer would
have tried to display *foo* with the customizations we provided here. The list (including
comments explaining who added this and the subsequent elements) is:
(display-buffer-same-window ;; `display-buffer-overriding-action'
display-buffer-reuse-window ;; `display-buffer-alist'
display-buffer-pop-up-frame
display-buffer-below-selected ;; ACTION argument
display-buffer-at-bottom
display-buffer-reuse-window ;; `display-buffer-base-action'
display-buffer-pop-up-frame
display-buffer--maybe-same-window ;; `display-buffer-fallback-action'
display-buffer-reuse-window
display-buffer--maybe-pop-up-frame-or-window
display-buffer-in-previous-window
display-buffer-use-some-window
display-buffer-pop-up-frame)
Note that among the internal functions listed here, display-buffer--maybe-same-window
is effectively ignored while display-buffer--maybe-pop-up-frame-or-window actually
runs display-buffer-pop-up-window.
Chapter 28: Windows 645
partially restore the layout of a frame when removing a buffer from it later (see Section 28.16
[Quitting Windows], page 651).
Below we will give a number of guidelines to redeem the frustration mentioned above
and thus to avoid literally losing buffers in-between the windows of a frame.
(customize-set-variable
'display-buffer-alist
'(("\\*foo\\*"
(display-buffer-below-selected display-buffer-at-bottom)
(inhibit-same-window . t)
(window-height . fit-window-to-buffer))
("\\*bar\\*"
(display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . visible))))
Treat each other with respect
display-buffer-alist and display-buffer-base-action are user options—
Lisp programs must never set or rebind them. display-buffer-overriding-
action, on the other hand, is reserved for applications—who seldom use that
option and if they use it, then with utmost care.
Older implementations of display-buffer frequently caused users and applica-
tions to fight over the settings of user options like pop-up-frames and pop-up-
windows (see Section 28.13.4 [Choosing Window Options], page 638). This was
one major reason for redesigning display-buffer—to provide a clear frame-
work specifying what users and applications should be allowed to do.
Lisp programs must be prepared that user customizations may cause buffers
to get displayed in an unexpected way. They should never assume in their
subsequent behavior, that the buffer has been shown precisely the way they
asked for in the action argument of display-buffer.
Users should not pose too many and too severe restrictions on how arbitrary
buffers get displayed. Otherwise, they will risk to lose the characteristics of
showing a buffer for a certain purpose. Suppose a Lisp program has been
written to compare different versions of a buffer in two windows side-by-side.
If the customization of display-buffer-alist prescribes that any such buffer
should be always shown in or below the selected window, the program will have
a hard time to set up the desired window configuration via display-buffer.
To specify a preference for showing an arbitrary buffer, users should customize
display-buffer-base-action. An example of how users who prefer work-
ing with multiple frames would do that was given in the previous subsection.
display-buffer-alist should be reserved for displaying specific buffers in a
specific way.
Consider reusing a window that already shows the buffer
Generally, it’s always a good idea for users and Lisp programmers to be prepared
for the case that a window already shows the buffer in question and to reuse
that window. In the preceding subsection we have shown that failing to do
so properly may cause display-buffer to continuously pop up a new frame
although a frame showing that buffer existed already. In a few cases only, it
might be undesirable to reuse a window, for example, when a different portion
of the buffer should be shown in that window.
Hence, display-buffer-reuse-window is one action function that should be
used as often as possible, both in action arguments and customizations. An
Chapter 28: Windows 648
Functions supposed to remove a buffer from a window or a window from a frame can
behave specially when a window they operate on is dedicated. We will distinguish three
basic cases, namely where (1) the window is not the only window on its frame, (2) the
window is the only window on its frame but there are other frames on the same terminal
left, and (3) the window is the only window on the only frame on the same terminal.
In particular, delete-windows-on (see Section 28.7 [Deleting Windows], page 615) han-
dles case (2) by deleting the associated frame and case (3) by showing another buffer in
that frame’s only window. The function replace-buffer-in-windows (see Section 28.11
[Buffers and Windows], page 626) which is called when a buffer gets killed, deletes the
window in case (1) and behaves like delete-windows-on otherwise.
When bury-buffer (see Section 27.8 [Buffer List], page 591) operates on the selected
window (which shows the buffer that shall be buried), it handles case (2) by calling
frame-auto-hide-function (see Section 28.16 [Quitting Windows], page 651) to deal with
the selected frame. The other two cases are handled as with replace-buffer-in-windows.
window-dedicated-p &optional window [Function]
This function returns non-nil if window is dedicated to its buffer and nil otherwise.
More precisely, the return value is the value assigned by the last call of set-window-
dedicated-p for window, or nil if that function was never called with window as its
argument. The default for window is the selected window.
set-window-dedicated-p window flag [Function]
This function marks window as dedicated to its buffer if flag is non-nil, and non-
dedicated otherwise.
As a special case, if flag is t, window becomes strongly dedicated to its buffer.
set-window-buffer signals an error when the window it acts upon is strongly dedi-
cated to its buffer and does not already display the buffer it is asked to display. Other
functions do not treat t differently from any non-nil value.
nil This means to not deal with the buffer in any particular way. As a
consequence, if window is not deleted, invoking switch-to-prev-buffer
will usually show the buffer again.
append This means that if window is not deleted, its buffer is moved to the end of
window’s list of previous buffers, so it’s less likely that a future invocation
of switch-to-prev-buffer will switch to it. Also, it moves the buffer to
the end of the frame’s buffer list.
bury This means that if window is not deleted, its buffer is removed from
window’s list of previous buffers. Also, it moves the buffer to the end
of the frame’s buffer list. This value provides the most reliable remedy
to not have switch-to-prev-buffer switch to this buffer again without
killing the buffer.
kill This means to kill window’s buffer.
Typically, the display routines run by display-buffer will set the quit-restore
window parameter correctly. It’s also possible to set it manually, using the following
code for displaying buffer in window:
(display-buffer-record-window type window buffer)
The following option specifies how to deal with a frame containing just one window that
should be either quit, or whose buffer should be buried.
For a particular frame, the value specified here may be overridden by that frame’s
auto-hide-function frame parameter (see Section 29.4.3.6 [Frame Interaction Pa-
rameters], page 709).
By default, side windows cannot be split via split-window (see Section 28.6 [Splitting
Windows], page 613). Also, a side window is not reused or split by any buffer display action
(see Section 28.13.2 [Buffer Display Action Functions], page 632) unless it is explicitly
specified as target of that action. Note also that delete-other-windows cannot make a
side window the only window on its frame (see Section 28.7 [Deleting Windows], page 615).
Once set up, side windows also change the behavior of the commands switch-to-prev-
buffer and switch-to-next-buffer (see Section 28.14 [Window History], page 649). In
particular, these commands will refrain from showing, in a side window, buffers that have
not been displayed in that window before. They will also refrain from having a normal,
non-side window show a buffer that has been already displayed in a side window. A notable
exception to the latter rule occurs when an application, after displaying a buffer, resets that
buffer’s local variables.
When a frame has side windows, the following function returns the main window of that
frame.
If frame has no side windows, it returns frame’s root window. Otherwise, it returns
either an internal non-side window such that all other non-side windows on frame
descend from it, or the single live non-side window of frame. Note that the main
window of a frame cannot be deleted via delete-window.
The following command is handy to toggle the appearance of all side windows on a
specified frame.
If frame has at least one side window, this command saves the state of frame’s root
window in the frame’s window-state frame parameter and deletes all side windows
on frame afterwards.
If frame has no side windows, but does have a window-state parameter, this com-
mand uses that parameter’s value to restore the side windows on frame leaving frame’s
main window alone.
An error is signaled if frame has no side windows and no saved state is found for it.
___________________________________
| *Buffer List* |
|___________________________________|
| | | |
| * | | * |
| d | | T |
| i | | a |
| r | Main Window Area | g |
| e | | s |
| d | | * |
| * | | |
|_____|_______________________|_____|
| *help*/*grep*/ | *shell*/ |
| *Completions* | *compilation* |
|_________________|_________________|
| Echo Area |
|___________________________________|
The following example illustrates how window parameters (see Section 28.27 [Window
Parameters], page 678) can be used with display-buffer-in-side-window (see
Section 28.17.1 [Displaying Buffers in Side Windows], page 654) to set up code for
producing the frame layout sketched above.
(defvar parameters
'(window-parameters . ((no-other-window . t)
(no-delete-other-windows . t))))
(setq fit-window-to-buffer-horizontally t)
(setq window-resize-pixelwise t)
(setq
display-buffer-alist
`(("\\*Buffer List\\*" display-buffer-in-side-window
(side . top) (slot . 0) (window-height . fit-window-to-buffer)
(preserve-size . (nil . t)) ,parameters)
("\\*Tags List\\*" display-buffer-in-side-window
(side . right) (slot . 0) (window-width . fit-window-to-buffer)
(preserve-size . (t . nil)) ,parameters)
("\\*\\(?:help\\|grep\\|Completions\\)\\*"
display-buffer-in-side-window
(side . bottom) (slot . -1) (preserve-size . (nil . t))
,parameters)
("\\*\\(?:shell\\|compilation\\)\\*" display-buffer-in-side-window
(side . bottom) (slot . 1) (preserve-size . (nil . t))
,parameters)))
This specifies display-buffer-alist entries (see Section 28.13.1 [Choosing Window],
page 630) for buffers with fixed names. In particular, it asks for showing *Buffer List*
with adjustable height at the top of the frame and *Tags List* with adjustable width on
the frame’s right. It also asks for having the *help*, *grep* and *Completions* buffers
Chapter 28: Windows 658
share a window on the bottom left side of the frame and the *shell* and *compilation*
buffers appear in a window on the bottom right side of the frame.
Note that the option fit-window-to-buffer-horizontally must have a non-nil value
in order to allow horizontal adjustment of windows. Entries are also added that ask for
preserving the height of side windows at the top and bottom of the frame and the width
of side windows at the left or right of the frame. To assure that side windows retain their
respective sizes when maximizing the frame, the variable window-resize-pixelwise is set
to a non-nil value. See Section 28.4 [Resizing Windows], page 608.
The last form also makes sure that none of the created side windows are accessible via
C-x o by installing the no-other-window parameter for each of these windows. In addition,
it makes sure that side windows are not deleted via C-x 1 by installing the no-delete-
other-windows parameter for each of these windows.
Since dired buffers have no fixed names, we use a special function dired-default-
directory-on-left in order to display a lean directory buffer on the left side of the frame.
(defun dired-default-directory-on-left ()
"Display `default-directory' in side window on left, hiding details."
(interactive)
(let ((buffer (dired-noselect default-directory)))
(with-current-buffer buffer (dired-hide-details-mode t))
(display-buffer-in-side-window
buffer `((side . left) (slot . 0)
(window-width . fit-window-to-buffer)
(preserve-size . (t . nil)) ,parameters))))
Evaluating the preceding forms and typing, in any order, M-x list-buffers, C-h f, M-x
shell, M-x list-tags, and M-x dired-default-directory-on-left should now repro-
duce the frame layout sketched above.
They can also be used to permanently display information pertinent to a specific window
in bars on that window’s sides.
Atomic windows are implemented with the help of the reserved window-atom window
parameter (see Section 28.27 [Window Parameters], page 678) and an internal window (see
Section 28.1 [Basic Windows], page 598) called the root window of the atomic window. All
windows that are part of the same atomic window have this root window as their common
ancestor and are assigned a non-nil window-atom parameter.
The following function returns the root of the atomic window a specified window is part
of:
The most simple approach to make a new atomic window is to take an existing internal
window and apply the following function:
To create a new atomic window from an existing live window or to add a new window to
an existing atomic window, the following buffer display action function (see Section 28.13.2
[Buffer Display Action Functions], page 632) can be used:
window The value of such an element specifies an existing window the new window
shall be combined with. If it specifies an internal window, all children
of that window become part of the atomic window too. If no window is
specified, the new window becomes a sibling of the selected window. The
window-atom parameter of the existing window is set to main provided
that window is live and its window-atom parameter was not already set.
side The value of such an element denotes the side of the existing window
where the new window shall be located. Valid values are below, right,
above and left. The default is below. The window-atom parameter of
the new window is set to this value.
The return value is the new window, nil when creating that window failed.
Chapter 28: Windows 660
Note that the value of the window-atom parameter does not really matter as long as
it is non-nil. The values assigned by display-buffer-in-atom-window just allow for
easy retrieval of the original and the new window after that function has been applied.
Note also that the window-atom parameter is the only window parameter assigned by
display-buffer-in-atom-window. Further parameters have to be set by the application
explicitly via a window-parameters entry in alist.
Atomic windows automatically cease to exist when one of their constituents gets
deleted. To dissolve an atomic window manually, reset the window-atom parameter of its
constituents—the root of the atomic window and all its descendants.
The following code snippet, when applied to a single-window frame, first splits the
selected window and makes the selected and the new window constituents of an atomic
window with their parent as root. It then displays the buffer *Messages* in a new window
at the frame’s bottom and makes that new window part of the atomic window just created.
(let ((window (split-window-right)))
(window-make-atom (window-parent window))
(display-buffer-in-atom-window
(get-buffer-create "*Messages*")
`((window . ,(window-parent window)) (window-height . 5))))
At this moment typing C-x 2 in any window of that frame produces a new window at
the bottom of the frame. Typing C-x 3 instead will put the new window at the frame’s
right. In either case, typing now C-x 1 in any window of the atomic window will remove
the new window only. Typing C-x 0 in any window of the atomic window will make that
new window fill the frame.
Emacs displays the cursor, by default as a rectangular block, in each window at the
position of that window’s point. When the user switches to another buffer in a window,
Emacs moves that window’s cursor to where point is in that buffer. If the exact position of
point is hidden behind some display element, such as a display string or an image, Emacs
displays the cursor immediately before or after that display element.
Chapter 28: Windows 661
window-point-insertion-type [Variable]
This variable specifies the marker insertion type (see Section 31.5 [Marker Insertion
Types], page 759) of window-point. The default is nil, so window-point will stay
behind text inserted there.
position of the entire group. This condition holds when the buffer local variable
window-group-start-function is set to a function. In this case, window-group-
start calls the function with the single argument window, then returns its result.
(set-window-start
(selected-window)
(save-excursion
(goto-char 1)
(forward-line 1)
(point)))
⇒ 37
non-nil. The argument position defaults to the current position of point in window;
window defaults to the selected window. If position is t, that means to check either
the first visible position of the last screen line in window, or the end-of-buffer position,
whichever comes first.
This function considers only vertical scrolling. If position is out of view only because
window has been scrolled horizontally, pos-visible-in-window-p returns non-nil
anyway. See Section 28.23 [Horizontal Scrolling], page 669.
If position is visible, pos-visible-in-window-p returns t if partially is nil; if par-
tially is non-nil, and the character following position is fully visible, it returns a list
of the form (x y), where x and y are the pixel coordinates relative to the top left
corner of the window; otherwise it returns an extended list of the form (x y rtop
rbot rowh vpos), where rtop and rbot specify the number of off-window pixels at
the top and bottom of the row at position, rowh specifies the visible height of that
row, and vpos specifies the vertical position (zero-based row number) of that row.
Here is an example:
;; If point is off the screen now, recenter it now.
(or (pos-visible-in-window-p
(point) (selected-window))
(recenter 0))
other-window-scroll-buffer [Variable]
If this variable is non-nil, it tells scroll-other-window which buffer’s window to
scroll.
upward from the bottom of the window, so that −1 stands for the last usable line in
the window.
If count is nil (or a non-nil list), recenter puts the line containing point in the
middle of the window. If count is nil, this function may redraw the frame, according
to the value of recenter-redisplay.
When recenter is called interactively, count is the raw prefix argument. Thus, typing
C-u as the prefix sets the count to a non-nil list, while typing C-u 4 sets count to 4,
which positions the current line four lines from the top.
With an argument of zero, recenter positions the current line at the top of the win-
dow. The command recenter-top-bottom offers a more convenient way to achieve
this.
What fraction of a line the vertical scrolling covers, or how many lines, depends on what
the lines contain. A value of .5 could scroll a line whose height is very short off the screen,
while a value of 3.3 could scroll just part of the way through a tall line or an image.
auto-window-vscroll [Variable]
If this variable is non-nil, the line-move, scroll-up, and scroll-down functions
will automatically modify the vertical scroll position to scroll through display rows
that are taller than the height of the window, for example in the presence of large
images.
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.
The default value of auto-hscroll-mode is t; setting it to current-line activates
a variant of automatic horizontal scrolling whereby only the line showing the cursor is
horizontally scrolled to make point visible, the rest of the window is left either unscrolled,
or at the minimum scroll amount set by scroll-left and scroll-right, see below.
scroll-left &optional count set-minimum [Command]
This function scrolls the selected window count columns to the left (or to the right if
count is negative). The default for count is the window width, minus 2.
The return value is the total amount of leftward horizontal scrolling in effect after the
change—just like the value returned by window-hscroll (below).
Note that text in paragraphs whose base direction is right-to-left (see Section 39.26
[Bidirectional Display], page 1067) moves in the opposite direction: e.g., it moves to
the right when scroll-left is invoked with a positive value of count.
Once you scroll a window as far right as it can go, back to its normal position where
the total leftward scrolling is zero, attempts to scroll any farther right have no effect.
If set-minimum is non-nil, the new scroll amount becomes the lower bound for au-
tomatic scrolling; that is, automatic scrolling will not scroll a window to a column
less than the value returned by this function. Interactive calls pass non-nil for set-
minimum.
scroll-right &optional count set-minimum [Command]
This function scrolls the selected window count columns to the right (or to the left if
count is negative). The default for count is the window width, minus 2. Aside from
the direction of scrolling, this works just like scroll-left.
window-hscroll &optional window [Function]
This function returns the total leftward horizontal scrolling of window—the number
of columns by which the text in window is scrolled left past the left margin. (In right-
to-left paragraphs, the value is the total amount of the rightward scrolling instead.)
The default for window is the selected window.
The return value is never negative. It is zero when no horizontal scrolling has been
done in window (which is usually the case).
(window-hscroll)
⇒ 0
Chapter 28: Windows 671
(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)))))
Y coordinate of the topmost row, the X coordinate one column to the right of the
rightmost column, and the Y coordinate one row down from the bottommost row.
Note that these are the actual outer edges of the window, including any header line,
mode line, scroll bar, fringes, window divider and display margins. On a text terminal,
if the window has a neighbor on its right, its right edge includes the separator line
between the window and its neighbor.
If the optional argument body is nil, this means to return the edges corresponding
to the total size of window. body non-nil means to return the edges of window’s
body (aka text area). If body is non-nil, window must specify a live window.
If the optional argument absolute is nil, this means to return edges relative to the
native position of window’s frame. absolute non-nil means to return coordinates rel-
ative to the origin (0, 0) of window’s display. On non-graphical systems this argument
has no effect.
If the optional argument pixelwise is nil, this means to return the coordinates in
terms of the default character width and height of window’s frame (see Section 29.3.2
[Frame Font], page 694), rounded if necessary. pixelwise non-nil means to return the
coordinates in pixels. Note that the pixel specified by right and bottom is immediately
outside of these edges. If absolute is non-nil, pixelwise is implicitly non-nil too.
window-body-edges &optional window [Function]
This function returns the edges of window’s body (see Section 28.3 [Window
Sizes], page 603). Calling (window-body-edges window) is equivalent to calling
(window-edges window t), see above.
The following functions can be used to relate a set of frame-relative coordinates to a
window:
window-at x y &optional frame [Function]
This function returns the live window at the coordinates x and y given in default
character sizes (see Section 29.3.2 [Frame Font], page 694) relative to the native
position of frame (see Section 29.3 [Frame Geometry], page 688).
If there is no window at that position, the return value is nil. If frame is omitted or
nil, it defaults to the selected frame.
coordinates-in-window-p coordinates window [Function]
This function checks whether a window window occupies the frame relative coordi-
nates coordinates, and if so, which part of the window that is. window should be a
live window.
coordinates should be a cons cell of the form (x . y), where x and y are given in
default character sizes (see Section 29.3.2 [Frame Font], page 694) relative to the
native position of window’s frame (see Section 29.3 [Frame Geometry], page 688).
If there is no window at the specified position, the return value is nil . Otherwise,
the return value is one of the following:
(relx . rely)
The coordinates are inside window. The numbers relx and rely are the
equivalent window-relative coordinates for the specified position, counting
from 0 at the top left corner of the window.
Chapter 28: Windows 673
mode-line
The coordinates are in the mode line of window.
header-line
The coordinates are in the header line of window.
right-divider
The coordinates are in the divider separating window from a window on
the right.
bottom-divider
The coordinates are in the divider separating window from a window
beneath.
vertical-line
The coordinates are in the vertical line between window and its neighbor
to the right. This value occurs only if the window doesn’t have a scroll
bar; positions in a scroll bar are considered outside the window for these
purposes.
left-fringe
right-fringe
The coordinates are in the left or right fringe of the window.
left-margin
right-margin
The coordinates are in the left or right margin of the window.
nil The coordinates are not in any part of window.
The function coordinates-in-window-p does not require a frame as argument be-
cause it always uses the frame that window is on.
The following functions return window positions in pixels, rather than character units.
Though mostly useful on graphical displays, they can also be called on text terminals, where
the screen area of each text character is taken to be one pixel.
window-pixel-edges &optional window [Function]
This function returns a list of pixel coordinates for the edges of window. Calling
(window-pixel-edges window) is equivalent to calling (window-edges window nil
nil t), see above.
window-body-pixel-edges &optional window [Function]
This function returns the pixel edges of window’s body. Calling (window-body-
pixel-edges window) is equivalent to calling (window-edges window t nil t), see
above.
The following functions return window positions in pixels, relative to the origin of the
display screen rather than that of the frame:
window-absolute-pixel-edges &optional window [Function]
This function returns the pixel coordinates of window relative to an origin at (0,
0) of the display of window’s frame. Calling (window-absolute-pixel-edges) is
equivalent to calling (window-edges window nil t t), see above.
Chapter 28: Windows 674
The following function returns the screen coordinates of a buffer position visible in a
window:
The following function returns the largest rectangle that can be inscribed in a window
without covering text displayed in that window.
with the largest rectangle first. count can be also a cons cell whose car specifies the
number of rectangles to return and whose cdr, if non-nil, states that all rectangles
returned must be disjoint.
The optional arguments min-width and min-height, if non-nil, specify the minimum
width and height of any rectangle returned.
The optional argument positions, if non-nil, is a cons cell whose car specifies the
uppermost and whose cdr specifies the lowermost pixel position that must be covered
by any rectangle returned. These positions measure from the start of the text area
of window.
The optional argument left, if non-nil, means to return values suitable for buffers
displaying right to left text. In that case, any rectangle returned is assumed to start
at the left edge of window’s text area.
Note that this function has to retrieve the dimensions of each line of window’s glyph
matrix via window-lines-pixel-dimensions (see Section 39.10 [Size of Displayed
Text], page 992). Hence, this function may also return nil when the current glyph
matrix of window is not up-to-date.
Mouse auto-selection can be used to emulate a focus follows mouse policy for child frames
(see Section 29.14 [Child Frames], page 726) which usually are not tracked by the window
manager. This requires to set the value of focus-follows-mouse (see Section 29.10 [Input
Focus], page 720) to a non-nil value. If the value of focus-follows-mouse is auto-raise,
entering a child frame with the mouse will raise it automatically above all other child frames
of that frame’s parent frame.
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.
The objects returned by current-window-configuration die together with the Emacs
process. In order to store a window configuration on disk and read it back in another Emacs
session, you can use the functions described next. These functions are also useful to clone
the state of a frame into an arbitrary live window (set-window-configuration effectively
clones the windows of a frame into the root window of that very frame only).
The value returned by window-state-get can be used in the same session to make a
clone of a window in another window. It can be also written to disk and read back in another
session. In either case, use the following function to restore the state of the window.
Chapter 28: Windows 678
window-persistent-parameters [Variable]
This variable is an alist specifying which parameters get saved by current-window-
configuration and window-state-get, and subsequently restored by set-window-
configuration and window-state-put. See Section 28.26 [Window Configurations],
page 676.
The car of each entry of this alist is a symbol specifying the parameter. The cdr
should be one of the following:
nil This value means the parameter is saved neither by window-state-get
nor by current-window-configuration.
t This value specifies that the parameter is saved by current-window-
configuration and (provided its writable argument is nil) by
window-state-get.
writable This means that the parameter is saved unconditionally by both
current-window-configuration and window-state-get. This value
should not be used for parameters whose values do not have a read
syntax. Otherwise, invoking window-state-put in another session may
fail with an invalid-read-syntax error.
ignore-window-parameters [Variable]
If this variable is non-nil, some standard functions do not process window param-
eters. The functions currently affected by this are split-window, delete-window,
delete-other-windows, and other-window.
An application can bind this variable to a non-nil value around calls to these func-
tions. If it does so, the application is fully responsible for correctly assigning the
parameters of all involved windows when exiting that function.
The following parameters are currently used by the window management code:
delete-window
This parameter affects the execution of delete-window (see Section 28.7 [Delet-
ing Windows], page 615).
delete-other-windows
This parameter affects the execution of delete-other-windows (see
Section 28.7 [Deleting Windows], page 615).
no-delete-other-windows
This parameter marks the window as not deletable by delete-other-windows
(see Section 28.7 [Deleting Windows], page 615).
split-window
This parameter affects the execution of split-window (see Section 28.6 [Split-
ting Windows], page 613).
Chapter 28: Windows 680
other-window
This parameter affects the execution of other-window (see Section 28.10 [Cyclic
Window Ordering], page 624).
no-other-window
This parameter marks the window as not selectable by other-window (see
Section 28.10 [Cyclic Window Ordering], page 624).
clone-of This parameter specifies the window that this one has been cloned from. It
is installed by window-state-get (see Section 28.26 [Window Configurations],
page 676).
window-preserved-size
This parameter specifies a buffer, a direction where nil means vertical and t
horizontal, and a size in pixels. If this window displays the specified buffer and
its size in the indicated direction equals the size specified by this parameter, then
Emacs will try to preserve the size of this window in the indicated direction.
This parameter is installed and updated by the function window-preserve-
size (see Section 28.5 [Preserving Window Sizes], page 612).
quit-restore
This parameter is installed by the buffer display functions (see Section 28.13.1
[Choosing Window], page 630) and consulted by quit-restore-window (see
Section 28.16 [Quitting Windows], page 651). It is a list of four elements, see
the description of quit-restore-window in Section 28.16 [Quitting Windows],
page 651, for details.
window-side
window-slot
These parameters are used internally for implementing side windows (see
Section 28.17 [Side Windows], page 654).
window-atom
This parameter is used internally for implementing atomic windows, see
Section 28.18 [Atomic Windows], page 658.
mode-line-format
This parameter replaces the value of the buffer-local variable mode-line-
format (see Section 23.4.1 [Mode Line Basics], page 476) of this window’s
buffer whenever this window is displayed. The symbol none means to suppress
display of a mode line for this window. Display and contents of the mode line
on other windows showing this buffer are not affected.
header-line-format
This parameter replaces the value of the buffer-local variable header-line-
format (see Section 23.4.1 [Mode Line Basics], page 476) of this window’s buffer
whenever this window is displayed. The symbol none means to suppress display
of a header line for this window. Display and contents of the header line on
other windows showing this buffer are not affected.
min-margins
The value of this parameter is a cons cell whose car and cdr, if non-nil, specify
the minimum values (in columns) for the left and right margin of this window
Chapter 28: Windows 681
(see Section 39.16.5 [Display Margins], page 1033. When present, Emacs will
use these values instead of the actual margin widths for determining whether a
window can be split or shrunk horizontally.
Emacs never auto-adjusts the margins of any window after splitting or resizing
it. It is the sole responsibility of any application setting this parameter to adjust
the margins of this window as well as those of any new window that inherits
this window’s margins due to a split. Both window-configuration-change-
hook and window-size-change-functions (see Section 28.28 [Window Hooks],
page 681) should be employed for this purpose.
This parameter was introduced in Emacs version 25.1 to support applications
that use large margins to center buffer text within a window and should be
used, with due care, exclusively by those applications. It might be replaced by
an improved solution in future versions of Emacs.
window-scroll-functions [Variable]
This variable holds a list of functions that Emacs should call before redisplaying a
window with scrolling. Displaying a different buffer in the window also runs these
functions.
This variable is not a normal hook, because each function is called with two arguments:
the window, and its new display-start position. At the time of the call, the display-
start position of the window argument is already set to its new value, and the buffer
to be displayed in the window is already set as the current buffer.
These functions must take care when using window-end (see Section 28.20 [Window
Start and End], page 661); 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 once per redisplay, and once for each frame
on which size changes have occurred.
Each function receives the frame as its sole argument. To find out
whether a specific window has changed size, compare the return values of
window-pixel-width-before-size-change and window-pixel-width respectively
Chapter 28: Windows 682
window-configuration-change-hook [Variable]
A normal hook that is run every time the window configuration of a frame changes.
Window configuration changes include splitting and deleting windows, and the display
of a different buffer in a window.
The hook can be also used for tracking changes of window sizes. It is, however, not
run when the size of a frame changes or automatic resizing of a minibuffer window (see
Section 20.11 [Minibuffer Windows], page 364) changes the size of another window.
As a rule, adding a function to window-size-change-functions, see above, is the
recommended way for reliably tracking size changes of any window.
The buffer-local value of this hook is run once for each window on the affected frame,
with the relevant window selected and its buffer current. The global value of this
hook is run once for the modified frame, with that frame selected.
In addition, you can use jit-lock-register to register a Font Lock fontification func-
tion, which will be called whenever parts of a buffer are (re)fontified because a window was
scrolled or its size changed. See Section 23.6.4 [Other Font Lock Variables], page 493.
683
29 Frames
A frame is a screen object that contains one or more Emacs windows (see Chapter 28
[Windows], page 598). It is the kind of object 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. In Emacs Lisp, a frame object is a Lisp object that represents a
frame on the screen. See Section 2.4.4 [Frame Type], page 25.
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. See Section 28.6
[Splitting Windows], page 613.
A terminal is a display device capable of displaying one or more Emacs frames. In
Emacs Lisp, a terminal object is a Lisp object that represents a terminal. See Section 2.4.5
[Terminal Type], page 26.
There are two classes of terminals: text terminals and graphical terminals. Text termi-
nals are non-graphics-capable displays, including xterm and other terminal emulators. On
a text terminal, each Emacs frame occupies the terminal’s entire screen; although you can
create additional frames and switch between them, the terminal only shows one frame at a
time. Graphical terminals, on the other hand, are managed by graphical display systems
such as the X Window System, which allow Emacs to show multiple frames simultaneously
on the same display.
On GNU and Unix systems, you can create additional frames on any available terminal,
within a single Emacs session, regardless of whether Emacs was started on a text or graphical
terminal. Emacs can display on both graphical and text terminals simultaneously. This
comes in handy, for instance, when you connect to the same session from several remote
locations. See Section 29.2 [Multiple Terminals], page 685.
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:
t The frame is displayed on a text terminal.
x The frame is displayed on an X graphical terminal.
w32 The frame is displayed on a MS-Windows graphical terminal.
ns The frame is displayed on a GNUstep or Macintosh Cocoa graphical ter-
minal.
pc The frame is displayed on an MS-DOS terminal.
frame-terminal &optional frame [Function]
This function returns the terminal object that displays frame. If frame is nil or
unspecified, it defaults to the selected frame.
terminal-live-p object [Function]
This predicate returns a non-nil value if object is a terminal that is live (i.e., not
deleted), and nil otherwise. For live terminals, the return value indicates what kind
of frames are displayed on that terminal; the list of possible values is the same as for
framep above.
Chapter 29: Frames 684
frame-inherited-parameters [Variable]
This variable specifies the list of frame parameters that a newly created frame inherits
from the currently selected frame. For each parameter (a symbol) that is an element in
this list and has not been assigned earlier when processing make-frame, the function
sets the value of that parameter in the created frame to its value in the selected frame.
delete-terminal-functions [Variable]
An abnormal hook run by delete-terminal. Each function receives one argument,
the terminal argument passed to delete-terminal. Due to technical details, the
functions may be called either just before the terminal is deleted, or just afterwards.
A few Lisp variables are terminal-local; that is, they have a separate binding for each ter-
minal. The binding in effect at any time is the one for the terminal that the currently selected
frame belongs to. These variables include default-minibuffer-frame, defining-kbd-
macro, last-kbd-macro, and system-key-alist. They are always terminal-local, and can
never be buffer-local (see Section 12.11 [Buffer-Local Variables], page 185).
On GNU and Unix systems, each X display is a separate graphical terminal. When
Emacs is started from within the X window system, it uses the X display specified by the
DISPLAY environment variable, or by the ‘--display’ option (see Section “Initial Options”
in The GNU Emacs Manual). Emacs can connect to other X displays via the command
make-frame-on-display. Each X display has its own selected frame and its own minibuffer
windows; however, only one of those frames is the selected frame at any given moment (see
Section 29.10 [Input Focus], page 720). Emacs can even connect to other text terminals,
by interacting with the emacsclient program. See Section “Emacs Server” in The GNU
Emacs Manual.
A single X server can handle more than one display. Each X display has a three-
part name, ‘hostname:displaynumber.screennumber’. The first part, hostname, specifies
the name of the machine to which the display is physically connected. The second part,
displaynumber, is a zero-based number that identifies one or more monitors connected to
that machine that share a common keyboard and pointing device (mouse, tablet, etc.). The
third part, screennumber, identifies a zero-based screen number (a separate monitor) that
is part of a single monitor collection on that X server. When you use two or more screens
belonging to one server, Emacs knows by the similarity in their names that they share a
single keyboard.
Systems that don’t use the X window system, such as MS-Windows, don’t support the
notion of X displays, and have only one display on each host. The display name on these
systems doesn’t follow the above 3-part format; for example, the display name on MS-
Windows systems is a constant string ‘w32’, and exists for compatibility, so that you could
pass it to functions that expect a display name.
x-display-list [Function]
This function returns a list that indicates which X displays Emacs has a connection
to. The elements of the list are strings, and each one is a display name.
Chapter 29: Frames 687
On some multi-monitor setups, a single X display outputs to more than one physical mon-
itor. You can use the functions display-monitor-attributes-list and frame-monitor-
attributes to obtain information about such setups.
x, y, width, and height are integers. ‘name’ and ‘source’ may be absent.
A frame is dominated by a physical monitor when either the largest area of the frame
resides in that monitor, or (if the frame does not intersect any physical monitors)
that monitor is the closest to the frame. Every (non-tooltip) frame (whether visible
or not) in a graphical display is dominated by exactly one physical monitor at a time,
though the frame can span multiple (or no) physical monitors.
(display-monitor-attributes-list)
⇒
(((geometry 0 0 1920 1080) ;; Left-hand, primary monitor
(workarea 0 0 1920 1050) ;; A taskbar occupies some of the height
(mm-size 677 381)
(name . "DISPLAY1")
(frames #<frame emacs@host *Messages* 0x11578c0>
#<frame emacs@host *scratch* 0x114b838>))
((geometry 1920 0 1680 1050) ;; Right-hand monitor
(workarea 1920 0 1680 1050) ;; Whole screen can be used
(mm-size 593 370)
(name . "DISPLAY2")
(frames)))
In practice not all of the areas shown in the drawing will or may be present. The meaning
of these areas is described below.
Outer Frame
The outer frame is a rectangle comprising all areas shown in the drawing. The
edges of that rectangle are called the outer edges of the frame. Together, the
outer width and outer height of the frame specify the outer size of that rectangle.
Knowing the outer size of a frame is useful for fitting a frame into the working
area of its display (see Section 29.2 [Multiple Terminals], page 685) or for placing
two frames adjacent to each other on the screen. Usually, the outer size of
a frame is available only after the frame has been mapped (made visible, see
Section 29.11 [Visibility of Frames], page 723) at least once. For the initial frame
or a frame that has not been created yet, the outer size can be only estimated
or must be calculated from the window-system’s or window manager’s defaults.
One workaround is to obtain the differences of the outer and native (see below)
sizes of a mapped frame and use them for calculating the outer size of the new
frame.
The position of the upper left corner of the outer frame (indicated by ‘(0)’ in
the drawing above) is the outer position of the frame. The outer position of
a graphical frame is also referred to as “the position” of the frame because it
usually remains unchanged on its display whenever the frame is resized or its
layout is changed.
The outer position is specified by and can be set via the left and top frame
parameters (see Section 29.4.3.2 [Position Parameters], page 702). For a normal,
top-level frame these parameters usually represent its absolute position (see
below) with respect to its display’s origin. For a child frame (see Section 29.14
[Child Frames], page 726) these parameters represent its position relative to the
native position (see below) of its parent frame. For frames on text terminals
the values of these parameters are meaningless and always zero.
Chapter 29: Frames 690
External Border
The external border is part of the decorations supplied by the window manager.
It is typically used for resizing the frame with the mouse and is therefore not
shown on “fullboth” and maximized frames (see Section 29.4.3.3 [Size Param-
eters], page 705). Its width is determined by the window manager and cannot
be changed by Emacs’ functions.
External borders don’t exist on text terminal frames. For graphical frames, their
display can be suppressed by setting the override-redirect or undecorated
frame parameter (see Section 29.4.3.8 [Management Parameters], page 711).
Outer Border
The outer border is a separate border whose width can be specified with
the border-width frame parameter (see Section 29.4.3.4 [Layout Parameters],
page 707). In practice, either the external or the outer border of a frame
are displayed but never both at the same time. Usually, the outer border
is shown only for special frames that are not (fully) controlled by the win-
dow manager like tooltip frames (see Section 39.25 [Tooltips], page 1065),
child frames (see Section 29.14 [Child Frames], page 726) and undecorated
or override-redirect frames (see Section 29.4.3.8 [Management Parameters],
page 711).
Outer borders are never shown on text terminal frames and on frames generated
by GTK+ routines. On MS-Windows, the outer border is emulated with the
help of a one pixel wide external border. Non-toolkit builds on X allow to change
the color of the outer border by setting the border-color frame parameter (see
Section 29.4.3.4 [Layout Parameters], page 707).
Title Bar The title bar, a.k.a. caption bar, is also part of the window manager’s deco-
rations and typically displays the title of the frame (see Section 29.6 [Frame
Titles], page 717) as well as buttons for minimizing, maximizing and deleting
the frame. It can be also used for dragging the frame with the mouse. The title
bar is usually not displayed for fullboth (see Section 29.4.3.3 [Size Parameters],
page 705), tooltip (see Section 39.25 [Tooltips], page 1065) and child frames (see
Section 29.14 [Child Frames], page 726) and doesn’t exist for terminal frames.
Display of the title bar can be suppressed by setting the override-redirect
or the undecorated frame parameters (see Section 29.4.3.8 [Management Pa-
rameters], page 711).
Menu Bar The menu bar (see Section 22.17.5 [Menu Bar], page 446) can be either internal
(drawn by Emacs itself) or external (drawn by the toolkit). Most builds (GTK+,
Lucid, Motif and MS-Windows) rely on an external menu bar. NS also uses
an external menu bar which, however, is not part of the outer frame. Non-
toolkit builds can provide an internal menu bar. On text terminal frames, the
menu bar is part of the frame’s root window (see Section 28.2 [Windows and
Frames], page 599). As a rule, menu bars are never shown on child frames
(see Section 29.14 [Child Frames], page 726). Display of the menu bar can
be suppressed by setting the menu-bar-lines parameter (see Section 29.4.3.4
[Layout Parameters], page 707) to zero.
Chapter 29: Frames 691
Whether the menu bar is wrapped or truncated whenever its width becomes
too large to fit on its frame depends on the toolkit . Usually, only Motif and
MS-Windows builds can wrap the menu bar. When they (un-)wrap the menu
bar, they try to keep the outer height of the frame unchanged, so the native
height of the frame (see below) will change instead.
Tool Bar Like the menu bar, the tool bar (see Section 22.17.6 [Tool Bar], page 447) can
be either internal (drawn by Emacs itself) or external (drawn by a toolkit). The
GTK+ and NS builds have the tool bar drawn by the toolkit. The remaining
builds use internal tool bars. With GTK+ the tool bar can be located on either
side of the frame, immediately outside the internal border, see below. Tool
bars are usually not shown for child frames (see Section 29.14 [Child Frames],
page 726). Display of the tool bar can be suppressed by setting the tool-bar-
lines parameter (see Section 29.4.3.4 [Layout Parameters], page 707) to zero.
If the variable auto-resize-tool-bars is non-nil, Emacs wraps the internal
tool bar when its width becomes too large for its frame. If and when Emacs (un-
)wraps the internal tool bar, it by default keeps the outer height of the frame
unchanged, so the native height of the frame (see below) will change instead.
Emacs built with GTK+, on the other hand, never wraps the tool bar but may
automatically increase the outer width of a frame in order to accommodate an
overlong tool bar.
Native Frame
The native frame is a rectangle located entirely within the outer frame. It
excludes the areas occupied by an external or outer border, the title bar and
any external menu or tool bar. The edges of the native frame are called the
native edges of the frame. Together, the native width and native height of a
frame specify the native size of the frame.
The native size of a frame is the size Emacs passes to the window-system or
window manager when creating or resizing the frame from within Emacs. It
is also the size Emacs receives from the window-system or window manager
whenever these resize the frame’s window-system window, for example, after
maximizing the frame by clicking on the corresponding button in the title bar
or when dragging its external border with the mouse.
The position of the top left corner of the native frame specifies the native
position of the frame. (1)–(3) in the drawing above indicate that position for
the various builds:
(1) non-toolkit and terminal frames
(2) Lucid, Motif and MS-Windows frames
(3) GTK+ and NS frames
Accordingly, the native height of a frame may include the height of the tool
bar but not that of the menu bar (Lucid, Motif, MS-Windows) or those of the
menu bar and the tool bar (non-toolkit and text terminal frames).
The native position of a frame is the reference position for functions that set
or return the current position of the mouse (see Section 29.16 [Mouse Posi-
tion], page 730) and for functions dealing with the position of windows like
Chapter 29: Frames 692
tool-bar-size
A cons of the width and height of the tool bar of frame.
internal-border-width
The width of the internal border of frame.
The following function can be used to retrieve the edges of the outer, native and inner
frame.
frame-edges &optional frame type [Function]
This function returns the absolute edges of the outer, native or inner frame of frame.
frame must be a live frame and defaults to the selected one. The returned list has the
form (left top right bottom) where all values are in pixels relative to the origin of
frame’s display. For terminal frames the values returned for left and top are always
zero.
Optional argument type specifies the type of the edges to return: outer-edges means
to return the outer edges of frame, native-edges (or nil) means to return its native
edges and inner-edges means to return its inner edges.
By convention, the pixels of the display at the values returned for left and top are
considered to be inside (part of) frame. Hence, if left and top are both zero, the pixel
at the display’s origin is part of frame. The pixels at bottom and right, on the other
hand, are considered to lie immediately outside frame. This means that if you have,
for example, two side-by-side frames positioned such that the right outer edge of the
frame on the left equals the left outer edge of the frame on the right, the pixels at
that edge show a part of the frame on the right.
If the optional argument keep-size is nil, this keeps the number of frame lines and
columns fixed. (If non-nil, the option frame-inhibit-implied-resize described in
the next section will override this.) If keep-size is non-nil (or with a prefix argument),
it tries to keep the size of the display area of the current frame fixed by adjusting the
number of lines and columns.
If the optional argument frames is nil, this applies the font to the selected frame
only. If frames is non-nil, it should be a list of frames to act upon, or t meaning all
existing and all future graphical frames.
frame. The frame parameters left and top (see Section 29.4.3.2 [Position Param-
eters], page 702) allow to do that, but may still fail to provide good results for the
initial or a new frame.
This function has no effect on text terminal frames.
move-frame-functions [Variable]
This hook specifies the functions that are run when an Emacs frame is moved (assigned
a new position) by the window-system or window manager. The functions are run
with one argument, the frame that moved. For a child frame (see Section 29.14 [Child
Frames], page 726), the functions are run only when the position of the frame changes
in relation to that of its parent frame.
The functions following next return the pixel widths and heights of the native, outer
and inner frame and the text area (see Section 29.3.1 [Frame Layout], page 688) of a given
frame. For a text terminal, the results are in characters rather than pixels.
Chapter 29: Frames 697
On window systems that support it, Emacs tries by default to make the text size of a
frame measured in pixels a multiple of the frame’s character size. This, however, usually
means that a frame can be resized only in character size increments when dragging its
external borders. It also may break attempts to truly maximize the frame or making it
“fullheight” or “fullwidth” (see Section 29.4.3.3 [Size Parameters], page 705) leaving some
empty space below and/or on the right of the frame. The following option may help in that
case.
None of these three functions will make a frame smaller than needed to display all of its
windows together with their scroll bars, fringes, margins, dividers, mode and header lines.
This contrasts with requests by the window manager triggered, for example, by dragging the
external border of a frame with the mouse. Such requests are always honored by clipping, if
necessary, portions that cannot be displayed at the right, bottom corner of the frame. The
parameters min-width and min-height (see Section 29.4.3.3 [Size Parameters], page 705)
can be used to obtain a similar behavior when changing the frame size from within Emacs.
The abnormal hook window-size-change-functions (see Section 28.28 [Window
Hooks], page 681) tracks all changes of the inner size of a frame including those induced by
request of the window-system or window manager. To rule out false positives that might
occur when changing only the sizes of a frame’s windows without actually changing the
size of the inner frame, use the following function.
the size change. Note that wrapping a menu or tool bar usually does not resize the frame’s
outer size, hence this will alter the number of displayed lines.
Occasionally, such implied frame resizing may be unwanted, for example, when the frame
is maximized or made full-screen (where it’s turned off by default). In other cases you can
disable implied resizing with the following option:
If these parameters include (minibuffer . nil), that indicates that the initial frame
should have no minibuffer. In this case, Emacs creates a separate minibuffer-only frame as
well.
If you invoke Emacs with command-line options that specify frame appearance, those
options take effect by adding elements to either initial-frame-alist or default-frame-
alist. Options which affect just the initial frame, such as ‘--geometry’ and ‘--maximized’,
add to initial-frame-alist; the others add to default-frame-alist. see Section “Com-
mand Line Arguments for Emacs Invocation” in The GNU Emacs Manual.
Chapter 29: Frames 702
an integer A positive integer always relates the left edge of the frame to the left
edge of its display or parent frame. A negative integer relates the
right frame edge to the right edge of the display or parent frame.
(+ pos) This specifies the position of the left frame edge relative to the left
edge of its display or parent frame. The integer pos may be positive
or negative; a negative value specifies a position outside the screen
or parent frame or on a monitor other than the primary one (for
multi-monitor displays).
(- pos) This specifies the position of the right frame edge relative to the
right edge of the display or parent frame. The integer pos may be
positive or negative; a negative value specifies a position outside
the screen or parent frame or on a monitor other than the primary
one (for multi-monitor displays).
a floating-point value
A floating-point value in the range 0.0 to 1.0 specifies the left edge’s
offset via the left position ratio of the frame—the ratio of the left
edge of its outer frame to the width of the frame’s workarea (see
Section 29.2 [Multiple Terminals], page 685) or its parent’s native
frame (see Section 29.14 [Child Frames], page 726) minus the width
of the outer frame. Thus, a left position ratio of 0.0 flushes a frame
to the left, a ratio of 0.5 centers it and a ratio of 1.0 flushes it to
the right of its display or parent frame. Similarly, the top position
ratio of a frame is the ratio of the frame’s top position to the height
of its workarea or parent frame minus the height of the frame.
Emacs will try to keep the position ratios of a child frame un-
altered if that frame has a non-nil keep-ratio parameter (see
Section 29.4.3.6 [Frame Interaction Parameters], page 709) and its
parent frame is resized.
Since the outer size of a frame (see Section 29.3 [Frame Geometry],
page 688) is usually unavailable before a frame has been made vis-
ible, it is generally not advisable to use floating-point values when
creating decorated frames. Floating-point values are more suited
for ensuring that an (undecorated) child frame is positioned nicely
within the area of its parent frame.
Some window managers ignore program-specified positions. If you want to be
sure the position you specify is not ignored, specify a non-nil value for the
user-position parameter as in the following example:
(modify-frame-parameters
nil '((user-position . t) (left . (+ -4))))
In general, it is not a good idea to position a frame relative to the right or
bottom edge of its display. Positioning the initial or a new frame is either not
accurate (because the size of the outer frame is not yet fully known before the
frame has been made visible) or will cause additional flicker (if the frame has
to be repositioned after becoming visible).
Chapter 29: Frames 704
Note also, that positions specified relative to the right/bottom edge of a display,
workarea or parent frame as well as floating-point offsets are stored internally
as integer offsets relative to the left/top edge of the display, workarea or parent
frame edge. They are also returned as such by functions like frame-parameters
and restored as such by the desktop saving routines.
top The screen position of the top (or bottom) edge, in pixels, with respect to the
top (or bottom) edge of the display or parent frame. It works just like left,
except vertically instead of horizontally.
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 when the frame is iconified, if the
window manager supports this feature. If you specify a value for this parameter,
then you must also specify a value for icon-top and vice versa.
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 when the frame is iconified, if the
window manager supports this feature.
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.
z-group This parameter specifies a relative position of the frame’s window-system win-
dow in the stacking (Z-) order of the frame’s display.
If this is above, the frame’s window-system window is displayed above all other
window-system windows that do not have the above property set. If this is
nil, the frame’s window is displayed below all windows that have the above
property set and above all windows that have the below property set. If this
is below, the frame’s window is displayed below all windows that do not have
the below property set.
To position the frame above or below a specific other frame use the function
frame-restack (see Section 29.12 [Raising and Lowering], page 724).
Chapter 29: Frames 705
min-width
This parameter specifies the minimum native width (see Section 29.3 [Frame
Geometry], page 688) of the frame, in characters. Normally, the functions that
establish a frame’s initial width or resize a frame horizontally make sure that all
the frame’s windows, vertical scroll bars, fringes, margins and vertical dividers
can be displayed. This parameter, if non-nil allows to make a frame narrower
than that with the consequence that any components that do not fit will be
clipped by the window manager.
min-height
This parameter specifies the minimum native height (see Section 29.3 [Frame
Geometry], page 688) of the frame, in characters. Normally, the functions that
establish a frame’s initial size or resize a frame make sure that all the frame’s
windows, horizontal scroll bars and dividers, mode and header lines, the echo
area and the internal menu and tool bar can be displayed. This parameter, if
non-nil allows to make a frame smaller than that with the consequence that
any components that do not fit will be clipped by the window manager.
fullscreen
This parameter specifies whether to maximize the frame’s width, height or
both. Its value can be fullwidth, fullheight, fullboth, or maximized. A
fullwidth frame is as wide as possible, a fullheight frame is as tall as possible, and
a fullboth frame is both as wide and as tall as possible. A maximized frame
is like a “fullboth” frame, except that it usually keeps its title bar and the
buttons for resizing and closing the frame. Also, maximized frames typically
avoid hiding any task bar or panels displayed on the desktop. A “fullboth”
frame, on the other hand, usually omits the title bar and occupies the entire
available screen space.
Full-height and full-width frames are more similar to maximized frames in this
regard. However, these typically display an external border which might be
absent with maximized frames. Hence the heights of maximized and full-height
frames and the widths of maximized and full-width frames often differ by a few
pixels.
With some window managers you may have to customize the variable
frame-resize-pixelwise (see Section 29.3.4 [Frame Size], page 696) in
order to make a frame truly appear maximized or full-screen. Moreover,
some window managers might not support smooth transition between
the various full-screen or maximization states. Customizing the variable
x-frame-normalize-before-maximize can help to overcome that.
Full-screen on macOS hides both the tool-bar and the menu-bar, however both
will be displayed if the mouse pointer is moved to the top of the screen.
fullscreen-restore
This parameter specifies the desired fullscreen state of the frame after invoking
the toggle-frame-fullscreen command (see Section “Frame Commands” in
The GNU Emacs Manual) in the “fullboth” state. Normally this parameter is
installed automatically by that command when toggling the state to fullboth.
Chapter 29: Frames 707
If, however, you start Emacs in the “fullboth” state, you have to specify the
desired behavior in your initial file as, for example
(setq default-frame-alist
'((fullscreen . fullboth)
(fullscreen-restore . fullheight)))
This will give a new frame full height after typing in it F11 for the first time.
fit-frame-to-buffer-margins
This parameter allows to override the value of the option fit-frame-to-
buffer-margins when fitting this frame to the buffer of its root window with
fit-frame-to-buffer (see Section 28.4 [Resizing Windows], page 608).
fit-frame-to-buffer-sizes
This parameter allows to override the value of the option fit-frame-to-
buffer-sizes when fitting this frame to the buffer of its root window with
fit-frame-to-buffer (see Section 28.4 [Resizing Windows], page 608).
When you use frame-parameter to query the value of either of these two frame
parameters, the return value is always an integer. When using set-frame-
parameter, passing a nil value imposes an actual default value of 8 pixels.
right-divider-width
The width (thickness) reserved for the right divider (see Section 39.15 [Window
Dividers], page 1027) of any window on the frame, in pixels. A value of zero
means to not draw right dividers.
bottom-divider-width
The width (thickness) reserved for the bottom divider (see Section 39.15 [Win-
dow Dividers], page 1027) of any window on the frame, in pixels. A value of
zero means to not draw bottom dividers.
menu-bar-lines
The number of lines to allocate at the top of the frame for a menu bar (see
Section 22.17.5 [Menu Bar], page 446). The default is one if Menu Bar mode is
enabled and zero otherwise. See Section “Menu Bars” in The GNU Emacs Man-
ual. For an external menu bar (see Section 29.3.1 [Frame Layout], page 688),
this value remains unchanged even when the menu bar wraps to two or more
lines. In that case, the menu-bar-size value returned by frame-geometry (see
Section 29.3 [Frame Geometry], page 688) allows to derive whether the menu
bar actually occupies one or more lines.
tool-bar-lines
The number of lines to use for the tool bar (see Section 22.17.6 [Tool Bar],
page 447). The default is one if Tool Bar mode is enabled and zero otherwise.
See Section “Tool Bars” in The GNU Emacs Manual. This value may change
whenever the tool bar wraps (see Section 29.3.1 [Frame Layout], page 688).
tool-bar-position
The position of the tool bar when Emacs was built with GTK+. Its value can
be one of top, bottom left, right. The default is top.
line-spacing
Additional space to leave below each text line, in pixels (a positive integer).
See Section 39.11 [Line Height], page 995, for more information.
no-special-glyphs
If this is non-nil, it suppresses the display of any truncation and continuation
glyphs (see Section 39.3 [Truncation], page 968) for all buffers displayed by this
frame. This is useful to eliminate such glyphs when fitting a frame to its buffer
via fit-frame-to-buffer (see Section 28.4 [Resizing Windows], page 608).
This parameter takes effect when the frame is created. If specified as nil, Emacs
will try to set it to the minibuffer window of default-minibuffer-frame (see
Section 29.9 [Minibuffers and Frames], page 719). For an existing frame, this
parameter can be used exclusively to specify another minibuffer window. It is
not allowed to change it from a minibuffer window to t and vice-versa, or from
t to nil. If the parameter specifies a minibuffer window already, setting it to
nil has no effect.
buffer-predicate
The buffer-predicate function for this frame. The function other-buffer uses
this predicate (from the selected frame) to decide which buffers it should con-
sider, if the predicate is not nil. It calls the predicate with one argument, a
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.
minibuffer-exit
When this parameter is non-nil, Emacs will by default make this frame invisible
whenever the minibuffer (see Chapter 20 [Minibuffers], page 334) is exited.
Alternatively, it can specify the functions iconify-frame and delete-frame.
This parameter is useful to make a child frame disappear automatically (similar
to how Emacs deals with a window) when exiting the minibuffer.
keep-ratio
This parameter is currently meaningful for child frames (see Section 29.14 [Child
Frames], page 726) only. If it is non-nil, then Emacs will try to keep the frame’s
size (width and height) ratios (see Section 29.4.3.3 [Size Parameters], page 705)
as well as its left and right position ratios (see Section 29.4.3.2 [Position Pa-
rameters], page 702) unaltered whenever its parent frame is resized.
If the value of this parameter is nil, the frame’s position and size remain
unaltered when the parent frame is resized, so the position and size ratios may
change. If the value of this parameter is t, Emacs will try to preserve the
frame’s size and position ratios, hence the frame’s size and position relative to
its parent frame may change.
More individual control is possible by using a cons cell: In that case the frame’s
width ratio is preserved if the car of the cell is either t or width-only. The
height ratio is preserved if the car of the cell is either t or height-only. The
left position ratio is preserved if the cdr of the cell is either t or left-only.
The top position ratio is preserved if the cdr of the cell is either t or top-only.
top-visible
If this parameter is a number, the top edge of the frame never appears above
the top edge of its display or parent frame. Moreover, as many pixels of the
frame as specified by that number will remain visible when the frame is moved
against any of the remaining edges of its display or parent frame. Setting this
parameter is useful to guard against dragging a child frame with a non-nil
drag-with-header-line parameter completely out of the area of its parent
frame.
bottom-visible
If this parameter is a number, the bottom edge of the frame never appears
below the bottom edge of its display or parent frame. Moreover, as many pixels
of the frame as specified by that number will remain visible when the frame
is moved against any of the remaining edges of its display or parent frame.
Setting this parameter is useful to guard against dragging a child frame with
a non-nil drag-with-mode-line parameter completely out of the area of its
parent frame.
visibility
The state of visibility of the frame. There are three possibilities: nil for invisi-
ble, t for visible, and icon for iconified. See Section 29.11 [Visibility of Frames],
page 723.
auto-raise
If non-nil, Emacs automatically raises the frame when it is selected. Some
window managers do not allow this.
auto-lower
If non-nil, Emacs automatically lowers the frame when it is deselected. Some
window managers do not allow this.
icon-type
The type of icon to use for this frame. If the value is a string, that specifies a
file containing a bitmap to use; nil specifies no icon (in which case the window
manager decides what to show); any other non-nil value specifies the default
Emacs icon.
icon-name
The name to use in the icon for this frame, when and if the icon appears. If
this is nil, the frame’s title is used.
window-id
The ID number which the graphical display uses for this frame. Emacs assigns
this parameter when the frame is created; changing the parameter has no effect
on the actual ID number.
Chapter 29: Frames 712
outer-window-id
The ID number of the outermost window-system window in which the frame
exists. As with window-id, changing this parameter has no actual effect.
wait-for-wm
If non-nil, tell Xt to wait for the window manager to confirm geometry changes.
Some window managers, including versions of Fvwm2 and KDE, fail to confirm,
so Xt hangs. Set this to nil to prevent hanging with those window managers.
sticky If non-nil, the frame is visible on all virtual desktops on systems with virtual
desktops.
inhibit-double-buffering
If non-nil, the frame is drawn to the screen without double buffering. Emacs
normally attempts to use double buffering, where available, to reduce flicker.
Set this property if you experience display bugs or pine for that retro, flicker-y
feeling.
skip-taskbar
If non-nil, this tells the window manager to remove the frame’s icon from the
taskbar associated with the frame’s display and inhibit switching to the frame’s
window via the combination Alt-TAB. On MS-Windows, iconifying such a frame
will "roll in" its window-system window at the bottom of the desktop. Some
window managers may not honor this parameter.
no-focus-on-map
If non-nil, this means that the frame does not want to receive input focus when
it is mapped (see Section 29.11 [Visibility of Frames], page 723). Some window
managers may not honor this parameter.
no-accept-focus
If non-nil, this means that the frame does not want to receive input
focus via explicit mouse clicks or when moving the mouse into it either
via focus-follows-mouse (see Section 29.10 [Input Focus], page 720) or
mouse-autoselect-window (see Section 28.25 [Mouse Window Auto-selection],
page 675). This may have the unwanted side-effect that a user cannot scroll a
non-selected frame with the mouse. Some window managers may not honor
this parameter.
undecorated
If non-nil, this frame’s window-system window is drawn without decorations,
like the title, minimize/maximize boxes and external borders. This usually
means that the window cannot be dragged, resized, iconified, maximized or
deleted with the mouse. If nil, the frame’s window is usually drawn with all
the elements listed above unless their display has been suspended via window
manager settings.
Under X, Emacs uses the Motif window manager hints to turn off decorations.
Some window managers may not honor these hints.
NS builds consider the tool bar to be a decoration, and therefore hide it on an
undecorated frame.
Chapter 29: Frames 713
override-redirect
If non-nil, this means that this is an override redirect frame—a frame not
handled by window managers under X. Override redirect frames have no window
manager decorations, can be positioned and resized only via Emacs’ positioning
and resizing functions and are usually drawn on top of all other frames. Setting
this parameter has no effect on MS-Windows.
ns-appearance
Only available on macOS, if set to dark draw this frame’s window-system win-
dow using the “vibrant dark” theme, otherwise use the system default. The
“vibrant dark” theme can be used to set the toolbar and scrollbars to a dark
appearance when using an Emacs theme with a dark background.
ns-transparent-titlebar
Only available on macOS, if non-nil, set the titlebar and toolbar to be trans-
parent. This effectively sets the background color of both to match the Emacs
background color.
Usual PC monitors have a screen gamma of 2.2, so color values in Emacs, and in
X windows generally, are calibrated to display properly on a monitor with that
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.
alpha This parameter specifies the opacity of the frame, on graphical displays that
support variable opacity. It should be an integer between 0 and 100, where 0
means completely transparent and 100 means completely opaque. It can also
have a nil value, which tells Emacs not to set the frame opacity (leaving it to
the window manager).
To prevent the frame from disappearing completely from view, the variable
frame-alpha-lower-limit defines a lower opacity limit. If the value of the
frame parameter is less than the value of this variable, Emacs uses the latter.
By default, frame-alpha-lower-limit is 20.
The alpha frame parameter can also be a cons cell (active . inactive), where
active is the opacity of the frame when it is selected, and inactive is the opacity
when it is not selected.
Some window systems do not support the alpha parameter for child frames
(see Section 29.14 [Child Frames], page 726).
The following frame parameters are semi-obsolete in that they are automatically equiv-
alent 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, ei-
ther a valid font name for your system or the name of an Emacs fontset (see
Section 39.12.11 [Fontsets], page 1013). 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.
Chapter 29: Frames 716
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.
29.4.4 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. The value possibilities for the position parame-
ters are: an integer, a list (+ pos), or a list (- pos); as previously described (see
Section 29.4.3.2 [Position Parameters], page 702).
Here is an example:
(x-parse-geometry "35x70+0-0")
⇒ ((height . 70) (width . 35)
(top - 0) (left . 0))
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.11
[Visibility of Frames], page 723. Frames on text terminals always count as visible,
even though only the selected one is actually displayed.
See also next-window and previous-window, in Section 28.10 [Cyclic Window Ordering],
page 624.
When you create the frame, you can explicitly specify its minibuffer window (in some
other frame) with the minibuffer frame parameter (see Section 29.4.3.5 [Buffer Parame-
ters], page 708). If you don’t, then the minibuffer is found in the frame which is the value
of the variable default-minibuffer-frame. Its value should be a frame that does have a
minibuffer.
If you use a minibuffer-only frame, you might want that frame to raise when you enter
the minibuffer. If so, set the variable minibuffer-auto-raise to t. See Section 29.12
[Raising and Lowering], page 724.
default-minibuffer-frame [Variable]
This variable specifies the frame to use for the minibuffer window, by default. It does
not affect existing frames. It is always local to the current terminal and cannot be
buffer-local. See Section 29.2 [Multiple Terminals], page 685.
same meaning as for select-frame (see below). The return value of this function is
not significant.
Ideally, the function described next should focus a frame without also raising it above
other frames. Unfortunately, many window-systems or window managers may refuse to
comply.
x-focus-frame frame &optional noactivate [Function]
This function gives frame the focus of the X server without necessarily raising it.
frame nil means use the selected frame. Under X, the optional argument noactivate,
if non-nil, means to avoid making frame’s window-system window the “active” win-
dow which should insist a bit more on avoiding to raise frame above other frames.
On MS-Windows the noactivate argument has no effect. However, if frame is a child
frame (see Section 29.14 [Child Frames], page 726), this function usually focuses frame
without raising it above other child frames.
If there is no window system support, this function does nothing.
select-frame frame &optional norecord [Command]
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, and its terminal becomes the se-
lected terminal. This function then calls select-window as a subroutine, passing
the window selected within frame as its first argument and norecord as its second
argument (hence, if norecord is non-nil, this avoids changing the order of recently
selected windows and the buffer list). See Section 28.9 [Selecting Windows], page 622.
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.7.9 [Focus Events], page 388.
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.
Chapter 29: Frames 722
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.
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.
focus-in-hook [Variable]
This is a normal hook run when an Emacs frame gains input focus. The frame gaining
focus is selected when this hook is run.
focus-out-hook [Variable]
This is a normal hook run when an Emacs frame has lost input focus and no other
Emacs frame has gained input focus instead.
Note that this option does not distinguish “sloppy” focus (where the frame that
previously had focus retains focus as long as the mouse pointer does not move into
another window manager window) from “strict” focus (where a frame immediately
loses focus when it’s left by the mouse pointer). Neither does it recognize whether your
window manager supports delayed focusing or auto-raising where you can explicitly
specify the time until a new frame gets focus or is auto-raised.
You can supply a “focus follows mouse” policy for individual Emacs windows by cus-
tomizing the variable mouse-autoselect-window (see Section 28.25 [Mouse Window
Auto-selection], page 675).
Unless force is non-nil, this function refuses to make frame invisible if all other frames
are invisible.
The visibility status of a frame is also available as a frame parameter. You can read or
change it as such. See Section 29.4.3.8 [Management Parameters], page 711. The user can
also 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.7.10 [Misc Events], page 388.
x-double-buffered-p &optional frame [Function]
This function returns non-nil if frame is currently being rendered with double buffer-
ing. frame defaults to the selected frame.
second step reinserts frame1’s window into the display below (above if above is true)
that of frame2. Hence the position of frame2 in its display’s Z (stacking) order relative
to all other frames excluding frame1 remains unaltered.
Some window managers may refuse to restack windows.
Note that the effect of restacking will only hold as long as neither of the involved frames
is iconified or made invisible. You can use the z-group (see Section 29.4.3.2 [Position
Parameters], page 702) frame parameter to add a frame to a group of frames permanently
shown above or below other frames. As long as a frame belongs to one of these groups,
restacking it will only affect its relative stacking position within that group. The effect of
restacking frames belonging to different z-groups is undefined. You can list frames in their
current stacking order with the function frame-list-z-order (see Section 29.8 [Finding
All Frames], page 718).
On window systems, you can also enable auto-raising (on frame selection) or auto-
lowering (on frame deselection) using frame parameters. See Section 29.4.3.8 [Management
Parameters], page 711.
The concept of raising and lowering frames also applies to text terminal frames. On each
text terminal, only the top frame is displayed at any one time.
current-frame-configuration [Function]
This function returns a frame configuration list that describes the current arrangement
of frames and their contents.
its parent window—the desktop’s root window. When a parent frame is iconified or made
invisible (see Section 29.11 [Visibility of Frames], page 723), its child frames are made
invisible. When a parent frame is deiconified or made visible, its child frames are made
visible. When a parent frame is about to be deleted (see Section 29.7 [Deleting Frames],
page 718), its child frames are recursively deleted before it.
Whether a child frame can have a menu or tool bar is window-system or window manager
dependent. Most window-systems explicitly disallow menus bars for child frames. It seems
advisable to disable both, menu and tool bars, via the frame’s initial parameters settings.
Usually, child frames do not exhibit window manager decorations like a title bar or
external borders (see Section 29.3 [Frame Geometry], page 688). When the child frame
does not show a menu or tool bar, any other of the frame’s borders (see Section 29.4.3.4
[Layout Parameters], page 707) can be used instead of the external borders.
In particular, under X (but not when building with GTK+), the frame’s outer border
can be used. On MS-Windows, specifying a non-zero outer border width will show a one-
pixel wide external border. Under all window-systems, the internal border can be used. In
either case, it’s advisable to disable a child frame’s window manager decorations with the
undecorated frame parameter (see Section 29.4.3.8 [Management Parameters], page 711).
To resize or move an undecorated child frame with the mouse, special frame parameters
(see Section 29.4.3.7 [Mouse Dragging Parameters], page 710) have to be used. The internal
border of a child frame, if present, can be used to resize the frame with the mouse, pro-
vided that frame has a non-nil drag-internal-border parameter. If set, the snap-width
parameter indicates the number of pixels where the frame snaps at the respective edge or
corner of its parent frame.
There are two ways to drag an entire child frame with the mouse: The drag-with-
mode-line parameter, if non-nil, allows to drag a frame without minibuffer window (see
Section 20.11 [Minibuffer Windows], page 364) via the mode line area of its bottommost
window. The drag-with-header-line parameter, if non-nil, allows to drag the frame via
the header line area of its topmost window.
In order to give a child frame a draggable header or mode line, the window parame-
ters mode-line-format and header-line-format are handy (see Section 28.27 [Window
Parameters], page 678). These allow to remove an unwanted mode line (when drag-with-
header-line is chosen) and to remove mouse-sensitive areas which might interfere with
frame dragging.
To avoid that dragging moves a frame completely out of its parent’s native frame, some-
thing which might happen when the mouse cursor overshoots and makes the frame difficult
to retrieve once the mouse button has been released, it is advisable to set the frame’s
top-visible or bottom-visible parameter correspondingly.
The top-visible parameter specifies the number of pixels at the top of the frame
that always remain visible within the parent’s native frame during dragging and should be
set when specifying a non-nil drag-with-header-line parameter. The bottom-visible
parameter specifies the number of pixels at the bottom of the frame that always remain
visible within the parent’s native frame during dragging and should be preferred when
specifying a non-nil drag-with-mode-line parameter.
When a child frame is used for displaying a buffer via display-buffer-in-child-frame
(see Section 28.13.2 [Buffer Display Action Functions], page 632), the frame’s auto-hide-
Chapter 29: Frames 728
function parameter (see Section 29.4.3.6 [Frame Interaction Parameters], page 709) can be
set to a function, in order to appropriately deal with the frame when the window displaying
the buffer shall be quit.
When a child frame is used during minibuffer interaction, for example, to display com-
pletions in a separate window, the minibuffer-exit parameter (see Section 29.4.3.6 [Frame
Interaction Parameters], page 709) is useful in order to deal with the frame when the mini-
buffer is exited.
The behavior of child frames deviates from that of top-level frames in a number of other
ways as well. Here we sketch a few of them:
• The semantics of maximizing and iconifying child frames is highly window-system de-
pendent. As a rule, applications should never invoke these operations on child frames.
By default, invoking iconify-frame on a child frame will try to iconify the top-level
frame corresponding to that child frame instead. To obtain a different behavior, users
may customize the option iconify-child-frame described below.
• Raising, lowering and restacking child frames (see Section 29.12 [Raising and Lower-
ing], page 724) or changing the z-group (see Section 29.4.3.2 [Position Parameters],
page 702) of a child frame changes only the stacking order of child frames with the
same parent.
• Many window-systems are not able to change the opacity (see Section 29.4.3.10 [Font
and Color Parameters], page 714) of child frames.
• Transferring focus from a child frame to an ancestor that is not its parent by clicking
with the mouse in a visible part of that ancestor’s window may fail with some window-
systems. You may have to click into the direct parent’s window-system window first.
• Window managers might not bother to extend their focus follows mouse policy to
child frames. Customizing mouse-autoselect-window can help in this regard (see
Section 28.25 [Mouse Window Auto-selection], page 675).
• Dropping (see Section 29.21 [Drag and Drop], page 734) on child frames is not guar-
anteed to work on all window-systems. Some will drop the object on the parent frame
or on some ancestor instead.
The following two functions can be useful when working with child and parent frames:
frame-parent &optional frame [Function]
This function returns the parent frame of frame. The parent frame of frame is the
Emacs frame whose window-system window is the parent window of frame’s window-
system window. If such a frame exists, frame is considered a child frame of that
frame.
This function returns nil if frame has no parent frame.
frame-ancestor-p ancestor descendant [Function]
This functions returns non-nil if ancestor is an ancestor of descendant. ancestor
is an ancestor of descendant when it is either descendant’s parent frame or it is an
ancestor of descendant’s parent frame. Both, ancestor and descendant must specify
live frames.
Note also the function window-largest-empty-rectangle (see Section 28.24 [Coordi-
nates and Windows], page 671) which can be used to inscribe a child frame in the largest
Chapter 29: Frames 729
empty area of an existing window. This can be useful to avoid that a child frame obscures
any text shown in that window.
Customizing the following option can be useful to tweak the behavior of iconify-frame
for child frames.
iconify-child-frame [User Option]
This option tells Emacs how to proceed when it is asked to iconify a child frame.
If it is nil, iconify-frame will do nothing when invoked on a child frame. If it is
iconify-top-level, Emacs will try to iconify the top-level frame that is the ancestor
of this child frame instead. If it is make-invisible, Emacs will try to make this child
frame invisible instead of iconifying it.
Any other value means to try iconifying the child frame. Since such an attempt may
not be honored by all window managers and can even lead to making the child frame
unresponsive to user actions, the default is to iconify the top level frame instead.
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 (possibly rounded) position
in multiples of the default character size of frame (see Section 29.3.2 [Frame Font],
page 694) relative to the native position of frame (see Section 29.3 [Frame Geometry],
page 688).
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.
On a graphical terminal the following two functions allow the absolute position of the
mouse cursor to be retrieved and set.
mouse-absolute-pixel-position [Function]
This function returns a cons cell (x . y) of the coordinates of the mouse cursor
position in pixels, relative to a position (0, 0) of the selected frame’s display.
set-mouse-absolute-pixel-position x y [Function]
This function moves the mouse cursor to the position (x, y). The coordinates x and
y are interpreted in pixels relative to a position (0, 0) of the selected frame’s display.
The following function can tell whether the mouse cursor is currently visible on a frame:
Chapter 29: Frames 731
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 446.
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.
When using X, 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.4.3.10 [Font and Color Parameters], page 714.
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.
When Emacs runs on MS-Windows, it does not implement X selections in general, but it
does support the clipboard. gui-get-selection and gui-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. The supported data type is STRING.
For backward compatibility, there are obsolete aliases x-get-selection and x-set-
selection, which were the names of gui-get-selection and gui-set-selection before
Emacs 25.1.
When an URL is dropped on Emacs it may be a file, but it may also be another URL
type (ftp, http, etc.). Emacs first checks dnd-protocol-alist to determine what to do
with the URL. If there is no match there and if browse-url-browser-function is an alist,
Emacs looks for a match there. If no match is found the text for the URL is inserted. If
you want to alter Emacs behavior, you can customize these variables.
The optional argument rgb, if specified, is an rgb value, a list of three numbers that
specify what the color actually looks like. If you do not specify rgb, then this color
cannot be used by tty-color-approximate to approximate other colors, because
Emacs will not know what it looks like.
tty-color-clear &optional frame [Function]
This function clears the table of defined colors for a text terminal.
tty-color-alist &optional frame [Function]
This function returns an alist recording the known colors supported by a text terminal.
Each element has the form (name number . rgb) or (name number). Here, name is
the color name, number is the number used to specify it to the terminal. If present,
rgb is a list of three color values (for red, green, and blue) that says what the color
actually looks like.
tty-color-approximate rgb &optional frame [Function]
This function finds the closest color, among the known colors supported for display,
to that described by the rgb value rgb (a list of color values). The return value is an
element of tty-color-alist.
tty-color-translate color &optional frame [Function]
This function finds the closest color to color among the known colors supported for
display and returns its index (an integer). If the name color is not defined, the value
is nil.
29.24 X Resources
This section describes some of the functions and variables for querying and using X re-
sources, or their equivalent on your operating system. See Section “X Resources” in The
GNU Emacs Manual, for more information about 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 other application
names 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.
Chapter 29: Frames 738
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"
inhibit-x-resources [Variable]
If this variable is non-nil, Emacs does not look up X resources, and X resources do
not have any effect when creating new frames.
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 756.
See also the field feature (see Section 32.19.9 [Fields], page 819), 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 753), 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.19 [Window Point], page 660, 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 753.)
Chapter 30: Positions 743
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 753.)
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 742.
pos is at the beginning of a word, and the function should return the position after
the last character of the word; otherwise, pos is at the last character of a word, and
the function should return the position of that word’s first character.
The division of the buffer into text lines is not affected by the width of the window, by line
continuation in display, or by how tabs and control characters are displayed.
Also see the functions bolp and eolp in Section 32.1 [Near Point], page 765. These
functions do not move point, but test whether it is already at the beginning or end of a
line.
page 669), the column on which point will end is in addition to the number of columns
by which the text is scrolled.
The return value is the number of screen lines over which point was moved. The value
may be less in absolute value than count if the beginning or end of the buffer was
reached.
The window window is used for obtaining parameters such as the width, the horizontal
scrolling, and the display table. But vertical-motion always operates on the current
buffer, even if window currently displays some other buffer.
The optional argument cur-col specifies the current column when the function is
called. This is the window-relative horizontal coordinate of point, measured in units
of font width of the frame’s default face. Providing it speeds up the function, especially
in very long lines, because the function doesn’t have to go back in the buffer in order
to determine the current column. Note that cur-col is also counted from the visual
start of the line.
(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 365.
(forward-sexp 3)
⇒ nil
30.3 Excursions
It is often useful to move point temporarily within a localized portion of the program. This
is called an excursion, and it is done with the save-excursion special form. This construct
remembers the initial identity of the current buffer, and its value of point, and restores
them after the excursion completes. It is the standard way to move point within one part
of a program and avoid affecting the rest of the program, and is used thousands of times in
the Lisp sources of Emacs.
If you only need to save and restore the identity of the current buffer, use save-current-
buffer or with-current-buffer instead (see Section 27.2 [Current Buffer], page 581). If
you need to save or restore window configurations, see the forms described in Section 28.26
[Window Configurations], page 676, and in Section 29.13 [Frame Configurations], page 725.
Chapter 30: Positions 753
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 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. Note that narrowing does not alter actual buffer positions (see Section 30.1 [Point],
page 742); it only determines which positions are considered the accessible portion of the
buffer. Most functions refuse to operate on text that is outside the accessible portion.
Commands for saving buffers are unaffected by narrowing; they save the entire buffer
regardless of any narrowing.
Chapter 30: Positions 754
If you need to display in a single buffer several very different types of text, consider using
an alternative facility described in Section 27.12 [Swapping Text], page 596.
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)))
buffer-narrowed-p [Function]
This function returns non-nil if the buffer is narrowed, and nil otherwise.
(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 742. 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 753.
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 753.
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 24080 in markers.texi>
(copy-marker 90000)
⇒ #<marker at 24080 in markers.texi>
An error is signaled if marker is neither a marker nor an integer.
Chapter 31: Markers 759
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
Once the mark exists in a buffer, it normally never ceases to exist. However, it may be-
come inactive, if Transient Mark mode is enabled. The buffer-local variable mark-active, if
non-nil, means that the mark is active. A command can call the function deactivate-mark
to deactivate the mark directly, or it can request deactivation of the mark upon return to
the editor command loop by setting the variable deactivate-mark to a non-nil value.
If Transient Mark mode is enabled, certain editing commands that normally apply to
text near point, apply instead to the region when the mark is active. This is the main
motivation for using Transient Mark mode. (Another is that this enables highlighting of
the region when the mark is active. See Chapter 39 [Display], page 967.)
In addition to the mark, each buffer has a mark ring which is a list of markers contain-
ing previous values of the mark. When editing commands change the mark, they should
normally save the old value of the mark on the mark ring. The variable mark-ring-max
specifies the maximum number of entries in the mark ring; once the list becomes this long,
adding a new element deletes the last element.
There is also a separate global mark ring, but that is used only in a few particular
user-level commands, and is not relevant to Lisp programming. So we do not describe it
here.
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>
(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!
Novice Emacs Lisp programmers often try to use the mark for the wrong purposes.
The mark saves a location for the user’s convenience. An editing command should
not alter the mark unless altering the mark is part of the user-level functionality of
the command. (And, in that case, this effect should be documented.) To remember a
location for internal use in the Lisp program, store it in a Lisp variable. For example:
(let ((beg (point)))
(forward-line 1)
(delete-region beg (point))).
push-mark &optional position nomsg activate [Function]
This function sets the current buffer’s mark to position, and pushes a copy of the
previous mark onto mark-ring. If position is nil, then the value of point is used.
The function push-mark normally does not activate the mark. To do that, specify t
for the argument activate.
A ‘Mark set’ message is displayed unless nomsg is non-nil.
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.
transient-mark-mode [User Option]
This variable, if non-nil, enables Transient Mark mode. In Transient Mark mode,
every buffer-modifying primitive sets deactivate-mark. As a consequence, most
commands that modify the buffer also deactivate the mark.
When Transient Mark mode is enabled and the mark is active, many commands that
normally apply to the text near point instead apply to the region. Such commands
should use the function use-region-p to test whether they should operate on the
region. See Section 31.8 [The Region], page 764.
Lisp programs can set transient-mark-mode to non-nil, non-t values to enable
Transient Mark mode temporarily. If the value is lambda, Transient Mark mode is
automatically turned off after any action, such as buffer modification, that would nor-
mally deactivate the mark. If the value is (only . oldval), then transient-mark-
mode is set to the value oldval after any subsequent command that moves point and
is not shift-translated (see Section 21.8.1 [Key Sequence Input], page 397), or after
any other action that would normally deactivate the mark.
mark-even-if-inactive [User Option]
If this is non-nil, Lisp programs and the Emacs user can use the mark even when it is
inactive. This option affects the behavior of Transient Mark mode. When the option
is non-nil, deactivation of the mark turns off region highlighting, but commands that
use the mark behave as if the mark were still active.
deactivate-mark [Variable]
If an editor command sets this variable non-nil, then the editor command loop
deactivates the mark after the command returns (if Transient Mark mode is enabled).
All the primitives that change the buffer set deactivate-mark, to deactivate the mark
when the command is finished. Setting this variable makes it buffer-local.
Chapter 31: Markers 763
To write Lisp code that modifies the buffer without causing deactivation of the mark
at the end of the command, bind deactivate-mark to nil around the code that does
the modification. For example:
(let (deactivate-mark)
(insert " "))
mark-active [Variable]
The mark is active when this variable is non-nil. This variable is always buffer-local
in each buffer. Do not use the value of this variable to decide whether a command
that normally operates on text near point should operate on the region instead. Use
the function use-region-p for that (see Section 31.8 [The Region], page 764).
activate-mark-hook [Variable]
deactivate-mark-hook [Variable]
These normal hooks are run, respectively, when the mark becomes active and when
it becomes inactive. The hook activate-mark-hook is also run at the end of the
command loop if the mark is active and it is possible that the region may have
changed.
handle-shift-selection [Function]
This function implements the shift-selection behavior of point-motion commands. See
Section “Shift Selection” in The GNU Emacs Manual. It is called automatically by the
Emacs command loop whenever a command with a ‘^’ character in its interactive
spec is invoked, before the command itself is executed (see Section 21.2.2 [Interactive
Codes], page 371).
If shift-select-mode is non-nil and the current command was invoked via shift
translation (see Section 21.8.1 [Key Sequence Input], page 397), this function sets the
mark and temporarily activates the region, unless the region was already temporarily
activated in this way. Otherwise, if the region has been activated temporarily, it
deactivates the mark and restores the variable transient-mark-mode to its earlier
value.
mark-ring [Variable]
The value of this buffer-local variable is the list of saved former marks of the current
buffer, most recent first.
mark-ring
⇒ (#<marker at 11050 in markers.texi>
#<marker at 10832 in markers.texi>
...)
When Delete Selection mode (see Section “Using Region” in The GNU Emacs Man-
ual) is enabled, commands that operate on the active region (a.k.a. “selection”) behave
slightly differently. This works by adding the function delete-selection-pre-hook to the
pre-command-hook (see Section 21.1 [Command Overview], page 368). That function calls
delete-selection-helper to delete the selection as appropriate for the command. If you
want to adapt a command to Delete Selection mode, put the delete-selection property
on the function’s symbol (see Section 9.4.1 [Symbol Plists], page 125); commands that don’t
have this property on their symbol won’t delete the selection. This property can have one
of several values to tailor the behavior to what the command is supposed to do; see the doc
strings of delete-selection-pre-hook and delete-selection-helper for the details.
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.
use-region-p [Function]
This function returns t if Transient Mark mode is enabled, the mark is active, and
there is a valid region in the buffer. This function is intended to be used by commands
that operate on the region, instead of on text near point, when the mark is active.
A region is valid if it has a non-zero size, or if the user option use-empty-active-
region is non-nil (by default, it is nil). The function region-active-p is similar
to use-region-p, but considers all regions as valid. In most cases, you should not
use region-active-p, since if the region is empty it is often more appropriate to
operate on point.
765
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 781).
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 756) or numeric character positions (see Chapter 30 [Positions],
page 742). 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.
(string (preceding-char))
⇒ "a"
(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 742.
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 742.
bolp [Function]
This function returns t if point is at the beginning of a line. See Section 30.2.4 [Text
Lines], page 745. 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 802.
However, overlays (see Section 39.9 [Overlays], page 985) 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-string [Function]
This function returns the contents of the entire accessible portion of the current buffer,
as a string.
If you need to make sure the resulting string, when copied to a different location,
will not change its visual appearance due to reordering of bidirectional text, use the
buffer-substring-with-bidi-context function (see Section 39.26 [Bidirectional
Display], page 1067).
filter-buffer-substring-function [Variable]
The value of this variable is a function that filter-buffer-substring will call to
do the actual work. The function receives three arguments, the same as those of
filter-buffer-substring, which it should treat as per the documentation of that
function. It should return the filtered text (and optionally delete the source text).
Chapter 32: Text 768
filter-buffer-substring-functions [Variable]
This obsolete variable is a wrapper hook, whose members should be functions that
accept four arguments: fun, start, end, and delete. fun is a function that takes three
arguments (start, end, and delete), and returns a string. In both cases, the start,
end, and delete arguments are the same as those of filter-buffer-substring.
The first hook function is passed a fun that is equivalent to the default operation of
filter-buffer-substring, i.e., it returns the buffer-substring between start and end
(processed by any buffer-substring-filters) and optionally deletes the original
text from the buffer. In most cases, the hook function will call fun once, and then do
its own processing of the result. The next hook function receives a fun equivalent to
this, and so on. The actual return value is the result of all the hook functions acting
in sequence.
buffer-substring-filters [Variable]
The value of this obsolete variable should be a list of functions that accept a single
string argument and return another string. The default filter-buffer-substring
function 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 passed to filter-buffer-substring-functions.
(thing-at-point 'word)
⇒ "Peace"
(thing-at-point 'line)
Chapter 32: Text 769
they do not convert unibyte character codes 128 through 255 to multibyte characters, not
even if the current buffer is a multibyte buffer. See Section 33.3 [Converting Representa-
tions], page 837.
This function calls auto-fill-function if the current column number is greater than
the value of fill-column and number-of-newlines is nil. Typically what auto-fill-
function does is insert a newline; thus, the overall result in this case is to insert two
newlines at different places: one at point, and another earlier in the line. newline
does not auto-fill if number-of-newlines is non-nil.
This command indents to the left margin if that is not zero. See Section 32.12
[Margins], page 788.
The value returned is nil. In an interactive call, count is the numeric prefix argument.
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).
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.
(delete-indentation)
⇒ nil
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
Chapter 32: Text 775
(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.
for internal purposes within a Lisp function, you should normally use deletion functions, so
as not to disturb the kill ring contents. See Section 32.6 [Deletion], page 772.
Killed text is saved for later yanking in the kill ring. This is a list that holds a number
of recent kills, not just the last text kill. We call this a “ring” because yanking treats it as
having elements in a cyclic order. The list is kept in the variable kill-ring, and can be
operated on with the usual functions for lists; there are also specialized functions, described
in this section, that treat it as a ring.
Some people think this use of the word “kill” is unfortunate, since it refers to operations
that specifically do not destroy the entities killed. This is in sharp contrast to ordinary life,
in which death is permanent and killed entities do not come back to life. Therefore, other
metaphors have been proposed. For example, the term “cut ring” makes sense to people
who, in pre-computer days, used scissors and paste to cut up and rearrange manuscripts.
However, it would be difficult to change the terminology now.
In an interactive call, start and end are point and the mark, and region is always
non-nil, so the command always kills the text in the current region.
If the buffer or text is read-only, kill-region modifies the kill ring just the same,
then signals an error without modifying the buffer. This is convenient because it lets
the user use a series of kill commands to copy text from a read-only buffer into the
kill ring.
kill-read-only-ok [User Option]
If this option is non-nil, kill-region does not signal an error if the buffer or text
is read-only. Instead, it simply returns, updating the kill ring but not changing the
buffer.
copy-region-as-kill start end &optional region [Command]
This function saves the stretch of text between start and end on the kill ring (including
text properties), but does not delete the text from the buffer. However, if the optional
argument region is non-nil, the function ignores start and end, and saves the current
region instead. It always returns nil.
In an interactive call, start and end are point and the mark, and region is always
non-nil, so the command always saves the text in the current region.
The command does not set this-command to kill-region, so a subsequent kill com-
mand does not append to the same kill ring entry.
32.8.3 Yanking
Yanking means inserting text from the kill ring, but it does not insert the text blindly. The
yank command, and related commands, use insert-for-yank to perform special processing
on the text before it is inserted.
insert-for-yank string [Function]
This function works like insert, except that it processes the text in string ac-
cording to the yank-handler text property, as well as the variables yank-handled-
properties and yank-excluded-properties (see below), before inserting the result
into the current buffer.
insert-buffer-substring-as-yank buf &optional start end [Function]
This function resembles insert-buffer-substring, except that it processes the text
according to yank-handled-properties and yank-excluded-properties. (It does
not handle the yank-handler property, which does not normally occur in buffer text
anyway.)
If you put a yank-handler text property on all or part of a string, that alters
how insert-for-yank inserts the string. If different parts of the string have different
yank-handler values (comparison being done with eq), each substring is handled
separately. 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 non-nil, it is called instead of insert to insert the string,
with one argument—the string to insert.
Chapter 32: Text 778
param If param is present and non-nil, it replaces string (or the substring 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, that disables the normal action of
yank-handled-properties and yank-excluded-properties on the inserted
string.
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.
is an integer different from one, it rotates the kill ring to place the yanked string at
the front.
yank returns nil.
yank-pop &optional arg [Command]
This command replaces the just-yanked entry from the kill ring with a different entry
from the kill ring.
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.
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.
To facilitate support for window systems that support multiple selections, this func-
tion may also return a list of strings. In that case, the first string is used as the most
recent kill, and all the other strings are pushed onto the kill ring, for easy access by
yank-pop.
The normal use of this function is to get the window system’s clipboard as the most
recent kill, even if the selection belongs to another application. See Section 29.20
[Window System Selections], page 733. However, if the clipboard contents come from
the current Emacs session, this function should return nil.
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
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 argument.
The normal use of this function is to put newly killed text in the window system’s
clipboard. See Section 29.20 [Window System Selections], page 733.
the beginning, or vice-versa. Rotation of the kill ring is virtual; it does not change the value
of kill-ring.
Both kill-ring and kill-ring-yank-pointer are Lisp variables whose values are nor-
mally lists. The word “pointer” in the name of the kill-ring-yank-pointer indicates
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 584.) 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.
Chapter 32: Text 782
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.
Here are the kinds of elements an undo list can have:
position This kind of element records a previous value of point; undoing this element
moves point to position. Ordinary cursor motion does not make any sort of
undo record, but deletion operations use these entries to record where point
was before the command.
(beg . end)
This kind of element indicates how to delete text that was inserted. Upon
insertion, the text occupied the range beg–end in the buffer.
(text . position)
This kind of element indicates how to reinsert text that was deleted. The
deleted text itself is the string text. The place to reinsert it is (abs position).
If position is positive, point was at the beginning of the deleted text, other-
wise it was at the end. Zero or more (marker . adjustment) elements follow
immediately after this element.
(t . time-flag)
This kind of element indicates that an unmodified buffer became modified.
A time-flag of the form (sec-high sec-low microsec picosec) represents
the visited file’s modification time as of when it was previously visited or
saved, using the same format as current-time; see Section 40.5 [Time of Day],
page 1086. A time-flag of 0 means the buffer does not correspond to any file;
−1 means the visited file previously did not exist. primitive-undo uses these
values to determine whether to mark the buffer as unmodified once again; it
does so only if the file’s status matches that of time-flag.
(nil property value beg . end)
This kind of element records a change in a text property. Here’s how you might
undo the change:
(put-text-property beg end property value)
(marker . adjustment)
This kind of element records the fact that the marker marker was relocated
due to deletion of surrounding text, and that it moved adjustment character
positions. If the marker’s location is consistent with the (text . position)
element preceding it in the undo list, then undoing this element moves marker
− adjustment characters.
(apply funname . args)
This is an extensible undo item, which is undone by calling funname with
arguments args.
(apply delta beg end funname . args)
This is an extensible undo item, which records a change limited to the range
beg to end, which increased the size of the buffer by delta characters. It is
undone by calling funname with arguments args.
Chapter 32: Text 783
This kind of element enables undo limited to a region to determine whether the
element pertains to that region.
nil This element is a boundary. The elements between two boundaries are called
a change group; normally, each change group corresponds to one keyboard
command, and undo commands normally undo an entire group as a unit.
undo-boundary [Function]
This function places a boundary element in the undo list. The undo command stops
at such a boundary, and successive undo commands undo to earlier and earlier bound-
aries. This function returns nil.
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.
Mostly, however, this function is called automatically at an appropriate time.
undo-auto-amalgamate [Function]
The editor command loop automatically calls undo-boundary just before executing
each key sequence, so that each undo normally undoes the effects of one command. A
few exceptional commands are amalgamating: these commands generally cause small
changes to buffers, so with these a boundary is inserted only every 20th command, al-
lowing the changes to be undone as a group. By default, the commands self-insert-
command, which produces self-inserting input characters (see Section 32.5 [Commands
for Insertion], page 771), and delete-char, which deletes characters (see Section 32.6
[Deletion], page 772), are amalgamating. Where a command affects the contents of
several buffers, as may happen, for example, when a function on the post-command-
hook affects a buffer other than the current-buffer, then undo-boundary will be
called in each of the affected buffers.
undo-auto-current-boundary-timer [Variable]
Some buffers, such as process buffers, can change even when no commands are exe-
cuting. In these cases, undo-boundary is normally called periodically by the timer in
this variable. Setting this variable to non-nil prevents this behavior.
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.
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 790) 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 788). If the current justification
style is none, the filling functions don’t actually do anything.
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.
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 to override the filling of paragraphs. If its 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))
fill-forward-paragraph-function [Variable]
This variable provides a way to override how the filling functions, such as fill-region
and fill-paragraph, move forward to the next paragraph. Its value should be a
function, which is called with a single argument n, the number of paragraphs to
move, and should return the difference between n and the number of paragraphs
actually moved. The default value of this variable is forward-paragraph. See Section
“Paragraphs” in The GNU Emacs Manual.
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. See Section
“Hard and Soft Newlines” in The GNU Emacs Manual.
Chapter 32: Text 788
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.
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.
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.
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<.
As an example of sort-subr, here is the complete function definition for sort-lines:
;; Note that the first two lines of doc string
;; are effectively one line when viewed by a user.
(defun sort-lines (reverse beg end)
"Sort lines in region alphabetically;\
argument means descending order.
Called from a program, there are three arguments:
REVERSE (non-nil means reverse order),\
BEG and END (region to sort).
The variable `sort-fold-case' determines\
whether alphabetic case affects
the sort order."
(interactive "P\nr")
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(let ((inhibit-field-text-motion t))
(sort-subr reverse 'forward-line 'end-of-line)))))
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:
(sort-subr reverse
(function
(lambda ()
(while (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1))))
'forward-paragraph)
Chapter 32: Text 793
Markers pointing into any sort records are left with no useful position after sort-subr
returns.
current-column [Function]
This function returns the horizontal position of point, measured in columns, counting
from 0 at the left margin. The column position is the sum of the widths of all the
displayed representations of the characters between the start of the current line and
point.
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 796
current-indentation [Function]
This function returns the indentation of the current line, which is the horizontal
position of the first nonblank character. If the contents are entirely blank, then this
is the horizontal position of the end of the line.
If rigid is non-nil (interactively, with a prefix argument), then after this command
indents a line or inserts a tab, it also rigidly indents the entire balanced expression
which starts at the beginning of the current line, in order to reflect the new indenta-
tion. This argument is ignored if the command indents the region.
indent-line-function [Variable]
This variable’s value is the function to be used by indent-for-tab-command, and
various other indentation commands, to indent the current line. It is usually assigned
by the major mode; for instance, Lisp mode sets it to lisp-indent-line, C mode
sets it to c-indent-line, and so on. The default value is indent-relative. See
Section 23.7 [Auto-Indentation], page 499.
indent-according-to-mode [Command]
This command calls the function in indent-line-function to indent the current
line in a way appropriate for the current major mode.
newline-and-indent [Command]
This function inserts a newline, then indents the new line (the one following the
newline just inserted) according to the major mode. It does indentation by calling
indent-according-to-mode.
reindent-then-newline-and-indent [Command]
This command reindents the current line, inserts a newline at point, and then indents
the new line (the one following the newline just inserted). It does indentation on both
lines by calling indent-according-to-mode.
Some major modes need to support embedded regions of text whose syntax belongs to
a different major mode. Examples include literate programming source files that combine
documentation and snippets of source code, Yacc/Bison programs that include snippets of
Python or JS code, etc. To correctly indent the embedded chunks, the primary mode needs
to delegate the indentation to another mode’s indentation engine (e.g., call js-indent-line
for JS code or python-indent-line for Python), while providing it with some context to
guide the indentation. Major modes, for their part, should avoid calling widen in their
indentation code and obey prog-first-column.
prog-indentation-context [Variable]
This variable, when non-nil, holds the indentation context for the sub-mode’s inden-
tation engine provided by the superior major mode. The value should be a list of the
form (first-column . rest. The members of the list have the following meaning:
Chapter 32: Text 798
first-column
The column to be used for top-level constructs. This replaces the default
value of the top-level column used by the sub-mode, usually zero.
rest This value is currently unused.
The following convenience function should be used by major mode’s indentation engine
in support of invocations as sub-modes of another major mode.
prog-first-column [Function]
Call this function instead of using a literal value (usually, zero) of the column number
for indenting top-level program constructs. The function’s value is the column number
to use for top-level constructs. When no superior mode is in effect, this function
returns zero.
indent-region-function [Variable]
The value of this variable is a function that can be used by indent-region as a
short cut. It should take two arguments, the start and end of the region. You should
design the function so that it will produce the same results as indenting the lines of
the region one by one, but presumably faster.
If the value is nil, there is no short cut, and indent-region actually works line by
line.
A short-cut function is useful in modes such as C mode and Lisp mode, where the
indent-line-function must scan from the beginning of the function definition: ap-
plying it to each line would be quadratic in time. The short cut can update the scan
information as it moves through the lines indenting them; this takes linear time. In
a mode where indenting a line individually is fast, there is no need for a short cut.
indent-region with a non-nil argument to-column has a different meaning and does
not use this variable.
This is useful not only for indenting regions of unindented text, but also for indenting
regions of formatted code. For example, if count is 3, this command adds 3 columns
of indentation to every line that begins in the specified region.
If called interactively with no prefix argument, this command invokes a transient
mode for adjusting indentation rigidly. See Section “Indentation Commands” in The
GNU Emacs Manual.
indent-relative-first-indent-point [Command]
This command indents the current line like the previous nonblank line, by calling
indent-relative with t as the first-only argument. The return value is unpre-
dictable.
If the previous nonblank line has no indent points beyond the current column, this
command does nothing.
(capitalize-region 1 37)
⇒ nil
in that buffer are considered first, in order of decreasing priority, followed by the text
properties. If object is a string, only text properties are considered, since strings
never have overlays.
get-pos-property position prop &optional object [Function]
This function is like get-char-property, except that it pays attention to properties’
stickiness and overlays’ advancement settings instead of the property of the character
at (i.e., right after) position.
get-char-property-and-overlay position prop &optional object [Function]
This is like get-char-property, but gives extra information about the overlay that
the property value comes from.
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.
text-properties-at position &optional object [Function]
This function returns the entire property list of the character at position in the string
or buffer object. If object is nil, it defaults to the current buffer.
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
buffer as modified. Buffer text property changes are undoable also (see Section 32.9 [Undo],
page 781). Positions in a string start from 0, whereas positions in a buffer start from 1.
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:
See Section 32.2 [Buffer Contents], page 766, for the function buffer-substring-no-
properties, which copies text from the buffer but does not copy its properties.
Chapter 32: Text 806
If you wish to add text properties to a buffer or remove them without marking the buffer
as modified, you can wrap the calls above in the with-silent-modifications macro. See
Section 27.5 [Buffer Modification], page 587.
If limit is non-nil, then the scan ends at position limit. If there is no property change
before that point, next-single-property-change returns limit.
The value is nil if the property remains unchanged all the way to the end of object
and limit is nil. If the value is non-nil, it is a position greater than or equal to pos;
it equals pos only if limit equals pos.
previous-single-property-change pos prop &optional object limit [Function]
This is like next-single-property-change, but scans back from pos instead of for-
ward. If the value is non-nil, it is a position less than or equal to pos; it equals pos
only if limit equals pos.
next-char-property-change pos &optional limit [Function]
This is like next-property-change except that it considers overlay properties as
well as text properties, and if no change is found before the end of the buffer, it
returns the maximum buffer position rather than nil (in this sense, it resembles the
corresponding overlay function next-overlay-change, rather than next-property-
change). There is no object operand because this function operates only on the
current buffer. It returns the next address at which either kind of property changes.
previous-char-property-change pos &optional limit [Function]
This is like next-char-property-change, but scans back from pos instead of forward,
and returns the minimum buffer position if no change is found.
next-single-char-property-change pos prop &optional object [Function]
limit
This is like next-single-property-change except that it considers overlay proper-
ties as well as text properties, and if no change is found before the end of the object,
it returns the maximum valid position in object rather than nil. Unlike next-char-
property-change, this function does have an object operand; if object is not a buffer,
only text-properties are considered.
previous-single-char-property-change pos prop &optional [Function]
object limit
This is like next-single-char-property-change, but scans back from pos instead
of forward, and returns the minimum valid position in object if no change is found.
text-property-any start end prop value &optional object [Function]
This function returns non-nil if at least one character between start and end has a
property prop whose value is value. More precisely, it returns the position of the first
such character. Otherwise, it returns nil.
The optional fifth argument, object, specifies the string or buffer to scan. Positions
are relative to object. The default for object is the current buffer.
text-property-not-all start end prop value &optional object [Function]
This function returns non-nil if at least one character between start and end does
not have a property prop with value value. More precisely, it returns the position of
the first such character. Otherwise, it returns nil.
The optional fifth argument, object, specifies the string or buffer to scan. Positions
are relative to object. The default for object is the current buffer.
Chapter 32: Text 808
fontified
This property says whether the text is ready for display. If nil, Emacs’s
redisplay routine calls the functions in fontification-functions (see
Section 39.12.7 [Auto Faces], page 1009) 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 39.16 [Display Property],
page 1028.
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 39.25 [Tooltips], page 1065).
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 813).
This feature is used in the mode line and for other active text.
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 422. 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.
Chapter 32: Text 810
syntax-table
The syntax-table property overrides what the syntax table says about this
particular character. See Section 35.4 [Syntax Properties], page 899.
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 814.
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 590.
inhibit-read-only
Characters that have the property inhibit-read-only can be edited even in
read-only buffers. See Section 27.7 [Read Only Buffers], page 590.
invisible
A non-nil invisible property can make a character invisible on the screen.
See Section 39.6 [Invisible Text], page 977, 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 (as it is by de-
fault), the intangible property is ignored.
Beware: this property operates at a very low level, and affects a lot of code
in unexpected ways. So use it with extreme caution. A common misuse is
to put an intangible property on invisible text, which is actually unnecessary
since the command loop will move point outside of the invisible text at the end
of each command anyway. See Section 21.6 [Adjusting Point], page 380. For
these reasons, this property is obsolete; use the cursor-intangible property
instead.
cursor-intangible
When the minor mode cursor-intangible-mode is turned on, point is moved
away from any position that has a non-nil cursor-intangible property, just
before redisplay happens.
Chapter 32: Text 811
wrap-prefix
If text has a wrap-prefix property, the prefix it defines will be added at display
time to the beginning of every continuation line due to text wrapping (so if
lines are truncated, the wrap-prefix is never used). It may be a string or an
image (see Section 39.16.4 [Other Display Specs], page 1031), or a stretch of
whitespace such as specified by the :width or :align-to display properties
(see Section 39.16.2 [Specified Space], page 1029).
A wrap-prefix may also be specified for an entire buffer using the wrap-prefix
buffer-local variable (however, a wrap-prefix text-property takes precedence
over the value of the wrap-prefix variable). See Section 39.3 [Truncation],
page 968.
line-prefix
If text has a line-prefix property, the prefix it defines will be added at display
time to the beginning of every non-continuation line. It may be a string or an
image (see Section 39.16.4 [Other Display Specs], page 1031), or a stretch of
whitespace such as specified by the :width or :align-to display properties
(see Section 39.16.2 [Specified Space], page 1029).
A line-prefix may also be specified for an entire buffer using the line-prefix
buffer-local variable (however, a line-prefix text-property takes precedence
over the value of the line-prefix variable). See Section 39.3 [Truncation],
page 968.
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 before
the actual modification. 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.
Furthermore, insertion will not modify any existing character, so this hook will
only be run when removing some characters, replacing them with others, or
changing their text-properties.
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 39.9.2 [Overlay Properties], page 988).
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.30 [Change Hooks], page 832, for other hooks that are called
when you change text in a buffer.
Chapter 32: Text 813
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
• the point-entered property of the character after the new location.
If these two values differ, each of them is called (if not nil) with two arguments:
the old value of point, and the new one.
The same comparison is made for the characters before the old and new lo-
cations. The result may be to execute two point-left functions (which may
be the same function) and/or two point-entered functions (which may be
the same function). In any case, all the point-left functions are called first,
followed by all the point-entered functions.
It is possible to use char-after to examine characters at various buffer posi-
tions without moving point to those positions. Only an actual change in the
value of point runs these hook functions.
The variable inhibit-point-motion-hooks by default inhibits running the
point-left and point-entered hooks, see [Inhibit point motion hooks],
page 813.
These properties are obsolete; please use cursor-sensor-functions instead.
cursor-sensor-functions
This special property records a list of functions that react to cursor motion.
Each function in the list is called, just before redisplay, with 3 arguments: the
affected window, the previous known position of the cursor, and one of the
symbols entered or left, depending on whether the cursor is entering the text
that has this property or leaving it. The functions are called only when the
minor mode cursor-sensor-mode is turned on.
When the variable cursor-sensor-inhibit is non-nil, the cursor-sensor-
functions property is ignored.
composition
This text property is used to display a sequence of characters as a single glyph
composed from components. But the value of the property itself is completely
internal to Emacs and should not be manipulated directly by, for instance,
put-text-property.
inhibit-point-motion-hooks [Variable]
When this obsolete variable is non-nil, point-left and point-entered hooks are
not run, and the intangible property has no effect. Do not set this variable globally;
bind it with let. Since the affected properties are obsolete, this variable’s default
value is t, to effectively disable them.
show-help-function [Variable]
If this variable is non-nil, it specifies a function called to display help strings. These
may be help-echo properties, menu help strings (see Section 22.17.1.1 [Simple Menu
Chapter 32: Text 814
Items], page 440, see Section 22.17.1.2 [Extended Menu Items], page 441), or tool
bar help strings (see Section 22.17.6 [Tool Bar], page 447). The specified function
is called with one argument, the help string to display, which is passed through
substitute-command-keys before being given to the function; see Section 24.3 [Keys
in Documentation], page 513. Tooltip mode (see Section “Tooltips” in The GNU
Emacs Manual) provides an example.
can use those two text properties to make any specific properties sticky or nonsticky in any
particular part of the text.
If a character’s front-sticky property is t, then all its properties are front-sticky. If the
front-sticky property is a list, then the sticky properties of the character are those whose
names are in the list. For example, if a character has a front-sticky property whose value
is (face read-only), then insertion before the character can inherit its face property and
its read-only property, but no others.
The rear-nonsticky property works the opposite way. Most properties are rear-sticky
by default, so the rear-nonsticky property says which properties are not rear-sticky. If
a character’s rear-nonsticky property is t, then none of its properties are rear-sticky. If
the rear-nonsticky property is a list, properties are rear-sticky unless their names are in
the list.
text-property-default-nonsticky [Variable]
This variable holds an alist which defines the default rear-stickiness of various text
properties. Each element has the form (property . nonstickiness), and it defines
the stickiness of a particular text property, property.
If nonstickiness is non-nil, this means that the property property is rear-nonsticky
by default. Since all properties are front-nonsticky by default, this makes property
nonsticky in both directions by default.
The text properties front-sticky and rear-nonsticky, when used, take precedence
over the default nonstickiness specified in text-property-default-nonsticky.
Here are the functions that insert text with inheritance of properties:
insert-and-inherit &rest strings [Function]
Insert the strings strings, just like the function insert, but inherit any sticky prop-
erties from the adjoining text.
insert-before-markers-and-inherit &rest strings [Function]
Insert the strings strings, just like the function insert-before-markers, but inherit
any sticky properties from the adjoining text.
See Section 32.4 [Insertion], page 769, for the ordinary insertion functions which do not
inherit.
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.
(interactive "e")
(let ((window (posn-window (event-end event)))
(pos (posn-point (event-end event)))
file)
(if (not (windowp window))
(error "No file chosen"))
(with-current-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)))))
This command uses the functions posn-window and posn-point to determine where the
click occurred, and dired-get-file-for-visit to determine which file to visit.
Instead of binding the mouse command in a major mode keymap, you can bind it within
the link text, using the keymap text property (see Section 32.19.4 [Special Properties],
page 808). For instance:
(let ((map (make-sparse-keymap)))
(define-key map [mouse-2] 'operate-this-button)
(put-text-property link-start link-end 'keymap map))
With this method, you can easily define different commands for different links. Furthermore,
the global definition of RET and mouse-2 remain available for the rest of the text in the
buffer.
The basic Emacs command for clicking on links is mouse-2. However, for compatibility
with other graphical applications, Emacs also recognizes mouse-1 clicks on links, provided
the user clicks on the link quickly without moving the mouse. This behavior is controlled
by the user option mouse-1-click-follows-link. See Section “Mouse References” in The
GNU Emacs Manual.
To set up the link so that it obeys mouse-1-click-follows-link, you must either (1)
apply a follow-link text or overlay property to the link text, or (2) bind the follow-link
event to a keymap (which can be a major mode keymap or a local keymap specified via
the keymap text property). The value of the follow-link property, or the binding for the
follow-link event, acts as a condition for the link action. This condition tells Emacs two
things: the circumstances under which a mouse-1 click should be regarded as occurring
inside the link, and how to compute an action code that says what to translate the mouse-1
click into. The link action condition can be one of the following:
mouse-face
If the condition is the symbol mouse-face, a position is inside a link if there is
a non-nil mouse-face property at that position. The action code is always t.
For example, here is how Info mode handles mouse-1:
(define-key Info-mode-map [follow-link] 'mouse-face)
Chapter 32: Text 818
a function If the condition is a 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:
(define-key map [follow-link]
(lambda (pos)
(eq (get-char-property pos 'face) 'cvs-filename-face)))
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 specify this kind of
condition only when applying the condition via a text or property overlay on
the link text (so that it does not apply to the entire buffer).
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. The property value should be a link action condition, as
described above. See Section 39.19 [Buttons], page 1049. 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. The property value should be a link action condition, as described
above. 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%]")
interval and yank it back. The same interval-coalescence feature that rescues the other case
causes trouble in this one: after yanking, we have just one interval. Once again, editing
does not preserve the distinction between one interval and two.
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 text at this buffer or string position?” 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 806.
Emacs also provides explicit intervals as a presentation feature; see Section 39.9 [Over-
lays], page 985.
(subst-char-in-region 1 20 ?i ?X)
⇒ nil
The return value of translate-region is the number of characters that were actually
changed by the translation. This does not count characters that were mapped into
themselves in the translation table.
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.
The contents of a register can have several possible types:
a number A number stands for itself. If insert-register finds a number in the register,
it converts the number to decimal.
a marker A marker represents a buffer position to jump to.
a string A string is text saved in the register.
a rectangle
A rectangle is represented by a list of strings.
(window-configuration position)
This represents a window configuration to restore in one frame, and a position
to jump to in the current buffer.
(frame-configuration position)
This represents a frame configuration to restore, and a position to jump to in
the current buffer.
(file filename)
This represents a file to visit; jumping to this value visits file filename.
(file-query filename position)
This represents a file to visit and a position in it; jumping to this value visits file
filename and goes to buffer position position. Restoring this type of position
asks the user for confirmation first.
The functions in this section return unpredictable values unless otherwise stated.
get-register reg [Function]
This function returns the contents of the register reg, or nil if it has no contents.
set-register reg value [Function]
This function sets the contents of register reg to value. A register can be set to any
value, but the other register functions expect only certain data types. The return
value is value.
Chapter 32: Text 823
buffer. This function attempts to keep point, markers, text properties, and overlays
in the current buffer intact. One potential case where this behavior is useful is ex-
ternal code formatting programs: they typically write the reformatted text into a
temporary buffer or file, and using delete-region and insert-buffer-substring
would destroy these properties. However, the latter combination is typically faster.
See Section 32.6 [Deletion], page 772, and Section 32.4 [Insertion], page 769.
zlib-available-p [Function]
This function returns non-nil if built-in zlib decompression is available.
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.
base64-decode-region beg end [Command]
This function converts the region from beg to end from base 64 code into the corre-
sponding decoded text. It returns the length of the decoded text.
The decoding functions ignore newline characters in the encoded text.
base64-decode-string string [Function]
This function converts the string string from base 64 code into the corresponding
decoded text. It returns a unibyte string containing the decoded text.
The decoding functions ignore newline characters in the encoded text.
32.26 Checksum/Hash
Emacs has built-in support for computing cryptographic hashes. A cryptographic hash, or
checksum, is a digital fingerprint of a piece of data (e.g., a block of text) which can be used
to check that you have an unaltered copy of that data.
Emacs supports several common cryptographic hash algorithms: MD5, SHA-1, SHA-
2, SHA-224, SHA-256, SHA-384 and SHA-512. MD5 is the oldest of these algorithms,
and is commonly used in message digests to check the integrity of messages transmitted
over a network. MD5 is not collision resistant (i.e., it is possible to deliberately design
different pieces of data which have the same MD5 hash), so you should not used it for
anything security-related. A similar theoretical weakness also exists in SHA-1. Therefore,
for security-related applications you should use the other hash types, such as SHA-2.
secure-hash-algorithms [Function]
This function returns a list of symbols representing algorithms that secure-hash can
use.
secure-hash algorithm object &optional start end binary [Function]
This function returns a hash for object. The argument algorithm is a symbol stating
which hash to compute: one of md5, sha1, sha224, sha256, sha384 or sha512. The
argument object should be a buffer or a string.
The optional arguments start and end are character positions specifying the portion
of object to compute the message digest for. If they are nil or omitted, the hash is
computed for the whole of object.
If the argument binary is omitted or nil, the function returns the text form of the
hash, as an ordinary Lisp string. If binary is non-nil, it returns the hash in binary
form, as a sequence of bytes stored in a unibyte string.
This function does not compute the hash directly from the internal representation of
object’s text (see Section 33.1 [Text Representations], page 835). Instead, it encodes
the text using a coding system (see Section 33.10 [Coding Systems], page 848), and
computes the hash from that encoded text. If object is a buffer, the coding system
used is the one which would be chosen by default for writing the text into a file. If
object is a string, the user’s preferred coding system is used (see Section “Recognize
Coding” in GNU Emacs Manual).
Chapter 32: Text 826
(iv-auto length)
This will generate an IV (Initialization Vector) of the specified length using the
GnuTLS GNUTLS_RND_NONCE generator and pass it to the function. This ensures
that the IV is unpredictable and unlikely to be reused in the same session. The
actual value of the IV is returned by the function as described below.
gnutls-macs [Function]
This function returns the alist of the GnuTLS MAC algorithms.
Each entry has a key which represents the algorithm, followed by a plist with internal
details about the algorithm. The plist will have :type gnutls-mac-algorithm
and also will have the keys :mac-algorithm-length :mac-algorithm-keysize
:mac-algorithm-noncesize to indicate the size, in bytes, of the resulting hash, the
key, and the nonce respectively.
The nonce is currently unused and only some MACs support it.
There is a name parallel between GnuTLS MAC and digest algorithms but they are
separate things internally and should not be mixed.
This function returns nil on error, and signals a Lisp error if the hash-method or
key or input are invalid.
On success, it returns a list of a binary string (the output) and the IV used.
gnutls-ciphers [Function]
This function returns the alist of the GnuTLS ciphers.
Each entry has a key which represents the cipher, followed by a plist with inter-
nal details about the algorithm. The plist will have :type gnutls-symmetric-
cipher and also will have the keys :cipher-aead-capable set to nil or t to indi-
cate AEAD capability; and :cipher-tagsize :cipher-blocksize :cipher-keysize
:cipher-ivsize to indicate the size, in bytes, of the tag, block size of the resulting
data, the key, and the IV respectively.
(div nil
"Yes")))
The following functions can be used to work with this structure. Each function takes a
DOM node, or a list of nodes. In the latter case, only the first node in the list is used.
Simple accessors:
dom-tag node
Return the tag (also called “node name”) of the node.
dom-attr node attribute
Return the value of attribute in the node. A common usage would be:
(dom-attr img 'href)
=> "https://fsf.org/logo.png"
dom-children node
Return all the children of the node.
dom-non-text-children node
Return all the non-string children of the node.
dom-attributes node
Return the key/value pair list of attributes of the node.
dom-text node
Return all the textual elements of the node as a concatenated string.
dom-texts node
Return all the textual elements of the node, as well as the textual elements of
all the children of the node, recursively, as a concatenated string. This function
also takes an optional separator to be inserted between the textual elements.
dom-parent dom node
Return the parent of node in dom.
dom-remove dom node
Remove node from dom.
The following are functions for altering the DOM.
dom-set-attribute node attribute value
Set the attribute of the node to value.
dom-append-child node child
Append child as the last child of node.
dom-add-child-before node child before
Add child to node’s child list before the before node. If before is nil, make
child the first child.
Chapter 32: Text 831
before-change-functions [Variable]
This variable holds a list of functions to call when Emacs is about to modify a buffer.
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 when the function is called.
after-change-functions [Variable]
This variable holds a list of functions to call after Emacs modifies a buffer. 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 has been changed is always the current buffer when the
function is called.
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, and neither
do certain internal buffer changes, such as changes in buffers created by Emacs internally
for certain jobs, that should not be visible to Lisp programs.
The vast majority of buffer changing primitives will call before-change-functions and
after-change-functions in balanced pairs, once for each change, where the arguments
to these hooks exactly delimit the change being made. Yet, hook functions should not
rely on this always being the case, because some complex primitives call before-change-
functions once before making changes, and then call after-change-functions zero or
more times, depending on how many individual changes the primitive is making. When
that happens, the arguments to before-change-functions will enclose a region in which
the individual changes are made, but won’t necessarily be the minimal such region, and the
arguments to each successive call of after-change-functions will then delimit the part of
text being changed exactly. In general, we advise to use either before- or the after-change
hooks, but not both.
combine-after-change-calls body. . . [Macro]
The macro executes body normally, but arranges to call the after-change functions
just once for a series of several changes—if that seems safe.
If a program makes several text changes in the same area of the buffer, using the
macro combine-after-change-calls around that part of the program can make it
run considerably faster when after-change hooks are in use. When the after-change
hooks are ultimately called, the arguments specify a portion of the buffer including
all of the changes made within the combine-after-change-calls body.
Warning: You must not alter the values of after-change-functions within the body
of a combine-after-change-calls form.
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.
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.
Chapter 32: Text 834
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 808) and overlay properties (see Section 39.9.2 [Overlay Properties], page 988).
Also, this variable is bound to non-nil while running those same hook variables,
so that by default modifying the buffer from a modification hook does not cause
other modification hooks to be run. If you do want modification hooks to be run
in a particular piece of code that is itself run from a modification hook, then rebind
locally inhibit-modification-hooks to nil.
835
33 Non-ASCII Characters
This chapter covers the special issues relating to 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 encoded text or binary
non-text data.
1
This internal representation is based on one of the encodings defined by the Unicode Standard, called
UTF-8, for representing any Unicode codepoint, but Emacs extends UTF-8 to represent the additional
codepoints it uses for raw 8-bit bytes and characters not unified with Unicode.
Chapter 33: Non-ASCII Characters 836
You cannot set this variable directly; instead, use the function set-buffer-
multibyte to change a buffer’s representation.
position-bytes position [Function]
Buffer positions are measured in character units. This function returns the byte-
position corresponding to buffer position position in the current buffer. This is 1 at
the start of the buffer, and counts upward in bytes. If position is out of range, the
value is nil.
byte-to-position byte-position [Function]
Return the buffer position, in character units, corresponding to given byte-position
in the current buffer. If byte-position is out of range, the value is nil. In a multibyte
buffer, an arbitrary value of byte-position can be not at character boundary, but
inside a multibyte sequence representing a single character; in this case, this function
returns the buffer position of the character whose multibyte sequence includes byte-
position. In other words, the value does not change for all byte positions that belong
to the same character.
The following two functions are useful when a Lisp program needs to map buffer positions
to byte offsets in a file visited by the buffer.
bufferpos-to-filepos position &optional quality coding-system [Function]
This function is similar to position-bytes, but instead of byte position in the cur-
rent buffer it returns the offset from the beginning of the current buffer’s file of the
byte that corresponds to the given character position in the buffer. The conversion
requires to know how the text is encoded in the buffer’s file; this is what the coding-
system argument is for, defaulting to the value of buffer-file-coding-system. The
optional argument quality specifies how accurate the result should be; it should be
one of the following:
exact The result must be accurate. The function may need to encode and
decode a large part of the buffer, which is expensive and can be slow.
approximate
The value can be an approximation. The function may avoid expensive
processing and return an inexact result.
nil If the exact result needs expensive processing, the function will return
nil rather than an approximation. This is the default if the argument is
omitted.
filepos-to-bufferpos byte &optional quality coding-system [Function]
This function returns the buffer position corresponding to a file position specified
by byte, a zero-base byte offset from the file’s beginning. The function performs
the conversion opposite to what bufferpos-to-filepos does. Optional arguments
quality and coding-system have the same meaning and values as for bufferpos-to-
filepos.
multibyte-string-p string [Function]
Return t if string is a multibyte string, nil otherwise. This function also returns nil
if string is some object other than a string.
Chapter 33: Non-ASCII Characters 837
with other multibyte text, because the multibyte representation is more general and can
hold whatever characters the unibyte text has.
When inserting text into a buffer, Emacs converts the text to the buffer’s representation,
as specified by enable-multibyte-characters in that buffer. In particular, when you
insert multibyte text into a unibyte buffer, Emacs converts the text to unibyte, even though
this conversion cannot in general preserve all the characters that might be in the multibyte
text. The other natural alternative, to convert the buffer contents to multibyte, is not
acceptable because the buffer’s representation is a choice made by the user that cannot be
overridden automatically.
Converting unibyte text to multibyte text leaves ASCII characters unchanged, and con-
verts bytes with codes 128 through 255 to the multibyte representation of raw eight-bit
bytes.
Converting multibyte text to unibyte converts all ASCII and eight-bit characters to their
single-byte form, but loses information for non-ASCII characters by discarding all but the
low 8 bits of each character’s codepoint. Converting unibyte text to multibyte and back to
unibyte reproduces the original unibyte text.
The next two functions either return the argument string, or a newly created string with
no text properties.
max-char [Function]
This function returns the largest value that a valid character codepoint can have.
(characterp (max-char))
⇒ t
(characterp (1+ (max-char)))
⇒ nil
In Emacs, each property has a name, which is a symbol, and a set of possible val-
ues, whose types depend on the property; if a character does not have a certain prop-
erty, the value is nil. As a general rule, the names of character properties in Emacs are
produced from the corresponding Unicode properties by downcasing them and replacing
each ‘_’ character with a dash ‘-’. For example, Canonical_Combining_Class becomes
canonical-combining-class. However, sometimes we shorten the names to make their
use easier.
Some codepoints are left unassigned by the UCD—they don’t correspond to any char-
acter. The Unicode Standard defines default values of properties for such codepoints; they
are mentioned below for each property.
Here is the full list of value types for all the character properties that Emacs knows
about:
name Corresponds to the Name Unicode property. The value is a string consisting of
upper-case Latin letters A to Z, digits, spaces, and hyphen ‘-’ characters. For
unassigned codepoints, the value is nil.
general-category
Corresponds to the General_Category Unicode property. The value is a symbol
whose name is a 2-letter abbreviation of the character’s classification. For
unassigned codepoints, the value is Cn.
canonical-combining-class
Corresponds to the Canonical_Combining_Class Unicode property. The value
is an integer. For unassigned codepoints, the value is zero.
bidi-class
Corresponds to the Unicode Bidi_Class property. The value is a symbol whose
name is the Unicode directional type of the character. Emacs uses this property
when it reorders bidirectional text for display (see Section 39.26 [Bidirectional
Display], page 1067). For unassigned codepoints, the value depends on the
code blocks to which the codepoint belongs: most unassigned codepoints get
the value of L (strong L), but some get values of AL (Arabic letter) or R (strong
R).
decomposition
Corresponds to the Unicode properties Decomposition_Type and
Decomposition_Value. The value is a list, whose first element may be a
symbol representing a compatibility formatting tag, such as small2 ; the other
elements are characters that give the compatibility decomposition sequence
of this character. For characters that don’t have decomposition sequences,
and for unassigned codepoints, the value is a list with a single member, the
character itself.
decimal-digit-value
Corresponds to the Unicode Numeric_Value property for characters whose
Numeric_Type is ‘Decimal’. The value is an integer, or nil if the character
2
The Unicode specification writes these tag names inside ‘<..>’ brackets, but the tag names in Emacs do
not include the brackets; e.g., Unicode specifies ‘<small>’ where Emacs uses ‘small’.
Chapter 33: Non-ASCII Characters 842
has no decimal digit value. For unassigned codepoints, the value is nil, which
means NaN, or “not a number”.
digit-value
Corresponds to the Unicode Numeric_Value property for characters whose
Numeric_Type is ‘Digit’. The value is an integer. Examples of such characters
include compatibility subscript and superscript digits, for which the value is
the corresponding number. For characters that don’t have any numeric value,
and for unassigned codepoints, the value is nil, which means NaN.
numeric-value
Corresponds to the Unicode Numeric_Value property for characters whose
Numeric_Type is ‘Numeric’. The value of this property is a number. Examples
of characters that have this property include fractions, subscripts, superscripts,
Roman numerals, currency numerators, and encircled numbers. For example,
the value of this property for the character U+2155 vulgar fraction one
fifth is 0.2. For characters that don’t have any numeric value, and for unas-
signed codepoints, the value is nil, which means NaN.
mirrored Corresponds to the Unicode Bidi_Mirrored property. The value of this prop-
erty is a symbol, either Y or N. For unassigned codepoints, the value is N.
mirroring
Corresponds to the Unicode Bidi_Mirroring_Glyph property. The value of this
property is a character whose glyph represents the mirror image of the char-
acter’s glyph, or nil if there’s no defined mirroring glyph. All the characters
whose mirrored property is N have nil as their mirroring property; however,
some characters whose mirrored property is Y also have nil for mirroring,
because no appropriate characters exist with mirrored glyphs. Emacs uses
this property to display mirror images of characters when appropriate (see
Section 39.26 [Bidirectional Display], page 1067). For unassigned codepoints,
the value is nil.
paired-bracket
Corresponds to the Unicode Bidi_Paired_Bracket property. The value of this
property is the codepoint of a character’s paired bracket, or nil if the character
is not a bracket character. This establishes a mapping between characters that
are treated as bracket pairs by the Unicode Bidirectional Algorithm; Emacs uses
this property when it decides how to reorder for display parentheses, braces, and
other similar characters (see Section 39.26 [Bidirectional Display], page 1067).
bracket-type
Corresponds to the Unicode Bidi_Paired_Bracket_Type property. For charac-
ters whose paired-bracket property is non-nil, the value of this property is a
symbol, either o (for opening bracket characters) or c (for closing bracket char-
acters). For characters whose paired-bracket property is nil, the value is the
symbol n (None). Like paired-bracket, this property is used for bidirectional
display.
Chapter 33: Non-ASCII Characters 843
;; U+2084
(get-char-code-property ?\N{SUBSCRIPT FOUR}
'digit-value)
⇒ 4
;; U+2155
(get-char-code-property ?\N{VULGAR FRACTION ONE FIFTH}
'numeric-value)
⇒ 0.2
;; U+2163
(get-char-code-property ?\N{ROMAN NUMERAL FOUR}
'numeric-value)
⇒ 4
(get-char-code-property ?\( 'paired-bracket)
⇒ 41 ;; closing parenthesis
(get-char-code-property ?\) 'bracket-type)
⇒ c
char-code-property-description prop value [Function]
This function returns the description string of property prop’s value, or nil if value
has no description.
(char-code-property-description 'general-category 'Zs)
⇒ "Separator, Space"
(char-code-property-description 'general-category 'Nd)
⇒ "Number, Decimal Digit"
(char-code-property-description 'numeric-value '1/5)
⇒ nil
put-char-code-property char propname value [Function]
This function stores value as the value of the property propname for the character
char.
unicode-category-table [Variable]
The value of this variable is a char-table (see Section 6.6 [Char-Tables], page 107) that
specifies, for each character, its Unicode General_Category property as a symbol.
char-script-table [Variable]
The value of this variable is a char-table that specifies, for each character, a symbol
whose name is the script to which the character belongs, according to the Unicode
Standard classification of the Unicode code space into script-specific blocks. This
char-table has a single extra slot whose value is the list of all script symbols.
char-width-table [Variable]
The value of this variable is a char-table that specifies the width of each character in
columns that it will occupy on the screen.
printable-chars [Variable]
The value of this variable is a char-table that specifies, for each character, whether it
is printable or not. That is, if evaluating (aref printable-chars char) results in
t, the character is printable, and if it results in nil, it is not.
Chapter 33: Non-ASCII Characters 845
charset-list [Variable]
The value is a list of all defined character set names.
Emacs can convert between its internal representation of a character and the character’s
codepoint in a specific charset. The following two functions support these conversions.
The following function comes in handy for applying a certain function to all or part of
the characters in a charset:
During decoding, the translation table’s translations are applied to the characters that
result from ordinary decoding. If a coding system has the property :decode-translation-
table, that specifies the translation table to use, or a list of translation tables to apply in
sequence. (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 848.) Finally, if standard-translation-table-for-
decode is non-nil, the resulting characters are translated by that table.
During 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 prop-
erty :encode-translation-table, that specifies the translation table to use, or a list of
translation tables to apply in sequence. In addition, if the variable standard-translation-
table-for-encode is non-nil, it specifies the translation table to use for translating the
result.
standard-translation-table-for-decode [Variable]
This is the default translation table for decoding. If a coding systems specifies its own
translation tables, the table that is the value of this variable, if non-nil, is applied
after them.
standard-translation-table-for-encode [Variable]
This is the default translation table for encoding. If a coding systems specifies its own
translation tables, the table that is the value of this variable, if non-nil, is applied
after them.
Chapter 33: Non-ASCII Characters 848
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.
This variable automatically becomes buffer-local when set.
In general, a coding system doesn’t guarantee roundtrip identity: decoding a byte se-
quence using a coding system, then encoding the resulting text in the same coding system,
can produce a different byte sequence. But some coding systems do guarantee that the byte
sequence will be the same as what you originally decoded. Here are a few examples:
iso-8859-1, utf-8, big5, shift jis, euc-jp
Encoding buffer text and then decoding the result can also fail to reproduce the original
text. For instance, if you encode a character with a coding system which does not support
that character, the result is unpredictable, and thus decoding it using the same coding
system may produce a different text. Currently, Emacs can’t report errors that result from
encoding unsupported characters.
End of line conversion handles three different conventions used on various systems for
representing end of line in files. The Unix convention, used on GNU and Unix systems, is to
use the linefeed character (also called newline). The DOS convention, used on MS-Windows
and MS-DOS systems, is to use a carriage return and a linefeed at the end of a line. The
Mac convention is to use just carriage return. (This was the convention used in Classic Mac
OS.)
Base coding systems such as latin-1 leave the end-of-line conversion unspecified, to be
chosen based on the data. Variant coding systems such as latin-1-unix, latin-1-dos and
latin-1-mac specify the end-of-line conversion explicitly as well. Most base coding systems
have three corresponding variants whose names are formed by adding ‘-unix’, ‘-dos’ and
‘-mac’.
The coding system raw-text is special in that it prevents character code conversion,
and causes the buffer visited with this coding system to be a unibyte buffer. For historical
reasons, you can save both unibyte and multibyte text with this coding system. When you
use raw-text to encode multibyte text, it does perform one character code conversion: it
converts eight-bit characters to their single-byte external representation. raw-text 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 (and its alias binary) is equivalent to raw-text-unix: it specifies no
conversion of either character codes or end-of-line.
The coding system utf-8-emacs specifies that the data is represented in the internal
Emacs encoding (see Section 33.1 [Text Representations], page 835). This is like raw-text
in that no code conversion happens, but different in that the result is multibyte data.
The name emacs-internal is an alias for utf-8-emacs-unix (so it forces no conversion of
end-of-line, unlike utf-8-emacs, which can decode all 3 kinds of end-of-line conventions).
buffer-file-coding-system [Variable]
This buffer-local variable records the coding system 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 853). 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.
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 859) 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.
Chapter 33: Non-ASCII Characters 851
The variable selection-coding-system specifies how to encode selections for the win-
dow system. See Section 29.20 [Window System Selections], page 733.
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.
If this function returns a vector, Emacs will decide, as part of the text encoding or
decoding process, what eol conversion to use. For decoding, the end-of-line format
of the text is auto-detected, and the eol conversion is set to match it (e.g., DOS-
style CRLF format will imply dos eol conversion). For encoding, the eol conversion is
taken from the appropriate default coding system (e.g., default value of buffer-file-
coding-system for buffer-file-coding-system), or from the default eol conversion
appropriate for the underlying platform.
coding-system-change-eol-conversion coding-system eol-type [Function]
This function returns a coding system which is like coding-system except for its eol
conversion, which is specified by eol-type. eol-type should be unix, dos, mac, or
nil. If it is nil, the returned coding system determines the end-of-line conversion
from the data.
eol-type may also be 0, 1 or 2, standing for unix, dos and mac, respectively.
coding-system-change-text-conversion eol-coding text-coding [Function]
This function returns a coding system which uses the end-of-line conversion of eol-
coding, and the text conversion of text-coding. If text-coding is nil, it returns
undecided, or one of its variants according to eol-coding.
find-coding-systems-region from to [Function]
This function returns a list of coding systems that could be used to encode a text
between from and to. All coding systems in the list can safely encode any multibyte
characters in that portion of the text.
If the text contains no multibyte characters, the function returns the list (undecided).
find-coding-systems-string string [Function]
This function returns a list of coding systems that could be used to encode the text
of string. All coding systems in the list can safely encode any multibyte characters in
string. If the text contains no multibyte characters, this returns the list (undecided).
find-coding-systems-for-charsets charsets [Function]
This function returns a list of coding systems that could be used to encode all the
character sets in the list charsets.
check-coding-systems-region start end coding-system-list [Function]
This function checks whether coding systems in the list coding-system-list can
encode all the characters in the region between start and end. If all of the coding sys-
tems in the list can encode the specified text, the function returns nil. If some coding
systems cannot encode some of the characters, the value is an alist, each element of
which has the form (coding-system1 pos1 pos2 ...), meaning that coding-system1
cannot encode characters at buffer positions pos1, pos2, . . . .
start may be a string, in which case end is ignored and the returned value references
string indices instead of buffer positions.
detect-coding-region start end &optional highest [Function]
This function chooses a plausible coding system for decoding the text from start to
end. This text should be a byte sequence, i.e., unibyte text or multibyte text with only
ASCII and eight-bit characters (see Section 33.10.7 [Explicit Encoding], page 859).
Chapter 33: Non-ASCII Characters 853
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.
If the region contains null bytes, the value is no-conversion, even if the region
contains text encoded in some coding system.
inhibit-null-byte-detection [Variable]
If this variable has a non-nil value, null bytes are ignored when detecting the encoding
of a region or a string. This allows the encoding of text that contains null bytes to
be correctly detected, such as Info files with Index nodes.
inhibit-iso-escape-detection [Variable]
If this variable has a non-nil value, ISO-2022 escape sequences are ignored when
detecting the encoding of a region or a string. The result is that no text is ever
detected as encoded in some ISO-2022 encoding, and all escape sequences become
visible in a buffer. Warning: Use this variable with extreme caution, because many
files in the Emacs distribution use ISO-2022 encoding.
See [Process Information], page 934, 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.
between from and to. If from is a string, the string specifies the text to encode, and
to is ignored.
If the specified text includes raw bytes (see Section 33.1 [Text Representations],
page 835), select-safe-coding-system suggests raw-text for its encoding.
If default-coding-system is non-nil, that is the first coding system to try; if that
can handle the text, select-safe-coding-system returns that coding system. It
can also be a list of coding systems; then the function tries each of them one by
one. After trying all of them, it next tries the current buffer’s value of buffer-file-
coding-system (if it is not undecided), then the default value of buffer-file-
coding-system and finally the user’s most preferred coding system, which the user
can set using the command prefer-coding-system (see Section “Recognizing Coding
Systems” in The GNU Emacs Manual).
If one of those coding systems can safely encode all the specified text, select-safe-
coding-system chooses it and returns it. Otherwise, it asks the user to choose from
a list of coding systems which can encode all the text, and returns the user’s choice.
default-coding-system can also be a list whose first element is t and whose other
elements are coding systems. Then, if no coding system in the list can handle the
text, select-safe-coding-system queries the user immediately, without trying any
of the three alternatives described above. This is handy for checking only the coding
systems in the list.
The optional argument accept-default-p determines whether a coding system selected
without user interaction is acceptable. If it’s omitted or nil, such a silent selection
is always acceptable. If it is non-nil, it should be a function; select-safe-coding-
system calls this function with one argument, the base coding system of the selected
coding system. If the function returns nil, select-safe-coding-system rejects the
silently selected coding system, and asks the user to select a coding system from a
list of possible candidates.
If the variable select-safe-coding-system-accept-default-p is non-nil, it
should be a function taking a single argument. It is used in place of accept-default-p,
overriding any value supplied for this argument.
As a final step, before returning the chosen coding system, select-safe-coding-
system checks whether that coding system is consistent with what would be selected
if the contents of the region were read from a file. (If not, this could lead to data
corruption in a file subsequently re-visited and edited.) Normally, select-safe-
coding-system uses buffer-file-name as the file for this purpose, but if file is
non-nil, it uses that file instead (this can be relevant for write-region and similar
functions). If it detects an apparent inconsistency, select-safe-coding-system
queries the user before selecting the coding system.
select-safe-coding-system-function [Variable]
This variable names the function to be called to request the user to select a proper cod-
ing system for encoding text when the default coding system for an output operation
cannot safely encode that text. The default value of this variable is select-safe-
coding-system. Emacs primitives that write text to files, such as write-region, or
send text to other processes, such as process-send-region, normally call the value
Chapter 33: Non-ASCII Characters 855
or a cons cell containing two coding systems. This value has the same meaning as
described above.
If coding (or what returned by the above function) is undecided, the normal code-
detection is performed.
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.
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.
The functions in this list could be called either when the file is visited and Emacs
wants to decode its contents, and/or when the file’s buffer is about to be saved and
Emacs wants to determine how to encode its contents.
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.
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.
(let ((coding-system-for-read 'no-conversion))
(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. It also applies to encoding command-line arguments with which
Emacs invokes subprocesses.
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.
coding-system-require-warning [Variable]
Binding coding-system-for-write to a non-nil value prevents output primitives
from calling the function specified by select-safe-coding-system-function (see
Section 33.10.4 [User-Chosen Coding Systems], page 853). This is because C-x
Chapter 33: Non-ASCII Characters 859
Sometimes, you need to prefer several coding systems for some operation, rather than fix
a single one. Emacs lets you specify a priority order for using coding systems. This ordering
affects the sorting of lists of coding systems returned by functions such as find-coding-
systems-region (see Section 33.10.3 [Lisp and Coding Systems], page 851).
The usual way to use the byte sequence that results from explicitly encoding text is to
copy it to a file or process—for example, to write it with write-region (see Section 25.4
[Writing to Files], page 528), and suppress encoding by binding coding-system-for-write
to no-conversion.
Here are the functions to perform explicit encoding or decoding. The encoding functions
produce sequences of bytes; the decoding functions are meant to operate on sequences of
bytes. All of these functions discard text properties. They also set last-coding-system-
used to the precise coding system they used.
encode-coding-region start end coding-system &optional [Command]
destination
This command encodes the text from start to end according to coding system coding-
system. Normally, the encoded text replaces the original text in the buffer, but the
optional argument destination can change that. If destination is a buffer, the encoded
text is inserted in that buffer after point (point does not move); if it is t, the command
returns the encoded text as a unibyte string without inserting it.
If encoded text is inserted in some buffer, this command returns the length of the
encoded text.
The result of encoding is logically a sequence of bytes, but the buffer remains multi-
byte if it was multibyte before, and any 8-bit bytes are converted to their multibyte
representation (see Section 33.1 [Text Representations], page 835).
Do not use undecided for coding-system when encoding text, since that may lead to
unexpected results. Instead, use select-safe-coding-system (see Section 33.10.4
[User-Chosen Coding Systems], page 853) to suggest a suitable encoding, if there’s no
obvious pertinent value for coding-system.
encode-coding-string string coding-system &optional nocopy [Function]
buffer
This function encodes the text in string according to coding system coding-system.
It returns a new string containing the encoded text, except when nocopy is non-nil,
in which case the function may return string itself if the encoding operation is trivial.
The result of encoding is a unibyte string.
decode-coding-region start end coding-system &optional [Command]
destination
This command decodes the text from start to end according to coding system coding-
system. To make explicit decoding useful, the text before decoding ought to be a
sequence of byte values, but both multibyte and unibyte buffers are acceptable (in
the multibyte case, the raw byte values should be represented as eight-bit characters).
Normally, the decoded text replaces the original text in the buffer, but the optional
argument destination can change that. If destination is a buffer, the decoded text
is inserted in that buffer after point (point does not move); if it is t, the command
returns the decoded text as a multibyte string without inserting it.
If decoded text is inserted in some buffer, this command returns the length of the
decoded text. If that buffer is a unibyte buffer (see Section 33.4 [Selecting a Repre-
sentation], page 838), the internal representation of the decoded text (see Section 33.1
[Text Representations], page 835) is inserted into the buffer as individual bytes.
Chapter 33: Non-ASCII Characters 861
This command puts a charset text property on the decoded text. The value of the
property states the character set used to decode the original text.
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...)
Chapter 33: Non-ASCII Characters 863
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
In POSIX, locales 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 mes-
sages and—on X Window system only—keyboard input, for sending batch output
to the standard output and error streams, 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.
If the system can’t provide the requested information, or if item is not one of
those symbols, the value is nil. All strings in the return value are decoded using
locale-coding-system. See Section “Locales” in The GNU Libc Manual, for more
information about locales and locale items.
865
(search-forward "fox")
⇒ 20
If count is a positive number n, the search is done n times; each successive search starts
at the end of the previous match. If all these successive searches succeed, the function
call succeeds, moving point and returning its new value. Otherwise the function call
fails, with results depending on the value of noerror, as described above. If count is a
negative number −n, the search is done n times in the opposite (backward) direction.
pattern. For example, in matching ‘ca*ar’ against the string ‘caaar’, the ‘a*’
first tries to match all three ‘a’s; but the rest of the pattern is ‘ar’ and there is
only ‘r’ left to match, so this try fails. The next alternative is for ‘a*’ to match
only two ‘a’s. With this choice, the rest of the regexp matches successfully.
Warning: Nested repetition operators can run for an indefinitely
long time, if they lead to ambiguous matching. For example, try-
ing to match the regular expression ‘\(x+y*\)*a’ against the string
‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz’ could take hours before it
ultimately fails. Emacs must try each way of grouping the ‘x’s before
concluding that none of them can work. Even worse, ‘\(x*\)*’ can match
the null string in infinitely many ways, so it causes an infinite loop. To avoid
these problems, check nested repetitions carefully, to make sure that they do
not cause combinatorial explosions in backtracking.
‘+’ is a postfix operator, similar to ‘*’ except that it must match the preceding
expression at least once. So, for example, ‘ca+r’ matches the strings ‘car’ and
‘caaaar’ but not the string ‘cr’, whereas ‘ca*r’ matches all three strings.
‘?’ 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). 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. However, the ending character of one range should not be the
starting point of another one; for example, ‘[a-m-z]’ should be avoided.
The usual regexp special characters are not special inside a character alterna-
tive. A completely different set of characters is special inside character alter-
natives: ‘]’, ‘-’ and ‘^’.
Chapter 34: Searching and Matching 870
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 as the upper bound of a range.
Thus, ‘[]-]’ matches both ‘]’ and ‘-’. (As explained below, you cannot use
‘\]’ to include a ‘]’ inside a character alternative, since ‘\’ is not special there.)
To include ‘^’ in a character alternative, put it anywhere but at the beginning.
The following aspects of ranges are specific to Emacs, in that POSIX allows
but does not require this behavior and programs other than Emacs may behave
differently:
1. If case-fold-search is non-nil, ‘[a-z]’ also matches upper-case letters.
2. A range is not affected by the locale’s collation sequence: it always rep-
resents the set of characters with codepoints ranging between those of its
bounds, so that ‘[a-z]’ matches only ASCII letters, even outside the C or
POSIX locale.
3. As a special case, if either bound of a range is a raw 8-bit byte, the other
bound should be a unibyte character, and the range matches only unibyte
characters.
4. If the lower bound of a range is greater than its upper bound, the range is
empty and represents no characters. Thus, ‘[b-a]’ always fails to match,
and ‘[^b-a]’ matches any character, including newline. However, the lower
bound should be at most one greater than the upper bound; for example,
‘[c-a]’ should be avoided.
A character alternative can also specify named character classes (see
Section 34.3.1.2 [Char Classes], page 872). This is a POSIX feature. For
example, ‘[[:ascii:]]’ matches any ASCII character. 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. A character class should not appear as the lower or upper bound
of a range.
‘[^ ... ]’ ‘[^’ 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.
You can specify named character classes, just like in character alternatives.
For instance, ‘[^[:ascii:]]’ matches any non-ASCII character. See
Section 34.3.1.2 [Char Classes], page 872.
‘^’ 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
Chapter 34: Searching and Matching 871
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.
‘[: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 893).
‘[:unibyte:]’
This matches any unibyte character (see Section 33.1 [Text Representations],
page 835).
‘[:upper:]’
This matches any upper-case letter, as determined by the current case table
(see Section 4.9 [Case Tables], page 65). If case-fold-search is non-nil, this
also matches any lower-case letter.
‘[:word:]’
This matches any character that has word syntax (see Section 35.2.1 [Syntax
Class Table], page 893).
‘[:xdigit:]’
This matches the hexadecimal digits: ‘0’ through ‘9’, ‘a’ through ‘f’ and ‘A’
through ‘F’.
‘\b’ matches at the beginning or end of the buffer (or string) regardless of what
text appears next to it.
‘\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 a 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.
symbols The resulting regexp is surrounded by ‘\_<\(’ and ‘\)\_>’ (this is of-
ten appropriate when matching programming-language keywords and the
like).
non-nil The resulting regexp is surrounded by ‘\(’ and ‘\)’.
nil The resulting regexp is surrounded by ‘\(?:’ and ‘\)’, if it is necessary
to ensure that a postfix operator appended to it will apply to the whole
expression.
The resulting regexp of regexp-opt is equivalent to but usually more efficient than
that of a simplified version:
(defun simplified-regexp-opt (strings &optional paren)
(let ((parens
(cond
((stringp paren) (cons paren "\\)"))
((eq paren 'words) '("\\<\\(" . "\\)\\>"))
((eq paren 'symbols) '("\\_<\\(" . "\\)\\_>"))
((null paren) '("\\(?:" . "\\)"))
(t '("\\(" . "\\)")))))
(concat (car parens)
(mapconcat 'regexp-quote strings "\\|")
(cdr parens))))
is not matched by regexp, and leaves point at the end of the first match found. It
returns the new value of point.
If limit is non-nil, it must be a position in the current buffer. It specifies the upper
bound to the search. No match extending after that position is accepted. If limit is
omitted or nil, it defaults to the end of the accessible portion of the buffer.
What re-search-forward does when the search fails depends on the value of noerror:
nil Signal a search-failed error.
t Do nothing and return nil.
anything else
Move point to limit (or the end of the accessible portion of the buffer)
and return nil.
The argument noerror only affects valid searches which fail to find a match. Invalid
arguments cause errors regardless of noerror.
If count is a positive number n, the search is done n times; each successive search starts
at the end of the previous match. If all these successive searches succeed, the function
call succeeds, moving point and returning its new value. Otherwise the function call
fails, with results depending on the value of noerror, as described above. If count is a
negative number −n, the search is done n times in the opposite (backward) direction.
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 ----------
(match-end 0)
⇒ 32
string-match-p regexp string &optional start [Function]
This predicate function does what string-match does, but it avoids modifying the
match data.
looking-at regexp [Function]
This function determines whether the text in the current buffer directly following point
matches the regular expression regexp. “Directly following” means precisely that: the
search is “anchored” and it can succeed only starting with the first character following
point. The result is t if so, nil otherwise.
This function does not move point, but it does update the match data. See
Section 34.6 [Match Data], page 882. If you need to test for a match without
modifying the match data, use looking-at-p, described below.
In this example, point is located directly before the ‘T’. If it were anywhere else, the
result would be nil.
---------- Buffer: foo ----------
I read "?The cat in the hat
comes back" twice.
---------- Buffer: foo ----------
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.
The POSIX search and match functions do not properly support the non-greedy repe-
tition operators (see Section 34.3.1.1 [Regexp Special], page 868). This is because POSIX
backtracking conflicts with the semantics of non-greedy repetition.
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:
‘\&’ This stands for the entire text being replaced.
‘\n’, where n is a digit
This stands for the text that matched the nth subexpression in the
original regexp. Subexpressions are those expressions grouped inside
‘\(...\)’. If the nth subexpression never matched, an empty string is
substituted.
‘\\’ This stands for a single ‘\’ in the replacement text.
‘\?’ This stands for itself (for compatibility with replace-regexp and related
commands; see Section “Regexp Replace” in The GNU Emacs Manual).
Any other character following ‘\’ signals an error.
The substitutions performed by ‘\&’ and ‘\n’ occur after case conversion, if any.
Therefore, 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\)’.
Recall that the subexpressions of a regular expression are those expressions grouped
with escaped parentheses, ‘\(...\)’. The countth subexpression is found by counting oc-
currences of ‘\(’ from the beginning of the whole regular expression. The first subexpression
is numbered 1, the second 2, and so on. Only regular expressions can have subexpressions—
after a simple string search, the only information available is about the entire match.
Every successful search sets the match data. Therefore, you should query the match data
immediately after searching, before calling any other function that might perform another
search. Alternatively, you may save and restore the match data (see Section 34.6.4 [Saving
Match Data], page 886) around the call to functions that could perform another search. Or
use the functions that explicitly do not modify the match data; e.g., string-match-p.
A search which fails may or may not alter the match data. In the current implementation,
it does not, but we may change it in the future. Don’t try to rely on the value of the match
data after a failing search.
match-string count &optional in-string [Function]
This function returns, as a string, the text matched in the last search or match
operation. It returns the entire text if count is zero, or just the portion corresponding
to the countth parenthetical subexpression, if count is positive.
If the last such operation was done against a string with string-match, then you
should pass the same string as the argument in-string. After a buffer search or
match, you should omit in-string or pass nil for it; but you should make sure that the
current buffer when you call match-string is the one in which you did the searching
or matching. Failure to follow this advice will lead to incorrect results.
The value is nil if count is out of range, or for a subexpression inside a ‘\|’ alternative
that wasn’t used or a repetition that repeated zero times.
match-string-no-properties count &optional in-string [Function]
This function is like match-string except that the result has no text properties.
match-beginning count [Function]
If the last regular expression search found a match, this function returns the position
of the start of the matching text or of a subexpression of it.
If count is zero, then the value is the position of the start of the entire match. Oth-
erwise, count specifies a subexpression in the regular expression, and the value of the
function is the starting position of the match for that subexpression.
The value is nil for a subexpression inside a ‘\|’ alternative that wasn’t used or a
repetition that repeated zero times.
match-end count [Function]
This function is like match-beginning except that it returns the position of the end
of the match, rather than the position of the beginning.
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
Chapter 34: Searching and Matching 885
the beginning and end of the match for the first subexpression, and so on. In general,
element number 2n corresponds to (match-beginning n); and element number 2n+1
corresponds to (match-end n).
Normally all the elements are markers or nil, but if integers is non-nil, that means
to use integers instead of markers. (In that case, the buffer itself is appended as
an additional element at the end of the list, to facilitate complete restoration of the
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>)
You could use set-match-data together with match-data to imitate the effect of the
special form save-match-data. Here is how:
(let ((data (match-data)))
(unwind-protect
... ; Ok to change the original match data.
(set-match-data data)))
Emacs automatically saves and restores the match data when it runs process filter func-
tions (see Section 38.9.2 [Filter Functions], page 940) and process sentinels (see Section 38.10
[Sentinels], page 944).
If you want to write a command along the lines of query-replace, you can use
perform-replace to do the work.
of the buffer’s accessible portion is used for end. (If the optional argument backward
is non-nil, the search starts at end and goes backward.)
If query-flag is nil, it replaces all occurrences; otherwise, it asks the user what to do
about each one.
If regexp-flag is non-nil, then from-string is considered a regular expression; oth-
erwise, it must match literally. If delimited-flag is non-nil, then only replacements
surrounded by word boundaries are considered.
The argument replacements specifies what to replace occurrences with. If it is a
string, that string is used. It can also be a list of strings, to be used in cyclic order.
If replacements is a cons cell, (function . data), this means to call function after
each match to get the replacement text. This function is called with two arguments:
data, and the number of replacements already made.
If repeat-count is non-nil, it should be an integer. Then it specifies how many times
to use each of the strings in the replacements list before advancing cyclically to the
next one.
If from-string contains upper-case letters, then perform-replace binds case-fold-
search to nil, and it uses the replacements without altering their case.
Normally, the keymap query-replace-map defines the possible user responses
for queries. The argument map, if non-nil, specifies a keymap to use instead of
query-replace-map.
Non-nil region-noncontiguous-p means that the region between start and end is
composed of noncontiguous pieces. The most common example of this is a rectangular
region, where the pieces are separated by newline characters.
This function uses one of two functions to search for the next occurrence of from-
string. These functions are specified by the values of two variables: replace-re-
search-function and replace-search-function. The former is called when the
argument regexp-flag is non-nil, the latter when it is nil.
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”.
Chapter 34: Searching and Matching 889
exit-prefix
Like exit, but add the key that was pressed to unread-command-events (see
Section 21.8.6 [Event Input Misc], page 404).
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.
undo Undo last replacement and move back to the place where that replacement was
performed.
undo-all Undo all replacements and move back to the place where the first replacement
was performed.
edit Enter a recursive edit to deal with this question—instead of any other action
that would normally be taken.
edit-replacement
Edit the replacement for this question in the minibuffer.
delete-and-edit
Delete the text being considered, then enter a recursive edit to replace it.
recenter
scroll-up
scroll-down
scroll-other-window
scroll-other-window-down
Perform the specified window scroll operation, then ask the same question again.
Only y-or-n-p and related functions use this answer.
quit Perform a quit right away. Only y-or-n-p and related functions use this answer.
help Display some help, then ask again.
multi-query-replace-map [Variable]
This variable holds a keymap that extends query-replace-map by providing ad-
ditional keybindings that are useful in multi-buffer replacements. The additional
bindings are:
automatic-all
Answer this question and all subsequent questions in the series with “yes”,
without further user interaction, for all remaining buffers.
Chapter 34: Searching and Matching 890
exit-current
Answer this question “no”, and give up on the entire series of questions
for the current buffer. Continue to the next buffer in the sequence.
replace-search-function [Variable]
This variable specifies a function that perform-replace calls to search for the next
string to replace. Its default value is search-forward. Any other value should name
a function of 3 arguments: the first 3 arguments of search-forward (see Section 34.1
[String Search], page 865).
replace-re-search-function [Variable]
This variable specifies a function that perform-replace calls to search for the next
regexp to replace. Its default value is re-search-forward. Any other value should
name a function of 3 arguments: the first 3 arguments of re-search-forward (see
Section 34.4 [Regexp Search], page 878).
sentence-end [Function]
This function returns the value of the variable sentence-end, if non-nil.
Otherwise it returns a default value based on the values of the variables
sentence-end-double-space (see [Definition of sentence-end-double-space],
page 787), sentence-end-without-period, and sentence-end-without-space.
892
35 Syntax Tables
A syntax table specifies the syntactic role of each character in a buffer. It can be used
to determine where words, symbols, and other syntactic constructs begin and end. This
information is used by many Emacs facilities, including Font Lock mode (see Section 23.6
[Font Lock Mode], page 487) and the various complex movement commands (see Section 30.2
[Motion], page 743).
Each buffer has its own major mode, and each major mode has its own idea of the syntax
class of various characters. For example, in Lisp mode, the character ‘;’ begins a comment,
but in C mode, it terminates a statement. To support these variations, the syntax table is
local to each buffer. Typically, each major mode has its own syntax table, which it installs
in all buffers that use that mode. For example, the variable emacs-lisp-mode-syntax-
table holds the syntax table used by Emacs Lisp mode, and c-mode-syntax-table holds
the syntax table used by C mode. Changing a major mode’s syntax table alters the syntax
in all of that mode’s buffers, as well as in any buffers subsequently put in that mode.
Occasionally, several similar modes share one syntax table. See Section 23.2.9 [Example
Major Modes], page 469, for an example of how to set up a syntax table.
A syntax table can inherit from another syntax table, which is called its parent syntax
table. A syntax table can leave the syntax class of some characters unspecified, by giving
them the “inherit” syntax class; such a character then acquires the syntax class specified by
the parent syntax table (see Section 35.2.1 [Syntax Class Table], page 893). Emacs defines
a standard syntax table, which is the default parent syntax table, and is also the syntax
table used by Fundamental mode.
standard-syntax-table [Function]
This function returns the standard syntax table, which is the syntax table used in
Fundamental mode.
Syntax tables are not used by the Emacs Lisp reader, which has its own built-in syntactic
rules which cannot be changed. (Some Lisp systems provide ways to redefine the read
syntax, but we decided to leave this feature out of Emacs Lisp for simplicity.)
Chapter 35: Syntax Tables 893
newline This is a comment-end sequence for “a” style, because the newline character
does not have the ‘b’ flag.
• ‘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 900.
Since each buffer has its own current syntax table, we should make that more precise:
with-syntax-table temporarily alters the current syntax table of whichever buffer
is current at the time the macro execution starts. Other buffers are not affected.
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. The list of the positions of the currently open parentheses, starting with the outermost.
10. When the last buffer position scanned was the (potential) first character of a two
character construct (comment delimiter or escaped/char-quoted character pair), the
syntax-code (see Section 35.7 [Syntax Table Internals], page 904) of that position.
Otherwise nil.
Elements 1, 2, and 6 are ignored in a state which you pass as an argument to continue
parsing. Elements 9 and 10 are mainly used internally by the parser code.
One additional piece of useful information is available from a parser state using this
function:
Syntax flags are encoded in higher order bits, starting 16 bits from the least significant
bit. This table gives the power of two which corresponds to each syntax flag.
Prefix Flag Prefix Flag
‘1’ (lsh 1 16) ‘p’ (lsh 1 20)
‘2’ (lsh 1 17) ‘b’ (lsh 1 21)
‘3’ (lsh 1 18) ‘n’ (lsh 1 22)
‘4’ (lsh 1 19) ‘c’ (lsh 1 23)
35.8 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 107). 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 906
category-table [Function]
This function returns the current buffer’s category table.
standard-category-table [Function]
This function returns the standard category table.
907
make-category-table [Function]
This creates and returns an empty category table. In an empty category table, no
categories have been allocated, and no characters belong to any categories.
abbrevs-changed [Variable]
This variable is set non-nil by defining or altering any abbrevs (except system ab-
brevs). This serves as a flag for various Emacs commands to offer to save your
abbrevs.
Chapter 36: Abbrevs and Abbrev Expansion 911
(add-hook 'foo-mode-hook
#'(lambda ()
(add-function :around (local 'abbrev-expand-function)
#'foo-mode-abbrev-expand-function)))
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. It can also be a list of such tables.
abbrev-minor-mode-table-alist [Variable]
The value of this variable is a list of elements of the form (mode . abbrev-table)
where mode is the name of a variable: if the variable is bound to a non-nil value,
then the abbrev-table is active, otherwise it is ignored. abbrev-table can also be a
list of abbrev tables.
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. It is the parent of the local abbrev
table used in Emacs Lisp mode. See Section 36.7 [Abbrev Table Properties], page 914.
:system If non-nil, this property marks the abbrev as a system abbrev. Such abbrevs
are not saved (see Section 36.3 [Abbrev Files], page 910).
:enable-function
If non-nil, this property should be a function of no arguments which returns
nil if the abbrev should not be used and t otherwise.
:case-fixed
If non-nil, this property indicates that the case of the abbrev’s name is signif-
icant and should only match a text with the same pattern of capitalization. It
also disables the code that modifies the capitalization of the expansion.
37 Threads
Emacs Lisp provides a limited form of concurrency, called threads. All the threads in a
given instance of Emacs share the same memory. Concurrency in Emacs Lisp is “mostly
cooperative”, meaning that Emacs will only switch execution between threads at well-
defined times. However, the Emacs thread support has been designed in a way to later
allow more fine-grained concurrency, and correct programs should not rely on cooperative
threading.
Currently, thread switching will occur upon explicit request via thread-yield, when
waiting for keyboard input or for process output from asynchronous processes (e.g., during
accept-process-output), or during blocking operations relating to threads, such as mutex
locking or thread-join.
Emacs Lisp provides primitives to create and control threads, and also to create and
control mutexes and condition variables, useful for thread synchronization.
While global variables are shared among all Emacs Lisp threads, local variables are
not—a dynamic let binding is local. Each thread also has its own current buffer (see
Section 27.2 [Current Buffer], page 581) and its own match data (see Section 34.6 [Match
Data], page 882).
Note that let bindings are treated specially by the Emacs Lisp implementation. There
is no way to duplicate this unwinding and rewinding behavior other than by using let. For
example, a manual implementation of let written using unwind-protect cannot arrange
for variable values to be thread-specific.
In the case of lexical bindings (see Section 12.10 [Variable Scoping], page 179), a closure
is an object like any other in Emacs Lisp, and bindings in a closure are shared by any
threads invoking the closure.
37.2 Mutexes
A mutex is an exclusive lock. At any moment, zero or one threads may own a mutex. If a
thread attempts to acquire a mutex, and the mutex is already owned by some other thread,
then the acquiring thread will block until the mutex becomes available.
Emacs Lisp mutexes are of a type called recursive, which means that a thread can re-
acquire a mutex it owns any number of times. A mutex keeps a count of how many times it
has been acquired, and each acquisition of a mutex must be paired with a release. The last
release by a thread of a mutex reverts it to the unowned state, potentially allowing another
thread to acquire the mutex.
Chapter 37: Threads 917
38 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.
In addition to processes that run programs, Lisp programs can open connections of sev-
eral types to devices or processes running on the same machine or on other machines. The
supported connection types are: TCP and UDP network connections, serial port connec-
tions, and pipe connections. Each such connection is also represented by a process object.
In addition to subprocesses of the current Emacs session, you can also access other
processes running on your machine. See Section 38.12 [System Processes], page 946.
Please note: The argument program contains only the name of the program file; it may
not contain any command-line arguments. You must use a separate argument, args, to
provide those, as described below.
Each of the subprocess-creating functions has a buffer-or-name argument that specifies
where the 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 nil, which
says to discard the output, unless a custom filter function handles it. (See Section 38.9.2
[Filter Functions], page 940, and Chapter 19 [Read and Print], page 323.) Normally, you
should avoid having multiple processes send output to the same buffer because their output
would be intermixed randomly. For synchronous processes, you can send the output to a file
instead of a buffer (and the corresponding argument is therefore more appropriately called
destination). By default, both standard output and standard error streams go to the same
destination, but all the 3 primitives allow optionally to direct the standard error stream to
a different destination.
All three of the subprocess-creating functions allow to specify command-line arguments
for the process to run. For call-process and call-process-region, these come in the
form of a &rest argument, args. For make-process, both the program to run and its
command-line arguments are specified as a list of strings. The command-line arguments
must all be strings, and they are supplied to the program as separate argument strings.
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 inherits its environment from Emacs, but you can specify overrides for
it with process-environment. See Section 40.3 [System Environment], page 1082. The
subprocess gets its current directory from the value of default-directory.
exec-directory [Variable]
The value of this variable is a string, the name of a directory that contains programs
that come with GNU Emacs and are 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.
The following two functions are useful for combining a list of individual command-line
argument strings into a single string, and taking a string apart into a list of individual
command-line arguments. These functions are mainly intended for converting user input in
the minibuffer, a Lisp string, into a list of string arguments to be passed to make-process,
call-process or start-process, or for converting such lists of arguments into a single
Lisp string to be presented in the minibuffer or echo area. Note that if a shell is in-
volved (e.g., if using call-process-shell-command), arguments should still be protected
by shell-quote-argument; combine-and-quote-strings is not intended to protect spe-
cial characters from shell evaluation.
This function supports two types of quoting: enclosing a whole string in double quotes
"...", and quoting individual characters with a backslash escape ‘\’. The latter is
also used in Lisp strings, so this function can handle those as well.
combine-and-quote-strings list-of-strings &optional separator [Function]
This function concatenates list-of-strings into a single string, quoting each string as
necessary. It also sticks the separator string between each pair of strings; if separator
is omitted or nil, it defaults to " ". The return value is the resulting string.
The strings in list-of-strings that need quoting are those that include separator as
their substring. Quoting a string encloses it in double quotes "...". In the simplest
case, if you are consing a command from the individual command-line arguments,
every argument that includes embedded blanks will be quoted.
(see Section 25.12 [Magic File Names], page 559) to obtain an absolute file name as
seen from the remote host’s perspective.
process-file-side-effects [Variable]
This variable indicates whether a call of process-file changes remote files.
By default, this variable is always set to t, meaning that a call of process-file could
potentially change any file on a remote host. When set to nil, a file handler could
optimize its behavior with respect to remote file attribute caching.
You should only ever change this variable with a let-binding; never with setq.
used by Lisp programs for internal purposes (i.e., no user interaction with the subprocess is
required), where significant amounts of data need to be exchanged between the subprocess
and the Lisp program, it is often better to use a pipe, because pipes are more efficient.
Also, the total number of ptys is limited on many systems, and it is good not to waste them
unnecessarily.
If coding is nil, the default rules for finding the coding system will apply.
See Section 33.10.5 [Default Coding Systems], page 855.
:noquery query-flag
Initialize the process query flag to query-flag. See Section 38.11 [Query
Before Exit], page 946.
:stop stopped
If stopped is non-nil, start the process in the stopped state. In the
stopped state, a pipe process does not accept incoming data, but you
can send outgoing data. The stopped state is set by stop-process and
cleared by continue-process (see Section 38.8 [Signals to Processes],
page 936).
:filter filter
Initialize the process filter to filter. If not specified, a default filter will
be provided, which can be changed later. See Section 38.9.2 [Filter Func-
tions], page 940.
:sentinel sentinel
Initialize the process sentinel to sentinel. If not specified, a default sen-
tinel will be used, which can be changed later. See Section 38.10 [Sen-
tinels], page 944.
The original argument list, modified with the actual connection information, is avail-
able via the process-contact function.
If the process object represents a network, serial, or pipe connection, its status changes
to closed; otherwise, it changes to signal, unless the process already exited. See
Section 38.6 [Process Information], page 932.
(delete-process "*shell*")
⇒ nil
:filter The associated value is the process filter function. See Section 38.9.2
[Filter Functions], page 940.
:sentinel
The associated value is the process sentinel function. See Section 38.10
[Sentinels], page 944.
:remote In a connection, the address in internal format of the remote peer.
:local The local address, in internal format.
:service In a server, if you specified t for service, this value is the actual port
number.
:local and :remote are included even if they were not specified explicitly in
make-network-process.
For a serial connection, see make-serial-process and serial-process-configure
for the list of keys. For a pipe connection, see make-pipe-process for the list of keys.
If key is a keyword, the function returns the value corresponding to that keyword.
process-id process [Function]
This function returns the PID of process. This is an integral number that distinguishes
the process process from all other processes running on the same computer at the
current time. The PID of a process is chosen by the operating system kernel when the
process is started and remains constant as long as the process exists. For network,
serial, and pipe connections, this function returns nil.
process-name process [Function]
This function returns the name of process, as a string.
process-status process-name [Function]
This function returns the status of process-name as a symbol. The argument process-
name must be a process, a buffer, or a process name (a string).
The possible values for an actual subprocess are:
run for a process that is running.
stop for a process that is stopped but continuable.
exit for a process that has exited.
signal for a process that has received a fatal signal.
open for a network, serial, or pipe connection that is open.
closed for a network, serial, or pipe connection that is closed. Once a connection
is closed, you cannot reopen it, though you might be able to open a new
connection to the same place.
connect for a non-blocking connection that is waiting to complete.
failed for a non-blocking connection that has failed to complete.
listen for a network server that is listening.
nil if process-name is not the name of an existing process.
Chapter 38: Processes 934
Every process also has a property list that you can use to store miscellaneous values
associated with the process.
think of this function as typing C-c on the terminal by which Emacs talks to the
subprocess.
interrupt-process-functions [Variable]
This variable is a list of functions to be called for interrupt-process. The arguments
of the functions are the same as for interrupt-process. These functions are called
in the order of the list, until one of them returns non-nil. The default function, which
shall always be the last in this list, is internal-default-interrupt-process.
This is the mechanism, how Tramp implements interrupt-process.
Chapter 38: Processes 938
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 read-
ing from such processes, thus allowing them to produce more output before Emacs
tries to read it.
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.
Killing the associated buffer of a process also kills the process. Emacs asks for confir-
mation first, if the process’s process-query-on-exit-flag is non-nil (see Section 38.11
[Query Before Exit], page 946). This confirmation is done by the function process-kill-
buffer-query-function, which is run from kill-buffer-query-functions (see
Section 27.10 [Killing Buffers], page 594).
process-buffer process [Function]
This function returns the associated buffer of the specified process.
(process-buffer (get-process "shell"))
⇒ #<buffer *shell*>
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.11 [Quitting], page 407.
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, errors are not caught. This makes
it possible to use the Lisp debugger to debug filter functions. See Section 18.1 [Debugger],
page 289.
Many filter functions sometimes (or always) insert the output in the process’s buffer,
mimicking the actions of the default filter. Such filter functions need to make sure that
they save the current buffer, select the correct buffer (if different) before inserting output,
and then restore the original buffer. They should also check whether the buffer is still alive,
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)
(when (buffer-live-p (process-buffer proc))
(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)))))))
To make the filter force the process buffer to be visible whenever new text arrives, you
could insert a line like the following 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 from the example and call goto-char unconditionally. Note that this
doesn’t necessarily move the window point. The default filter actually uses insert-before-
markers which moves all markers, including the window point. This may move unrelated
markers, so it’s generally better to move the window point explicitly, or set its insertion
type to t (see Section 28.19 [Window Point], page 660).
Note that Emacs automatically saves and restores the match data while executing filter
functions. See Section 34.6 [Match Data], page 882.
The output to the filter 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
output, make sure to handle the case where one of these strings is split across two or more
batches of output; one way to do this is to insert the received text into a temporary buffer,
which can then be searched.
In case the process’s output needs to be passed to several filters, you can use
add-function to combine an existing filter with a new one. See Section 13.11 [Advising
Functions], page 222.
Here is an example of the use of a filter function:
(defun keep-output (process output)
(setq kept (cons output kept)))
⇒ keep-output
(setq kept nil)
⇒ nil
(set-process-filter (get-process "shell") 'keep-output)
⇒ keep-output
(process-send-string "shell" "ls ~/other\n")
⇒ nil
kept
⇒ ("lewis@slug:$ "
"FINAL-W87-SHORT.MSS backup.otl kolstad.mss~
address.txt backup.psf kolstad.psf
backup.bib~ david.mss resume-Dec-86.mss~
backup.err david.psf resume-Dec.psf
backup.mss dland syllabus.mss
"
"#backups.mss# backup.mss~ kolstad.mss
")
in a Lisp program to explicitly permit output to arrive at a specific point, or even to wait
until output arrives from a process.
accept-process-output &optional process seconds millisec [Function]
just-this-one
This function allows Emacs to read pending output from processes. The output is
given to their filter functions. If process is non-nil then this function does not return
until some output has been received from process or process has closed the connection.
The arguments seconds and millisec let you specify timeout periods. The former speci-
fies a period measured in seconds and the latter specifies one measured in milliseconds.
The two time periods thus specified are added together, and accept-process-output
returns after that much time, even if there is no subprocess output.
The argument millisec is obsolete (and should not be used), because seconds can be
floating point to specify waiting a fractional number of seconds. If seconds is 0, the
function accepts whatever output is pending but does not wait.
If process is a process, and the argument just-this-one is non-nil, only output from
that process is handled, suspending output from other processes until some output
has been received from that process or the timeout expires. If just-this-one is an
integer, also inhibit running timers. This feature is generally not recommended, but
may be necessary for specific applications, such as speech synthesis.
The function accept-process-output returns non-nil if it got output from process,
or from any process if process is nil; this can occur even after a process has exited if
the corresponding connection contains buffered data. The function returns nil if the
timeout expired or the connection was closed before output arrived.
If a connection from a process contains buffered data, accept-process-output can
return non-nil even after the process has exited. Therefore, although the following loop:
;; This loop contains a bug.
(while (process-live-p process)
(accept-process-output process))
will often read all output from process, it has a race condition and can miss some output
if process-live-p returns nil while the connection still contains data. Better is to write
the loop like this:
(while (accept-process-output 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.11 [Quitting], page 407.
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, errors are not caught. This makes it possible to
use the Lisp debugger to debug the sentinel. See Section 18.1 [Debugger], page 289.
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.
Note that Emacs automatically saves and restores the match data while executing sen-
tinels. See Section 34.6 [Match Data], page 882.
In case a process status changes need to be passed to several sentinels, you can use
add-function to combine an existing sentinel with a new one. See Section 13.11 [Advising
Functions], page 222.
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, or nil if it was not.
Chapter 38: Processes 946
user User name corresponding to the process’s effective user ID, a string.
egid The group ID of the effective user ID, a number.
group Group name corresponding to the effective user’s group ID, a string.
comm The name of the command that runs in the process. This is a string that
usually specifies the name of the executable file of the process, without the
leading directories. However, some special system processes can report
strings that do not correspond to an executable file of a program.
state The state code of the process. This is a short string that encodes the
scheduling state of the process. Here’s a list of the most frequently seen
codes:
"D" uninterruptible sleep (usually I/O)
"R" running
"S" interruptible sleep (waiting for some event)
"T" stopped, e.g., by a job control signal
"Z" zombie: a process that terminated, but was not reaped by its
parent
For the full list of the possible states, see the manual page of the ps
command.
ppid The process ID of the parent process, a number.
pgrp The process group ID of the process, a number.
sess The session ID of the process. This is a number that is the process ID of
the process’s session leader.
ttname A string that is the name of the process’s controlling terminal. On Unix
and GNU systems, this is normally the file name of the corresponding
terminal device, such as /dev/pts65.
tpgid The numerical process group ID of the foreground process group that
uses the process’s terminal.
minflt The number of minor page faults caused by the process since its begin-
ning. (Minor page faults are those that don’t involve reading from disk.)
majflt The number of major page faults caused by the process since its begin-
ning. (Major page faults require a disk to be read, and are thus more
expensive than minor page faults.)
cminflt
cmajflt Like minflt and majflt, but include the number of page faults for all
the child processes of the given process.
utime Time spent by the process in the user context, for running
the application’s code. The corresponding value is in the
(high low microsec picosec) format, the same format used by
functions current-time (see Section 40.5 [Time of Day], page 1086) and
file-attributes (see Section 25.6.4 [File Attributes], page 536).
Chapter 38: Processes 948
stime Time spent by the process in the system (kernel) context, for processing
system calls. The corresponding value is in the same format as for utime.
time The sum of utime and stime. The corresponding value is in the same
format as for utime.
cutime
cstime
ctime Like utime, stime, and time, but include the times of all the child pro-
cesses of the given process.
pri The numerical priority of the process.
nice The nice value of the process, a number. (Processes with smaller nice
values get scheduled more favorably.)
thcount The number of threads in the process.
start The time when the process was started, in the same (high low microsec
picosec) format used by file-attributes and current-time.
etime The time elapsed since the process started, in the format (high low mi-
crosec picosec).
vsize The virtual memory size of the process, measured in kilobytes.
rss The size of the process’s resident set, the number of kilobytes occupied
by the process in the machine’s physical memory.
pcpu The percentage of the CPU time used by the process since it started. The
corresponding value is a floating-point number between 0 and 100.
pmem The percentage of the total physical memory installed on the machine
used by the process’s resident set. The value is a floating-point number
between 0 and 100.
args The command-line with which the process was invoked. This is a string
in which individual command-line arguments are separated by blanks;
whitespace characters that are embedded in the arguments are quoted
as appropriate for the system’s shell: escaped by backslash characters on
GNU and Unix, and enclosed in double quote characters on Windows.
Thus, this command-line string can be directly used in primitives such as
shell-command.
none of those values is possible for a real subprocess. See Section 38.6 [Process Information],
page 932.
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—see the :server keyword
of make-network-process, Section 38.17.1 [Network Processes], page 953.) 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.
Emacs can create encrypted network connections, using either built-in or external sup-
port. The built-in support uses the GnuTLS Transport Layer Security Library; see the
GnuTLS project page (https: / / www . gnu . org / software / gnutls / ). If your Emacs
was compiled with GnuTLS support, the function gnutls-available-p is defined and
returns non-nil. For more details, see Section “Overview” in The Emacs-GnuTLS manual.
The external support uses the starttls.el library, which requires a helper utility such
as gnutls-cli to be installed on the system. The open-network-stream function can
transparently handle the details of creating encrypted connections for you, using whatever
support is available.
open-network-stream name buffer host service &rest parameters [Function]
This function opens a TCP connection, with optional encryption, and returns a pro-
cess object that represents the connection.
The name argument specifies the name for the process object. It is modified as
necessary to make it unique.
The buffer argument is the buffer to associate with the connection. Output from
the connection is inserted in the buffer, unless you specify your own filter function to
handle the output. If buffer is nil, it means that the connection is not associated
with any buffer.
The arguments host and service specify where to connect to; host is the host name
(a string), and service is the name of a defined network service (a string) or a port
number (an integer like 80 or an integer string like "80").
The remaining arguments parameters are keyword/argument pairs that are mainly
relevant to encrypted connections:
:nowait boolean
If non-nil, try to make an asynchronous connection.
:type type
The type of connection. Options are:
plain An ordinary, unencrypted connection.
tls
ssl A TLS (Transport Layer Security) connection.
nil
network Start with a plain connection, and if parameters ‘:success’
and ‘:capability-command’ are supplied, try to upgrade to
Chapter 38: Processes 951
:shell-command string-or-nil
If the connection type is shell, this parameter will be interpreted as a
format-spec string that will be executed to make the connection. The
specs available are ‘%s’ for the host name and ‘%p’ for the port number.
For instance, if you want to first ssh to ‘gateway’ before making a plain
connection, then this parameter could be something like ‘ssh gateway nc
%s %p’.
38.16 Datagrams
A datagram connection communicates with individual packets rather than streams of data.
Each call to process-send sends one datagram packet (see Section 38.7 [Input to Processes],
page 935), 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
Chapter 38: Processes 953
using the :remote keyword. You can change it later on by calling set-process-datagram-
address.
38.17.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.
like ‘"80"’ that specifies the port number directly. For a server, it can
also be t, which means to let the system select an unused port number.
:family family
family specifies the address (and protocol) family for communication. nil
means determine the proper address family automatically for the given
host and service. local specifies a Unix socket, in which case host is
ignored. ipv4 and ipv6 specify to use IPv4 and IPv6, respectively.
:use-external-socket use-external-socket
If use-external-socket is non-nil use any sockets passed to Emacs on
invocation instead of allocating one. This is used by the Emacs server
code to allow on-demand socket activation. If Emacs wasn’t passed a
socket, this option is silently ignored.
:local local-address
For a server process, local-address is the address to listen on. It overrides
family, host and service, so you might 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, so you might 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
integers [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 match-
ing "open" (if successful) or "failed". The default is to block, so that
make-network-process does not return until the connection has suc-
ceeded or failed.
If you’re setting up an asynchronous TLS connection, you have to also
provide the :tls-parameters parameter (see below).
Chapter 38: Processes 955
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.
: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.
(:nowait t)
Non-nil if non-blocking connect is supported.
(:type datagram)
Non-nil if datagrams are supported.
(:family local)
Non-nil if local (a.k.a. “UNIX domain”) sockets are supported.
(:family ipv6)
Non-nil if IPv6 is supported.
(:service t)
Non-nil if the system can select the port for a server.
To test for the availability of a given network option, use featurep like this:
(featurep 'make-network-process 'keyword)
The accepted keyword values are :bindtodevice, etc. For the complete list, see
Section 38.17.2 [Network Options], page 956. This form returns non-nil if that particular
network option is supported by make-network-process (or set-network-process-
option).
Chapter 38: Processes 958
:filter filter
Install filter as the process filter.
:sentinel sentinel
Install sentinel as the process sentinel.
:plist plist
Install plist as the initial plist of the process.
:bytesize
:parity
:stopbits
:flowcontrol
These are handled by serial-process-configure, which is called by
make-serial-process.
The original argument list, possibly modified by later configuration, is available via
the function process-contact.
Here is an example:
(make-serial-process :port "/dev/ttyS0" :speed 9600)
:process process
:name name
:buffer buffer
:port port
Any of these arguments can be given to identify the process that is to
be configured. If none of these arguments is given, the current buffer’s
process is used.
:speed speed
The speed of the serial port in bits per second, a.k.a. baud rate. The
value can be any number, but most serial ports work only at a few defined
values between 1200 and 115200, with 9600 being the most common value.
If speed is nil, the function ignores all other arguments and does not
configure the port. This may be useful for special serial ports such as
Bluetooth-to-serial converters, which can only be configured through ‘AT’
commands sent through the connection. The value of nil for speed is
valid only for connections that were already opened by a previous call to
make-serial-process or serial-term.
:bytesize bytesize
The number of bits per byte, which can be 7 or 8. If bytesize is not given
or nil, it defaults to 8.
Chapter 38: Processes 961
:parity parity
The value can be nil (don’t use parity), the symbol odd (use odd parity),
or the symbol even (use even parity). If parity is not given, it defaults
to no parity.
:stopbits stopbits
The number of stopbits used to terminate a transmission of each byte.
stopbits can be 1 or 2. If stopbits is not given or nil, it defaults to 1.
:flowcontrol flowcontrol
The type of flow control to use for this connection, which is either nil
(don’t use flow control), the symbol hw (use RTS/CTS hardware flow
control), or the symbol sw (use XON/XOFF software flow control). If
flowcontrol is not given, it defaults to no flow control.
Internally, make-serial-process calls serial-process-configure for the initial
configuration of the serial port.
u16r
u24r
u32r Unsigned integer in little endian order, with length 2, 3 and 4, respectively.
str len String of length len.
strz len Zero-terminated string, in a fixed-size field with length len.
vec len [type]
Vector of len elements of type type, defaulting to bytes. The type is any of the
simple types above, or another vector specified as a list of the form (vec len
[type]).
ip Four-byte vector representing an Internet address. For example: [127 0 0 1]
for localhost.
bits len List of set bits in len bytes. The bytes are taken in big endian order and the bits
are numbered starting with 8 * len − 1 and ending with zero. For example:
bits 2 unpacks #x28 #x1c to (2 3 4 11 13) and #x1c #x28 to (3 5 10 11 12).
(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), where name is optional.
Don’t use names that are symbols meaningful as type specifications (above) or handler spec-
ifications (below), since that would be ambiguous. name can be a symbol or an 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:
For the (eval form) forms used in a bindat specification, the form can access and update
these dynamically bound variables during evaluation:
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"
(defun rfc868-payload ()
(bindat-pack
'((now-hi u16)
(now-lo u16))
;; Emacs uses Unix epoch, while RFC868 epoch
;; is 1900-01-01 00:00:00, which is 2208988800
;; (or #x83aa7e80) seconds more.
(let ((now (time-add nil '(#x83aa #x7e80))))
`((now-hi . ,(car now))
(now-lo . ,(cadr now))))))
Chapter 38: Processes 965
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 is:
(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)))
966
(setq packet-spec
'((header struct header-spec)
(counters vec 2 u32r) ; little endian order
(items u8)
(fill 3)
(item repeat (items)
(struct data-spec))))
A binary data representation is:
(setq binary-data
[ 192 168 1 100 192 168 1 101 01 28 21 32
160 134 1 0 5 1 0 0 2 0 0 0
2 3 0 5 ?A ?B ?C ?D ?E ?F 0 0 1 2 3 4 5 0 0 0
1 4 0 7 ?B ?C ?D ?E ?F ?G 0 0 6 7 8 9 10 11 12 0 ])
The corresponding decoded structure is:
(setq decoded (bindat-unpack packet-spec binary-data))
⇒
((header
(dest-ip . [192 168 1 100])
(src-ip . [192 168 1 101])
(dest-port . 284)
(src-port . 5408))
(counters . [100000 261])
(items . 2)
(item ((data . [1 2 3 4 5])
(id . "ABCDEF")
(length . 5)
(opcode . 3)
(type . 2))
((data . [6 7 8 9 10 11 12])
(id . "BCDEFG")
(length . 7)
(opcode . 4)
(type . 1))))
An example of fetching data from this structure:
(bindat-get-field decoded 'item 1 'id)
⇒ "BCDEFG"
967
39 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.
In Emacs, processing user input takes priority over redisplay. If you call these functions
when input is available, they don’t redisplay immediately, but the requested redisplay does
happen eventually—after all the input has been processed.
On text terminals, suspending and resuming Emacs normally 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.
Although redisplay tries immediately to redisplay, it does not change how Emacs de-
cides which parts of its frame(s) to redisplay. By contrast, the following function adds cer-
tain windows to the pending redisplay work (as if their contents had completely changed),
but does not immediately try to perform redisplay.
Chapter 39: Emacs Display 968
39.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 785.
On a graphical display, tiny arrow images in the window fringes indicate truncated
and continued lines (see Section 39.13 [Fringes], page 1019). 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 39.22.2 [Display Tables], page 1060).
truncate-lines [User Option]
If this buffer-local variable is non-nil, lines that extend beyond the right edge of
the window are truncated; otherwise, they are continued. As a special exception,
the variable truncate-partial-width-windows takes precedence in partial-width
windows (i.e., windows that do not occupy the entire frame width).
truncate-partial-width-windows [User Option]
This variable controls line truncation in partial-width windows. A partial-width win-
dow is one that does not occupy the entire frame width (see Section 28.6 [Splitting
Windows], page 613). If the value is nil, line truncation is determined by the vari-
able truncate-lines (see above). If the value is an integer n, lines are truncated
if the partial-width window has fewer than n columns, regardless of the value of
truncate-lines; if the partial-width window has n or more columns, line truncation
is determined by truncate-lines. For any other non-nil value, lines are truncated
in every partial-width window, regardless of the value of truncate-lines.
When horizontal scrolling (see Section 28.23 [Horizontal Scrolling], page 669) is in use
in a window, that forces truncation.
Chapter 39: Emacs Display 969
wrap-prefix [Variable]
If this buffer-local variable is non-nil, it defines a wrap prefix which Emacs displays
at the start of every continuation line. (If lines are truncated, wrap-prefix is never
used.) Its value may be a string or an image (see Section 39.16.4 [Other Display
Specs], page 1031), or a stretch of whitespace such as specified by the :width or
:align-to display properties (see Section 39.16.2 [Specified Space], page 1029). The
value is interpreted in the same way as a display text property. See Section 39.16
[Display Property], page 1028.
A wrap prefix may also be specified for regions of text, using the wrap-prefix text
or overlay property. This takes precedence over the wrap-prefix variable. See
Section 32.19.4 [Special Properties], page 808.
line-prefix [Variable]
If this buffer-local variable is non-nil, it defines a line prefix which Emacs displays
at the start of every non-continuation line. Its value may be a string or an image
(see Section 39.16.4 [Other Display Specs], page 1031), or a stretch of whitespace
such as specified by the :width or :align-to display properties (see Section 39.16.2
[Specified Space], page 1029). The value is interpreted in the same way as a display
text property. See Section 39.16 [Display Property], page 1028.
A line prefix may also be specified for regions of text using the line-prefix text
or overlay property. This takes precedence over the line-prefix variable. See
Section 32.19.4 [Special Properties], page 808.
In batch mode, the message is printed to the standard error stream, followed by a
newline.
When inhibit-message is non-nil, no message will be displayed in the echo area, it
will only be logged to ‘*Messages*’.
If format-string is nil or the empty string, message clears the echo area; if the
echo area has been expanded automatically, this brings it back to its normal size.
If the minibuffer is active, this brings the minibuffer contents back onto the screen
immediately.
(message "Reverting `%s'..." (buffer-name))
a Reverting ‘subr.el’...
⇒ "Reverting ‘subr.el’..."
inhibit-message [Variable]
When this variable is non-nil, message and related functions will not use the Echo
Area to display messages.
If min-value and max-value are numbers, you can give the argument current-value a
numerical value specifying the initial progress; if omitted, this defaults to min-value.
The remaining arguments control the rate of echo area updates. The progress reporter
will wait for at least min-change more percents of the operation to be completed before
printing next message; the default is one percent. min-time specifies the minimum
time in seconds to pass between successive prints; the default is 0.2 seconds. (On
some operating systems, the progress reporter may handle fractions of seconds with
varying precision).
This function calls progress-reporter-update, so the first message is printed im-
mediately.
You can rewrite the example in the beginning of this node using this macro this way:
(dotimes-with-progress-reporter
(k 500)
"Collecting some mana for Emacs..."
(sit-for 0.01))
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.
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.
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.11 [Minibuffer Windows], page 364).
condition-case, the user won’t see the error message; it could show the message to the
user by reporting it as a warning.)
Each warning has a warning type to classify it. The type is a list of symbols. The
first symbol should be the custom group that you use for the program’s user options.
For example, byte compiler warnings use the warning type (bytecomp). You can also
subcategorize the warnings, if you wish, by using more symbols in the list.
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
Chapter 39: Emacs Display 976
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.
delayed-warnings-list [Variable]
The value of this variable is a list of warnings to be displayed after the current
command has finished. Each element must be a list
(type message [level [buffer-name]])
with the same form, and the same meanings, as the argument list of
display-warning (see Section 39.5.1 [Warning Basics], page 974). Immediately after
running post-command-hook (see Section 21.1 [Command Overview], page 368), the
Emacs command loop displays all the warnings specified by this variable, then resets
it to nil.
Programs which need to further customize the delayed warnings mechanism can change
the variable delayed-warnings-hook:
delayed-warnings-hook [Variable]
This is a normal hook which is run by the Emacs command loop, after post-command-
hook, in order to process and display delayed warnings.
Its default value is a list of two functions:
(collapse-delayed-warnings display-delayed-warnings)
The function collapse-delayed-warnings removes repeated entries from
delayed-warnings-list. The function display-delayed-warnings calls
display-warning on each of the entries in delayed-warnings-list, in turn, and
then sets delayed-warnings-list to nil.
and subsequently make various subsets visible or invisible by changing the value of
buffer-invisibility-spec.
Controlling visibility with buffer-invisibility-spec is especially useful in a program
to display the list of entries in a database. It permits the implementation of convenient
filtering commands to view just a part of the entries in the database. Setting this variable
is very fast, much faster than scanning all the text in the buffer looking for properties to
change.
buffer-invisibility-spec [Variable]
This variable specifies which kinds of invisible properties actually make a character
invisible. Setting this variable makes it buffer-local.
t A character is invisible if its invisible property is non-nil. This is the
default.
a list Each element of the list specifies a criterion for invisibility; if a charac-
ter’s invisible property fits any one of these criteria, the character is
invisible. The list can have two kinds of elements:
atom A character is invisible if its invisible property value is
atom or if it is a list with atom as a member; comparison is
done with eq.
(atom . t)
A character is invisible if its invisible property value is
atom or if it is a list with atom as a member; comparison
is done with eq. Moreover, a sequence of such characters
displays as an ellipsis.
'invisible 'my-symbol)
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.
selective-display [Variable]
This buffer-local variable enables selective display. This means that lines, or portions
of lines, may be made hidden.
• If the value of selective-display is t, then the character control-m marks the
start of hidden text; the control-m, and the rest of the line following it, are not
displayed. This is explicit selective display.
• If the value of selective-display is a positive integer, then lines that start with
more than that many columns of indentation are not displayed.
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 a
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.
Chapter 39: Emacs Display 981
(setq selective-display 2)
⇒ 2
If the forms in body do not change the major mode in the output buffer, so that it
is still Help mode at the end of their execution, then with-output-to-temp-buffer
makes this buffer read-only at the end, and also scans it for function and variable
names to make them into clickable cross-references. See [Tips for Documentation
Strings], page 1149, in particular the item on hyperlinks in documentation strings,
for more details.
The string buffer-name specifies the temporary buffer, which need not already exist.
The argument must be a string, not a buffer. The buffer is erased initially (with no
questions asked), and it is marked as unmodified after with-output-to-temp-buffer
exits.
with-output-to-temp-buffer binds standard-output to the temporary buffer,
then it evaluates the forms in body. Output using the Lisp output functions within
body goes by default to that buffer (but screen display and messages in the echo
area, although they are “output” in the general sense of the word, are not affected).
See Section 19.5 [Output Functions], page 329.
Several hooks are available for customizing the behavior of this construct; they are
listed below.
The value of the last form in body is returned.
---------- Buffer: foo ----------
This is the contents of foo.
---------- Buffer: foo ----------
(with-output-to-temp-buffer "foo"
(print 20)
(print standard-output))
⇒ #<buffer foo>
20
#<buffer foo>
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.
with-temp-buffer-window buffer-or-name action quit-function [Macro]
body. . .
This macro is similar to with-output-to-temp-buffer. Like that construct, it ex-
ecutes body while arranging to insert any output it prints into the buffer named
buffer-or-name and displays that buffer in some window. Unlike with-output-to-
temp-buffer, however, it does not automatically switch that buffer to Help mode.
The argument buffer-or-name specifies the temporary buffer. It can be either a buffer,
which must already exist, or a string, in which case a buffer of that name is created,
if necessary. The buffer is marked as unmodified and read-only when with-temp-
buffer-window exits.
This macro does not call temp-buffer-show-function. Rather, it passes the action
argument to display-buffer (see Section 28.13.1 [Choosing Window], page 630) in
order to display the buffer.
The value of the last form in body is returned, unless the argument quit-function
is specified. In that case, it is called with two arguments: the window showing the
buffer and the result of body. The final return value is then whatever quit-function
returns.
This macro uses the normal hooks temp-buffer-window-setup-hook and
temp-buffer-window-show-hook in place of the analogous hooks run by
with-output-to-temp-buffer.
The two constructs described next are mostly identical to with-temp-buffer-window
but differ from it as specified:
with-current-buffer-window buffer-or-name action quit-function [Macro]
&rest body
This macro is like with-temp-buffer-window but unlike that makes the buffer spec-
ified by buffer-or-name current for running body.
with-displayed-buffer-window buffer-or-name action quit-function [Macro]
&rest body
This macro is like with-current-buffer-window but unlike that displays the buffer
specified by buffer-or-name before running body.
A window showing a temporary buffer can be fitted to the size of that buffer using the
following mode:
temp-buffer-resize-mode [User Option]
When this minor mode is enabled, windows showing a temporary buffer are automat-
ically resized to fit their buffer’s contents.
A window is resized if and only if it has been specially created for the buffer. In
particular, windows that have shown another buffer before are not resized. By de-
fault, this mode uses fit-window-to-buffer (see Section 28.4 [Resizing Windows],
Chapter 39: Emacs Display 984
page 608) for resizing. You can specify a different function by customizing the options
temp-buffer-max-height and temp-buffer-max-width below.
The following function uses the current buffer for temporary display:
(momentary-string-display
"**** Important Message! ****"
(point) ?\r
"Type RET when done reading")
⇒ t
Chapter 39: Emacs Display 985
39.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.
The visual effect of an overlay is the same as of the corresponding text property (see
Section 32.19 [Text Properties], page 802). However, due to a different implementation,
overlays generally don’t scale well (many operations take a time that is proportional to
the number of overlays in the buffer). If you need to affect the visual appearance of many
portions in the buffer, we recommend using text properties.
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.
from the overlay. If rear-advance is non-nil, text inserted at the end of the overlay
is included in the overlay.
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.
overlay-recenter pos [Function]
This function recenters the overlays of the current buffer around position pos. That
makes overlay lookup faster for positions near pos, but slower for positions far away
from pos.
A loop that scans the buffer forwards, creating overlays, can run faster if you do
(overlay-recenter (point-max)) first.
the other. (For the face property, the higher priority overlay’s value does not
completely override the other value; instead, its face attributes override the face
attributes of the lower priority face property.) If two overlays have the same
priority value, and one is nested in the other, then the inner one will prevail
over the outer one. If neither is nested in the other then you should not make
assumptions about which overlay will prevail.
Currently, all overlays take priority over text properties.
Note that Emacs sometimes uses non-numeric priority values for some of its
internal overlays, so do not try to do arithmetic on the priority of an overlay
(unless it is one that you created). In particular, the overlay used for showing
the region uses a priority value of the form (primary . secondary), where the
primary value is used as described above, and secondary is the fallback value
used when primary and the nesting considerations fail to resolve the precedence
between overlays. However, you are advised not to design Lisp programs based
on this implementation detail; if you need to put overlays in priority order, use
the sorted argument of overlays-at. See Section 39.9.3 [Finding Overlays],
page 992.
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 appearance of the text (see Section 39.12 [Faces],
page 997). The value of the property can be the following:
• A face name (a symbol or string).
• An anonymous face: a property list of the form (keyword value ...),
where each keyword is a face attribute name and value is a value for that
attribute.
• A list of faces. Each list element should be either a face name or an
anonymous face. This specifies a face which is an aggregate of the attributes
of each of the listed faces. Faces occurring earlier in the list have higher
priority.
• A cons cell of the form (foreground-color . color-name) or
(background-color . color-name). This specifies the foreground
or background color, similar to (:foreground color-name) or
(:background color-name). This form is supported for backward
compatibility only, and should be avoided.
mouse-face
This property is used instead of face when the mouse is within the range of
the overlay. However, Emacs ignores all face attributes from this property that
alter the text size (e.g., :height, :weight, and :slant). Those attributes are
always the same as in the unhighlighted text.
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
Chapter 39: Emacs Display 990
isearch-open-invisible
This property tells incremental search how to make an invisible overlay visible,
permanently, if the final match overlaps it. See Section 39.6 [Invisible Text],
page 977.
isearch-open-invisible-temporary
This property tells incremental search how to make an invisible overlay visible,
temporarily, during the search. See Section 39.6 [Invisible Text], page 977.
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.
line-prefix
This property specifies a display spec to prepend to each non-continuation line
at display-time. See Section 39.3 [Truncation], page 968.
wrap-prefix
This property specifies a display spec to prepend to each continuation line at
display-time. See Section 39.3 [Truncation], page 968.
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 (see
Section 39.9.1 [Managing Overlays], page 985) a non-nil evaporate property,
that deletes it immediately. Note that, unless an overlay has this property, it
will not be deleted when the text between its starting and ending positions is
deleted from the buffer.
keymap If this property is non-nil, it specifies a keymap for a portion of the text.
This keymap is used when the character after point is within the overlay, and
takes precedence over most other keymaps. See Section 22.7 [Active Keymaps],
page 422.
local-map
The local-map property is similar to keymap but replaces the buffer’s local
map rather than augmenting existing keymaps. This also means it has lower
precedence than minor mode keymaps.
The keymap and local-map properties do not affect a string displayed by the
before-string, after-string, or display properties. This is only relevant for mouse
clicks and other mouse events that fall on the string, since point is never on the string. To
bind special mouse events for the string, assign it a keymap or local-map text property.
See Section 32.19.4 [Special Properties], page 808.
Chapter 39: Emacs Display 992
The following function returns the size in pixels of text as if it were displayed in a given
window. This function is used by fit-window-to-buffer and fit-frame-to-buffer (see
Section 28.4 [Resizing Windows], page 608) to make a window exactly as large as the text
it contains.
The optional argument from, if non-nil, specifies the first text position to consider
and defaults to the minimum accessible position of the buffer. If from is t, it uses the
minimum accessible position that is not a newline character. The optional argument
to, if non-nil, specifies the last text position to consider and defaults to the maximum
accessible position of the buffer. If to is t, it uses the maximum accessible position
that is not a newline character.
The optional argument x-limit, if non-nil, specifies the maximum pixel-width that
can be returned. x-limit nil or omitted, means to use the pixel-width of window’s
body (see Section 28.3 [Window Sizes], page 603); this is useful when the caller does
not intend to change the width of window. Otherwise, the caller should specify here
the maximum width window’s body may assume. Text whose x-coordinate is beyond
x-limit is ignored. Since calculating the width of long lines can take some time, it’s
always a good idea to make this argument as small as needed; in particular, if the
buffer might contain long lines that will be truncated anyway.
The optional argument y-limit, if non-nil, specifies the maximum pixel-height that
can be returned. Text lines whose y-coordinate is beyond y-limit are ignored. Since
calculating the pixel-height of a large buffer can take some time, it makes sense to
specify this argument; in particular, if the caller does not know the size of the buffer.
The optional argument mode-and-header-line nil or omitted means to not include
the height of the mode- or header-line of window in the return value. If it is either the
symbol mode-line or header-line, include only the height of that line, if present, in
the return value. If it is t, include the height of both, if present, in the return value.
window-text-pixel-size treats the text displayed in a window as a whole and does
not care about the size of individual lines. The following function does.
window-lines-pixel-dimensions &optional window first last body [Function]
inverse left
This function calculates the pixel dimensions of each line displayed in the specified
window. It does so by walking window’s current glyph matrix—a matrix storing
the glyph (see Section 39.22.4 [Glyphs], page 1062) of each buffer character currently
displayed in window. If successful, it returns a list of cons pairs representing the x- and
y-coordinates of the lower right corner of the last character of each line. Coordinates
are measured in pixels from an origin (0, 0) at the top-left corner of window. window
must be a live window and defaults to the selected one.
If the optional argument first is an integer, it denotes the index (starting with 0) of
the first line of window’s glyph matrix to be returned. Note that if window has a
header line, the line with index 0 is that header line. If first is nil, the first line to
be considered is determined by the value of the optional argument body: If body is
non-nil, this means to start with the first line of window’s body, skipping any header
line, if present. Otherwise, this function will start with the first line of window’s glyph
matrix, possibly the header line.
If the optional argument last is an integer, it denotes the index of the last line of
window’s glyph matrix that shall be returned. If last is nil, the last line to be
considered is determined by the value of body: If body is non-nil, this means to use
the last line of window’s body, omitting window’s mode line, if present. Otherwise,
this means to use the last line of window which may be the mode line.
Chapter 39: Emacs Display 995
The optional argument inverse, if nil, means that the y-pixel value returned for any
line specifies the distance in pixels from the left edge (body edge if body is non-nil)
of window to the right edge of the last glyph of that line. inverse non-nil means that
the y-pixel value returned for any line specifies the distance in pixels from the right
edge of the last glyph of that line to the right edge (body edge if body is non-nil) of
window. This is useful for determining the amount of slack space at the end of each
line.
The optional argument left, if non-nil means to return the x- and y-coordinates of
the lower left corner of the leftmost character on each line. This is the value that
should be used for windows that mostly display text from right to left.
If left is non-nil and inverse is nil, this means that the y-pixel value returned for
any line specifies the distance in pixels from the left edge of the last (leftmost) glyph
of that line to the right edge (body edge if body is non-nil) of window. If left and
inverse are both non-nil, the y-pixel value returned for any line specifies the distance
in pixels from the left edge (body edge if body is non-nil) of window to the left edge
of the last (leftmost) glyph of that line.
This function returns nil if the current glyph matrix of window is not up-to-date
which usually happens when Emacs is busy, for example, when processing a command.
The value should be retrievable though when this function is run from an idle timer
with a delay of zero seconds.
line-pixel-height [Function]
This function returns the height in pixels of the line at point in the selected win-
dow. The value includes the line spacing of the line (see Section 39.11 [Line Height],
page 995).
When a buffer is displayed with line numbers (see Section “Display Custom” in The
GNU Emacs Manual), it is sometimes useful to know the width taken for displaying the
line numbers. The following function is for Lisp programs which need this information for
layout calculations.
line-number-display-width &optional pixelwise [Function]
This function returns the width used for displaying the line numbers in the selected
window. If the optional argument pixelwise is the symbol columns, the return value
is a float number of the frame’s canonical columns; if pixelwise is t or any other
non-nil value, the value is an integer and is measured in pixels. If pixelwise is
omitted or nil, the value is the integer number of columns of the font defined for the
line-number face, and doesn’t include the 2 columns used to pad the numbers on
display. If line numbers are not displayed in the selected window, the value is zero
regardless of the value of pixelwise. Use with-selected-window (see Section 28.9
[Selecting Windows], page 622) if you need this information about another window.
doesn’t include a final newline.) That is the default line height, if you do nothing to specify
a greater height. (In the most common case, this equals the height of the corresponding
frame’s default font, see Section 29.3.2 [Frame Font], page 694.)
There are several ways to explicitly specify a larger line height, either by specifying an
absolute height for the display line, or by specifying vertical space. However, no matter
what you specify, the actual line height can never be less than the default.
A newline can have a line-height text or overlay property that controls the total height
of the display line ending in that newline.
If the property value is t, the newline character has no effect on the displayed height
of the line—the visible contents alone determine the height. The line-spacing property,
described below, is also ignored in this case. This is useful for tiling small images (or image
slices) without adding blank areas between the images.
If the property value is a list of the form (height total), that adds extra space below
the display line. First Emacs uses height as a height spec to control extra space above the
line; then it adds enough space below the line to bring the total line height up to total. In
this case, any value of line-spacing property for the newline is ignored.
Any other kind of property value is a height spec, which translates into a number—the
specified line height. There are several ways to write a height spec; here’s how each of them
translates into a number:
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.
On graphical terminals, you can specify the line spacing for all lines in a frame, using the
line-spacing frame parameter (see Section 29.4.3.4 [Layout Parameters], page 707). How-
ever, if the default value of line-spacing is non-nil, it overrides the frame’s line-spacing
parameter. An integer specifies the number of pixels put below lines. A floating-point num-
ber 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 specifies the number of pixels put below lines. A floating-point number
Chapter 39: Emacs Display 997
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 can enlarge
the default frame line spacing and the buffer local line-spacing variable: if its value is
larger than the buffer or frame defaults, that larger value is used instead, 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.
On text terminals, the line spacing cannot be altered.
39.12 Faces
A face is a collection of graphical attributes for displaying text: font, foreground color,
background color, optional underlining, etc. Faces control how Emacs displays text in
buffers, as well as other parts of the frame such as the mode line.
One way to represent a face is as a property list of attributes, like (:foreground "red"
:weight bold). Such a list is called an anonymous face. For example, you can assign an
anonymous face as the value of the face text property, and Emacs will display the underlying
text with the specified attributes. See Section 32.19.4 [Special Properties], page 808.
More commonly, a face is referred to via a face name: a Lisp symbol associated
with a set of face attributes1 . Named faces are defined using the defface macro (see
Section 39.12.2 [Defining Faces], page 1001). Emacs comes with several standard named
faces (see Section 39.12.8 [Basic Faces], page 1010).
Many parts of Emacs require named faces, and do not accept anonymous faces. These in-
clude the functions documented in Section 39.12.3 [Attribute Functions], page 1003, and the
variable font-lock-keywords (see Section 23.6.2 [Search-based Fontification], page 489).
Unless otherwise stated, we will use the term face to refer only to named faces.
:family Font family name (a string). See Section “Fonts” in The GNU Emacs Manual,
for more information about font families. The function font-family-list (see
below) returns a list of available family names.
:foundry The name of the font foundry for the font family specified by the :family
attribute (a string). See Section “Fonts” in The GNU Emacs Manual.
:width Relative character width. This should be one of the symbols ultra-condensed,
extra-condensed, condensed, semi-condensed, normal, semi-expanded,
expanded, extra-expanded, or ultra-expanded.
:height The height of the font. In the simplest case, this is an integer in units of 1/10
point.
The value can also be floating point or a function, which specifies the height rel-
ative to an underlying face (see Section 39.12.4 [Displaying Faces], page 1006).
A floating-point value specifies the amount by which to scale the height of the
underlying face. A function value is called with one argument, the height of
the underlying face, and returns the height of the new face. If the function is
passed an integer argument, it must return an integer.
The height of the default face must be specified using an integer; floating point
and function values are not allowed.
:foreground
Foreground color, a string. The value can be a system-defined color name, or
a hexadecimal color specification. See Section 29.22 [Color Names], page 735.
On black-and-white displays, certain shades of gray are implemented by stipple
patterns.
:distant-foreground
Alternative foreground color, a string. This is like :foreground but the color is
only used as a foreground when the background color is near to the foreground
that would have been used. This is useful for example when marking text (i.e.,
the region face). If the text has a foreground that is visible with the region face,
that foreground is used. If the foreground is near the region face background,
:distant-foreground is used instead so the text is readable.
:background
Background color, a string. The value can be a system-defined color name, or
a hexadecimal color specification. See Section 29.22 [Color Names], page 735.
Chapter 39: Emacs Display 999
:underline
Whether or not characters should be underlined, and in what way. The possible
values of the :underline attribute are:
nil Don’t underline.
t Underline with the foreground color of the face.
color Underline in color color, a string specifying a color.
(:color color :style style)
color is either a string, or the symbol foreground-color, meaning
the foreground color of the face. Omitting the attribute :color
means to use the foreground color of the face. style should be
a symbol line or wave, meaning to use a straight or wavy line.
Omitting the attribute :style means to use a straight line.
:overline
Whether or not characters should be overlined, and in what color. If the value
is t, overlining uses the foreground color of the face. If the value is a string,
overlining uses that color. The value nil means do not overline.
:strike-through
Whether or not characters should be strike-through, and in what color. The
value is used like that of :overline.
: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. A negative width −n means to draw a line of width n whose
top and bottom parts occupy the space of the underlying text, thus
avoiding any increase in the character height.
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.
The value style specifies whether to draw a 3D box. If it is
released-button, the box looks like a 3D button that is not
being pressed. If it is pressed-button, the box looks like a 3D
button that is being pressed. If it is nil or omitted, a plain 2D
box is used.
:inverse-video
Whether or not characters should be displayed in inverse video. The value
should be t (yes) or nil (no).
Chapter 39: Emacs Display 1000
first element of spec. Each of the following elements can override any or
all of these defaults.
t This element of spec matches all terminals. Therefore, any subsequent
elements of spec are never used. Normally t is used in the last (or only)
element of spec.
a list If display is a list, each element should have the form (characteristic
value...). Here characteristic specifies a way of classifying terminals,
and the values are possible classifications which display should apply to.
Here are the possible values of characteristic:
type The kind of window system the terminal uses—either
graphic (any graphics-capable display), x, pc (for the
MS-DOS console), w32 (for MS Windows 9X/NT/2K/XP),
or tty (a non-graphics-capable display). See Section 39.24
[Window Systems], page 1065.
class What kinds of colors the terminal supports—either color,
grayscale, or mono.
background
The kind of background—either light or dark.
min-colors
An integer that represents the minimum number of colors
the terminal should support. This matches a terminal if its
display-color-cells value is at least the specified integer.
supports Whether or not the terminal can display the face attributes
given in value . . . (see Section 39.12.1 [Face Attributes],
page 997). See [Display Face Attribute Testing], page 739,
for more information on exactly how this testing is done.
If an element of display specifies more than one value for a given
characteristic, any of those values is acceptable. If display has more
than one element, each element should specify a different characteristic;
then each characteristic of the terminal must match one of the values
specified for it in display.
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
Normally, Emacs uses the face specs of each face to automatically calculate its attributes
on each frame (see Section 39.12.2 [Defining Faces], page 1001). The function set-face-
attribute can override this calculation by directly assigning attributes to a face, either on
a specific frame or for all frames. This function is mostly intended for internal usage.
If frame is t, this function sets the default attributes for newly created frames. If
frame is nil, this function sets the attributes for all existing frames, as well as for
newly created frames.
The following commands and functions mostly provide compatibility with old versions
of Emacs. They work by calling set-face-attribute. Values of t and nil (or omitted)
for their frame argument are handled just like set-face-attribute and face-attribute.
The commands read their arguments using the minibuffer, if called interactively.
set-face-foreground face color &optional frame [Command]
set-face-background face color &optional frame [Command]
These set the :foreground attribute (or :background attribute, respectively) of face
to color.
set-face-stipple face pattern &optional frame [Command]
This sets the :stipple attribute of face to pattern.
set-face-font face font &optional frame [Command]
This sets the :font attribute of face to font.
set-face-bold face bold-p &optional frame [Function]
This sets the :weight attribute of face to normal if bold-p is nil, and to bold
otherwise.
set-face-italic face italic-p &optional frame [Function]
This sets the :slant attribute of face to normal if italic-p is nil, and to italic
otherwise.
set-face-underline face underline &optional frame [Command]
This sets the :underline attribute of face to underline.
set-face-inverse-video face inverse-video-p &optional frame [Command]
This sets the :inverse-video attribute of face to inverse-video-p.
invert-face face &optional frame [Command]
This swaps the foreground and background colors of face face.
The following functions examine the attributes of a face. They mostly provide compat-
ibility with old versions of Emacs. If you don’t specify frame, they refer to the selected
frame; t refers to the default data for new frames. They return unspecified if the face
doesn’t define any value for that attribute. If inherit is nil, only an attribute directly
defined by the face is returned. If inherit is non-nil, any faces specified by its :inherit
attribute are considered as well, and if inherit is a face or a list of faces, then they are also
considered, until a specified attribute is found. To ensure that the return value is always
specified, use a value of default for inherit.
face-font face &optional frame character [Function]
This function returns the name of the font of face face.
If the optional argument frame is specified, it returns the name of the font of face for
that frame. If frame is omitted or nil, the selected frame is used. And, in this case,
if the optional third argument character is supplied, it returns the font name used for
character.
Chapter 39: Emacs Display 1006
• If the text comes from an overlay string via before-string or after-string proper-
ties (see Section 39.9.2 [Overlay Properties], page 988), or from a display string (see
Section 39.16.4 [Other Display Specs], page 1031), and the string doesn’t contain a
face or mouse-face property, but the buffer text affected by the overlay/display prop-
erty does define a face, Emacs applies the face attributes of the “underlying” buffer
text. Note that this is so even if the overlay or display string is displayed in the display
margins (see Section 39.16.5 [Display Margins], page 1033).
• If any given attribute has not been specified during the preceding steps, Emacs applies
the attribute of the default face.
At each stage, if a face has a valid :inherit attribute, Emacs treats any attribute with
an unspecified value as having the corresponding value drawn from the parent face(s).
see Section 39.12.1 [Face Attributes], page 997. Note that the parent face(s) may also leave
the attribute unspecified; in that case, the attribute remains unspecified at the next level
of face merging.
face-remapping-alist [Variable]
The value of this variable is an alist whose elements have the form (face .
remapping). This causes Emacs to display any text having the face face with
remapping, rather than the ordinary definition of face.
remapping may be any face spec suitable for a face text property: either a face (i.e.,
a face name or a property list of attribute/value pairs), or a list of faces. For details,
see the description of the face text property in Section 32.19.4 [Special Properties],
page 808. remapping serves as the complete specification for the remapped face—it
replaces the normal definition of face, instead of modifying it.
If face-remapping-alist is buffer-local, its local value takes effect only within that
buffer.
Note: face remapping is non-recursive. If remapping references the same face name
face, either directly or via the :inherit attribute of some other face in remapping,
that reference uses the normal definition of face. For instance, if the mode-line face
is remapped using this entry in face-remapping-alist:
(mode-line italic mode-line)
then the new definition of the mode-line face inherits from the italic face, and the
normal (non-remapped) definition of mode-line face.
where, as explained above, each of the relative-spec-N and base-spec is either a face name,
or a property list of attribute/value pairs. Each of the relative remapping entries, relative-
spec-N, is managed by the face-remap-add-relative and face-remap-remove-relative
functions; these are intended for simple modifications like changing the text size. The base
remapping entry, base-spec, has the lowest priority and is managed by the face-remap-
set-base and face-remap-reset-base functions; it is intended for major modes to remap
faces in the buffers they control.
face-list [Function]
This function returns a list of all defined face names.
by its face number. However, functions that manipulate glyphs, such as make-glyph-
code and glyph-face (see Section 39.22.4 [Glyphs], page 1062) access the face num-
bers internally. Note that the face number is stored as the value of the face property
of the face symbol, so we recommend not to set that property of a face to any value
of your own.
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,
just before doing redisplay. They are called even when Font Lock Mode isn’t en-
abled. When Font Lock Mode is enabled, this variable usually holds just one function,
jit-lock-function.
The functions are called in the order listed, with one argument, a buffer position
pos. Collectively they should attempt to assign faces to the text in the current buffer
starting at pos.
The functions should record the faces they assign by setting the face property. They
should also add a non-nil fontified property to all the text they have assigned faces
to. That property tells redisplay that faces have been assigned to that text already.
It is probably a good idea for the functions 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 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.
Chapter 39: Emacs Display 1010
default The default face, whose attributes are all specified. All other faces implicitly
inherit from it: any unspecified attribute defaults to the attribute on this face
(see Section 39.12.1 [Face Attributes], page 997).
bold
italic
bold-italic
underline
fixed-pitch
fixed-pitch-serif
variable-pitch
These have the attributes indicated by their names (e.g., bold has a bold
:weight attribute), with all other attributes unspecified (and so given by
default).
shadow For dimmed-out text. For example, it is used for the ignored part of a filename
in the minibuffer (see Section “Minibuffers for File Names” in The GNU Emacs
Manual).
link
link-visited
For clickable text buttons that send the user to a different buffer or location.
highlight
For stretches of text that should temporarily stand out. For example, it is
commonly assigned to the mouse-face property for cursor highlighting (see
Section 32.19.4 [Special Properties], page 808).
match
isearch
lazy-highlight
For text matching (respectively) permanent search matches, interactive search
matches, and lazy highlighting other matches than the current interactive one.
error
warning
success For text concerning errors, warnings, or successes. For example, these are used
for messages in *Compilation* buffers.
Chapter 39: Emacs Display 1011
Emacs can make use of scalable fonts, but by default it does not use them.
2
In this context, the term font has nothing to do with Font Lock (see Section 23.6 [Font Lock Mode],
page 487).
Chapter 39: Emacs Display 1012
39.12.11 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.
The construct ‘charset:font’ specifies which font to use (in this fontset) for one partic-
ular 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.
Chapter 39: Emacs Display 1014
For instance, this changes the default fontset to use a font of which family name is
‘Kochi Gothic’ for all characters belonging to the charset japanese-jisx0208.
(set-fontset-font t 'japanese-jisx0208
(font-spec :family "Kochi Gothic"))
A font object is a Lisp object that represents a font that Emacs has opened. Font objects
cannot be modified in Lisp, but they can be inspected.
A font spec is a Lisp object that contains a set of specifications that can be used to find
a font. More than one font may match the specifications in a font spec.
:size The font size—either a non-negative integer that specifies the pixel size,
or a floating-point number that specifies the point size.
:adstyle Additional typographic style information for the font, such as ‘sans’. The
value should be a string or a symbol.
:registry
The charset registry and encoding of the font, such as ‘iso8859-1’. The
value should be a string or a symbol.
:script The script that the font must support (a symbol).
:lang The language that the font should support. The value should be a symbol
whose name is a two-letter ISO-639 language name. On X, the value is
matched against the “Additional Style” field of the XLFD name of a font,
if it is non-empty. On MS-Windows, fonts matching the spec are required
to support codepages needed for the language. Currently, only a small
set of CJK languages is supported with this property: ‘ja’, ‘ko’, and ‘zh’.
:otf The font must be an OpenType font that supports these OpenType fea-
tures, provided Emacs is compiled with a library, such as ‘libotf’ on
GNU/Linux, that supports complex text layout for scripts which need
that. The value must be a list of the form
(script-tag langsys-tag gsub gpos)
where script-tag is the OpenType script tag symbol; langsys-tag is the
OpenType language system tag symbol, or nil to use the default language
system; gsub is a list of OpenType GSUB feature tag symbols, or nil
if none is required; and gpos is a list of OpenType GPOS feature tag
symbols, or nil if none is required. If gsub or gpos is a list, a nil element
in that list means that the font must not match any of the remaining tag
symbols. The gpos element may be omitted.
A font entity is a reference to a font that need not be open. Its properties are intermediate
between a font object and a font spec: like a font object, and unlike a font spec, it refers to
a single, specific font. Unlike a font object, creating a font entity does not load the contents
of that font into computer memory. Emacs may open multiple font objects of different sizes
from a single font entity referring to a scalable font.
if non-nil, should be another font spec, which is used to control the order of the
returned list; the returned font entities are sorted in order of decreasing closeness to
that font spec.
If you call set-face-attribute and pass a font spec, font entity, or font name string
as the value of the :font attribute, Emacs opens the best matching font that is available
for display. It then stores the corresponding font object as the actual value of the :font
attribute for that face.
The following functions can be used to obtain information about a font. For these
functions, the font argument can be a font object, a font entity, or a font spec.
space-width
The width, in pixels, of the font’s space character.
average-width
The average width of the font characters. If this is zero, Emacs uses the
value of space-width instead, when it calculates text layout on display.
capability A list whose first element is a symbol representing the font type, one
of x, opentype, truetype, type1, pcf, or bdf. For OpenType fonts,
the list includes 2 additional elements describing the gsub and gpos
features supported by the font. Each of these elements is a list of the form
((script (langsys feature ...) ...) ...), where script is a symbol
representing an OpenType script tag, langsys is a symbol representing
an OpenType langsys tag (or nil, which stands for the default langsys),
and each feature is a symbol representing an OpenType feature tag.
The following four functions return size information about fonts used by various faces, al-
lowing various layout considerations in Lisp programs. These functions take face remapping
into consideration, returning information about the remapped face, if the face in question
was remapped. See Section 39.12.5 [Face Remapping], page 1007.
default-font-width [Function]
This function returns the average width in pixels of the font used by the current
buffer’s default face.
default-font-height [Function]
This function returns the height in pixels of the font used by the current buffer’s
default face.
39.13 Fringes
On graphical displays, Emacs draws fringes next to each window: thin vertical strips down
the sides which can display bitmaps indicating truncation, continuation, horizontal scrolling,
and so on.
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 39.16.5
[Display Margins], page 1033.
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.
Any buffer which does not specify values for these variables uses the values specified
by the left-fringe and right-fringe frame parameters (see Section 29.4.3.4 [Layout
Parameters], page 707).
The above variables actually take effect via the function set-window-buffer (see
Section 28.11 [Buffers and Windows], page 626), which calls set-window-fringes as a
subroutine. If you change one of these variables, the fringe display is not updated in
existing windows showing the buffer, unless you call set-window-buffer again in each
affected window. You can also use set-window-fringes to control the fringe display in
individual windows.
set-window-fringes window left &optional right outside-margins [Function]
This function sets the fringe widths of window window. If window is nil, the selected
window is used.
The argument left specifies the width in pixels of the left fringe, and likewise right
for the right fringe. A value of nil for either one stands for the default width. If
outside-margins is non-nil, that specifies that fringes should appear outside of the
display margins.
If window is not large enough to accommodate fringes of the desired width, this leaves
the fringes of window unchanged.
The values specified here may be later overridden by invoking set-window-buffer
(see Section 28.11 [Buffers and Windows], page 626) on window with its keep-margins
argument nil or omitted.
window-fringes &optional window [Function]
This function returns information about the fringes of a window window. If window
is omitted or nil, the selected window is used. The value has the form (left-width
right-width outside-margins).
fringe-indicator-alist [Variable]
This buffer-local variable specifies the mapping from logical fringe indicators to the
actual bitmaps displayed in the window fringes. The value is an alist of elements (in-
dicator . bitmaps), where indicator specifies a logical indicator type and bitmaps
specifies the fringe bitmaps to use for that indicator.
Each indicator should be one of the following symbols:
truncation, continuation.
Used for truncation and continuation lines.
up, down, top, bottom, top-bottom
Used when indicate-buffer-boundaries is non-nil: up and down in-
dicate a buffer boundary lying above or below the window edge; top
and bottom indicate the topmost and bottommost buffer text line; and
top-bottom indicates where there is just one line of text in the buffer.
empty-line
Used to indicate empty lines when indicate-empty-lines is non-nil.
overlay-arrow
Used for overlay arrows (see Section 39.13.6 [Overlay Arrow], page 1024).
Each bitmaps value may be a list of symbols (left right [left1 right1]). The
left and right symbols specify the bitmaps shown in the left and/or right fringe, for
the specific indicator. left1 and right1 are specific to the bottom and top-bottom
Chapter 39: Emacs Display 1022
indicators, and are used to indicate that the last text line has no final newline. Al-
ternatively, bitmaps may be a single symbol which is used in both left and right
fringes.
See Section 39.13.4 [Fringe Bitmaps], page 1022, for a list of standard bitmap symbols
and how to define your own. In addition, nil represents the empty bitmap (i.e., an
indicator that is not shown).
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
default value of fringe-indicator-alist is used.
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 has
the form (cursor-type . bitmap), which means to use the fringe bitmap bitmap to
display cursors of type cursor-type.
Each cursor-type should be one of box, hollow, bar, hbar, or hollow-small. The
first four have the same meanings as in the cursor-type frame parameter (see
Section 29.4.3.9 [Cursor Parameters], page 713). The hollow-small type is used
instead of hollow when the normal hollow-rectangle bitmap is too tall to fit on a
specific display line.
Each bitmap should be a symbol specifying the fringe bitmap to be displayed for that
logical cursor type. See the next subsection for details.
When fringe-cursor-alist has a buffer-local value, and there is no bitmap
defined for a cursor type, the corresponding value from the default value of
fringes-indicator-alist is used.
The argument align specifies the positioning of the bitmap relative to the range of
rows where it is used; the default is to center the bitmap. The allowed values are top,
center, or bottom.
The align argument may also be a list (align periodic) where align is interpreted
as described above. If periodic is non-nil, it specifies that the rows in bits should
be repeated enough times to reach the specified height.
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
is possible to 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 39.9.2 [Overlay Properties], page 988.
You can define multiple overlay arrows via the variable overlay-arrow-variable-list.
Chapter 39: Emacs Display 1025
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.
You can override the frame specific settings for individual windows by using the following
function:
height specifies the height of the horizontal scroll bar in pixels (nil means use the
height specified for the frame). horizontal-type specifies whether to have a horizontal
scroll bar. The possible values are bottom, t, which means to use the frame’s default,
and nil for no horizontal scroll bar.
If window is not large enough to accommodate a scroll bar of the desired dimension,
this leaves the corresponding scroll bar unchanged.
The values specified here may be later overridden by invoking set-window-buffer
(see Section 28.11 [Buffers and Windows], page 626) on window with its keep-margins
argument nil or omitted.
The following four functions take as argument a live window which defaults to the
selected one.
If you don’t specify these values for a window with set-window-scroll-bars, the buffer-
local variables vertical-scroll-bar, horizontal-scroll-bar, scroll-bar-width and
scroll-bar-height in the buffer being displayed control the window’s 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.
You can control the appearance of scroll bars for a particular buffer by setting the
following variables which automatically become buffer-local when set.
vertical-scroll-bar [Variable]
This variable specifies the location of the vertical scroll bar. The possible values are
left, right, t, which means to use the frame’s default, and nil for no scroll bar.
Chapter 39: Emacs Display 1027
horizontal-scroll-bar [Variable]
This variable specifies the location of the horizontal scroll bar. The possible values
are bottom, t, which means to use the frame’s default, and nil for no scroll bar.
scroll-bar-width [Variable]
This variable specifies the width of the buffer’s vertical scroll bars, measured in pixels.
A value of nil means to use the value specified by the frame.
scroll-bar-height [Variable]
This variable specifies the height of the buffer’s horizontal scroll bar, measured in
pixels. A value of nil means to use the value specified by the frame.
Finally you can toggle the display of scroll bars on all frames by customizing the variables
scroll-bar-mode and horizontal-scroll-bar-mode.
scroll-bar-mode [User Option]
This variable controls whether and where to put vertical scroll bars in all frames.
The possible values are nil for no scroll bars, left to put scroll bars on the left and
right to put scroll bars on the right.
horizontal-scroll-bar-mode [User Option]
This variable controls whether to display horizontal scroll bars on all frames.
window-divider-last-pixel
This is the face used for drawing the last pixel of a divider that is at least three
pixels wide. To obtain a solid appearance, set this to the same value used for
the window-divider face.
You can get the sizes of the dividers of a specific window with the following two functions.
window-right-divider-width &optional window [Function]
Return the width (thickness) in pixels of window’s right divider. window must be a
live window and defaults to the selected one. The return value is always zero for a
rightmost window.
window-bottom-divider-width &optional window [Function]
Return the width (thickness) in pixels of window’s bottom divider. window must
be a live window and defaults to the selected one. The return value is zero for the
minibuffer window or a bottommost window on a minibuffer-less frame.
Here is an example which illustrates this point. A string serves as a replacing display
specification, which replaces the text that has the property with the specified string (see
Section 39.16.4 [Other Display Specs], page 1031). Consider the following function:
(defun foo ()
(dotimes (i 5)
(let ((string (concat "A"))
(start (+ i i (point-min))))
(put-text-property start (1+ start) 'display string)
(put-text-property start (+ 2 start) 'display string))))
This function gives each of the first ten characters in the buffer a display property which is
a string "A", but they don’t all get the same string object. The first two characters get the
same string object, so they are replaced with one ‘A’; the fact that the display property was
assigned in two separate calls to put-text-property is irrelevant. Similarly, the next two
characters get a second string (concat creates a new string object), so they are replaced
with one ‘A’; and so on. Thus, the ten characters appear as five A’s.
: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 39.16.3
[Pixel Specification], page 1030).
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.
Note that space properties are treated as paragraph separators for the purposes of re-
ordering bidirectional text for display. See Section 39.26 [Bidirectional Display], page 1067,
for the details.
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. When the window displays line numbers, the text is considered to start
where the space used for line-number display ends.
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 (which should be given by its image spec).
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. It is mainly meant to support display of subscripts
and superscripts.
The 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.
Note that if the text also has a height display specification, which was specified
before (i.e. to the left of) raise, the latter will affect the amount of raising or
lowering in pixels, because that is based on the height of the text being raised.
Therefore, if you want to display a sub- or superscript that is smaller than the
normal text height, consider specifying raise before height.
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.
Chapter 39: Emacs Display 1033
Note that condition will only be evaluated when redisplay examines the text where this
display spec is located, so this feature is best suited for conditions that are relatively stable,
i.e. yield, for each particular buffer position, the same results on every evaluation. If the
results change for the same text location, e.g., if the result depends on the position of point,
then the conditional specification might not do what you want, because redisplay examines
only those parts of buffer text where it has reasons to assume that something changed since
the last display cycle.
If window is not large enough to accommodate margins of the desired width, this
leaves the margins of window unchanged.
The values specified here may be later overridden by invoking set-window-buffer
(see Section 28.11 [Buffers and Windows], page 626) on window with its keep-margins
argument nil or omitted.
39.17 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 39.16
[Display Property], page 1028).
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 sup-
port 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.25
[Display Feature Testing], page 738).
image-types [Variable]
This variable contains a list of type symbols for image formats which are potentially
supported in the current configuration.
“Potentially” means that Emacs knows about the image types, not necessarily that
they can be used (for example, they could depend on unavailable dynamic libraries).
To know which image types are really available, use image-type-available-p.
Chapter 39: Emacs Display 1035
:mask mask
If mask is heuristic or (heuristic bg), build a clipping mask for the image,
so that the background of a frame is visible behind the image. If bg is not
specified, or if bg is t, determine the background color of the image by looking
at the four corners of the image, assuming the most frequently occurring color
from the corners is the background color of the image. Otherwise, bg must be
a list (red green blue) specifying the color to assume for the background of
the image.
If mask is nil, remove a mask from the image, if it has one. Images in some
formats include a mask which can be removed by specifying :mask nil.
:pointer shape
This specifies the pointer shape when the mouse pointer is over this image. See
Section 29.19 [Pointer Shape], page 733, for available pointer shapes.
:map map This associates an image map of hot spots with this image.
An image map is an alist where each element has the format (area id plist).
An area is specified as either a rectangle, a circle, or a polygon.
A rectangle is a cons (rect . ((x0 . y0) . (x1 . y1))) which specifies the
pixel coordinates of the upper left and bottom right corners of the rectangle
area.
A circle is a cons (circle . ((x0 . y0) . r)) which specifies the center and
the radius of the circle; r may be a float or integer.
A polygon is a cons (poly . [x0 y0 x1 y1 ...]) where each pair in the vector
describes one corner in the polygon.
When the mouse pointer lies on a hot-spot area of an image, the plist of that
hot-spot is consulted; if it contains a help-echo property, that defines a tool-tip
for the hot-spot, and if it contains a pointer property, that defines the shape of
the mouse cursor when it is on the hot-spot. See Section 29.19 [Pointer Shape],
page 733, for available pointer shapes.
When you click the mouse when the mouse pointer is over a hot-spot, an event
is composed by combining the id of the hot-spot with the mouse event; for
instance, [area4 mouse-1] if the hot-spot’s id is area4.
image-mask-p spec &optional frame [Function]
This function returns t if image spec has a mask bitmap. frame is the frame on which
the image will be displayed. frame nil or omitted means to use the selected frame
(see Section 29.10 [Input Focus], page 720).
: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.
If you specify an XBM image using data within Emacs instead of an external file, use
the following three properties:
:data data
The value, data, specifies the contents of the image. There are three formats
you can use for data:
• A vector of strings or bool-vectors, each specifying one line of the image.
Do specify :height and :width.
• A string containing the same byte sequence as an XBM file would contain.
You must not specify :height and :width in this case, because omitting
them is what indicates the data has the format of an XBM file. The file
contents specify the height and width of the image.
• A string or a bool-vector containing the bits of the image (plus perhaps
some extra bits at the end that will not be used). It should contain at least
width * height bits. In this case, you must specify :height and :width,
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.
image-format-suffixes [Variable]
This variable is an alist mapping image types to file name extensions. Emacs uses
this in conjunction with the :format image property (see below) to give a hint to the
ImageMagick library as to the type of an image. Each element has the form (type
extension), where type is a symbol specifying an image content-type, and extension
is a string that specifies the associated file name extension.
Images loaded with ImageMagick support the following additional image descriptor prop-
erties:
:background background
background, if non-nil, should be a string specifying a color, which is used as
the image’s background color if the image supports transparency. If the value
is nil, it defaults to the frame’s background color.
:width width, :height height
The :width and :height keywords are used for scaling the image. If only one
of them is specified, the other one will be calculated so as to preserve the aspect
ratio. If both are specified, aspect ratio may not be preserved.
:max-width max-width, :max-height max-height
The :max-width and :max-height keywords are used for scaling if the size
of the image of the image exceeds these values. If :width is set it will have
precedence over max-width, and if :height is set it will have precedence
over max-height, but you can otherwise mix these keywords as you wish.
:max-width and :max-height will always preserve the aspect ratio.
If both :width and :max-height has been set (but :height has not been set),
then :max-height will have precedence. The same is the case for the oppo-
site combination: The “max” keyword has precedence. That is, if you have a
200x100 image and specify that :width should be 400 and :max-height should
be 150, you’ll end up with an image that is 300x150: Preserving the aspect
ratio and not exceeding the “max” setting. This combination of parameters is
a useful way of saying “display this image as large as possible, but no larger
than the available display area”.
:scale scale
This should be a number, where values higher than 1 means to increase the
size, and lower means to decrease the size. For instance, a value of 0.25 will
Chapter 39: Emacs Display 1040
make the image a quarter size of what it originally was. If the scaling makes
the image larger than specified by :max-width or :max-height, the resulting
size will not exceed those two values. If both :scale and :height/:width are
specified, the height/width will be adjusted by the specified scaling factor.
:format type
The value, type, should be a symbol specifying the type of the image data, as
found in image-format-suffixes. This is used when the image does not have
an associated file name, to provide a hint to ImageMagick to help it detect the
image type.
:rotation angle
Specifies a rotation angle in degrees.
:index frame
See Section 39.17.10 [Multi-Frame Images], page 1046.
All the following functions take an optional list of keyword parameters that alter the
various attributes from their default values. Valid attributes include:
:stroke-width
The width (in pixels) of lines drawn, and outlines around solid shapes.
Chapter 39: Emacs Display 1041
:stroke-color
The color of lines drawn, and outlines around solid shapes.
:fill-color
The color used for solid shapes.
:id The identified of the shape.
:gradient
If given, this should be the identifier of a previously defined gradient object.
svg-rectangle svg x y width height &rest args [Function]
Add to svg a rectangle whose upper left corner is at position x/y and whose size is
width/height.
(svg-rectangle svg 100 100 500 500 :gradient "gradient1")
svg-circle svg x y radius &rest args [Function]
Add to svg a circle whose center is at x/y and whose radius is radius.
svg-ellipse svg x y x-radius y-radius &rest args [Function]
Add to svg an ellipse whose center is at x/y, and whose horizontal radius is x-radius
and the vertical radius is y-radius.
svg-line svg x1 y1 x2 y2 &rest args [Function]
Add to svg a line that starts at x1/y1 and extends to x2/y2.
svg-polyline svg points &rest args [Function]
Add to svg a multiple-segment line (a.k.a. “polyline”) that goes through points, which
is a list of X/Y position pairs.
(svg-polyline svg '((200 . 100) (500 . 450) (80 . 100))
:stroke-color "green")
svg-polygon svg points &rest args [Function]
Add a polygon to svg where points is a list of X/Y pairs that describe the outer
circumference of the polygon.
(svg-polygon svg '((100 . 100) (200 . 150) (150 . 90))
:stroke-color "blue" :fill-color "red")
svg-text svg text &rest args [Function]
Add the specified text to svg.
(svg-text
svg "This is a text"
:font-size "40"
:font-weight "bold"
:stroke "black"
:fill "white"
:font-family "impact"
:letter-spacing "4pt"
:x 300
:y 400
:stroke-width 1)
Chapter 39: Emacs Display 1042
Here’s a complete example that creates and inserts an image with a circle:
(let ((svg (svg-create 400 400 :stroke-width 10)))
(svg-gradient svg "gradient1" 'linear '((0 . "red") (100 . "blue")))
(svg-circle svg 200 200 100 :gradient "gradient1"
:stroke-color "green")
(insert-image (svg-image svg)))
: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 PBM 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 PBM
that is 0. The default is the frame’s background color.
GIF Image type gif. Supports the :index property. See Section 39.17.10 [Multi-
Frame Images], page 1046.
TIFF Image type tiff. Supports the :index property. See Section 39.17.10 [Multi-
Frame Images], page 1046.
Chapter 39: Emacs Display 1043
return sizes measured in the default character size of frame (see Section 29.3.2 [Frame
Font], page 694). frame is the frame on which the image will be displayed. frame nil
or omitted means use the selected frame (see Section 29.10 [Input Focus], page 720).
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 floating point, 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 39.17.11 [Image
Cache], page 1047).
Images inserted with the insertion functions above also get a local keymap installed in
the text properties (or overlays) that span the displayed image. This keymap defines the
following commands:
+ Increase the image size (image-increase-size). A prefix value of ‘4’ means
to increase the size by 40%. The default is 20%.
- Decrease the image size (image-increase-size). A prefix value of ‘4’ means
to decrease the size by 40%. The default is 20%.
r Rotate the image by 90 degrees (image-rotate).
o Save the image to a file (image-save).
Animation operates by means of a timer. Note that Emacs imposes a minimum frame delay
of 0.01 (image-minimum-frame-delay) seconds. If the image itself does not specify a delay,
Emacs uses image-default-frame-delay.
One use for image-flush is to tell Emacs about a change in an image file. If an image
specification contains a :file property, the image is cached based on the file’s contents
when the image is first displayed. Even if the file subsequently changes, Emacs continues
displaying the old version of the image. Calling image-flush flushes the image from the
cache, forcing Emacs to re-read the file the next time it needs to display that image.
Another use for image-flush is for memory conservation. If your Lisp program cre-
ates a large number of temporary images over a period much shorter than image-cache-
eviction-delay (see below), you can opt to flush unused images yourself, instead of waiting
for Emacs to do it automatically.
is taken to be a file name, and all images associated with that file name are removed
from all image caches.
If an image in the image cache has not been displayed for a specified period of time,
Emacs removes it from the cache and frees the associated memory.
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.
Under some circumstances, if the number of images in the cache grows too large, the
actual eviction delay may be shorter than this.
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.
39.19 Buttons
The Button package defines functions for inserting and manipulating buttons that can be
activated with the mouse or via keyboard commands. These buttons are typically used for
various kinds of hyperlinks.
A button is essentially a set of text or overlay properties, attached to a stretch of text
in a buffer. These properties are called button properties. One of these properties, the
action property, specifies a function which is called when the user invokes the button using
the keyboard or the mouse. The action function may examine the button and use its other
properties as desired.
In some ways, the Button package duplicates the functionality in the Widget package.
See Section “Introduction” in The Emacs Widget Library. The advantage of the Button
Chapter 39: Emacs Display 1050
package is that it is faster, smaller, and simpler to program. From the point of view of the
user, the interfaces produced by the two packages are very similar.
this type (a button’s type may be set by giving it a type property when creating the
button, using the :type keyword argument).
In addition, the keyword argument :supertype may be used to specify a button-type
from which name inherits its default property values. Note that this inheritance hap-
pens only when name is defined; subsequent changes to a supertype are not reflected
in its subtypes.
The following functions are similar, but using text properties (see Section 32.19 [Text
Properties], page 802) to hold the button properties. Such buttons do not add markers
to the buffer, so editing in the buffer does not slow down if there is an extremely large
numbers of buttons. However, if there is an existing face text property on the text (e.g.,
a face assigned by Font Lock mode), the button face may not be visible. Both of these
functions return the starting position of the new button.
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 correspondence
between buffer positions and nodes, move point from one node’s textual representation to
another, and so forth. See Section 39.20.1 [Abstract Display Functions], page 1054.
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.
(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.
If ctl-arrow is nil, these characters are displayed as octal escapes (see below).
This rule also applies to carriage return (character code 13), if that character appears in
the buffer. But carriage returns usually do not appear in buffer text; they are eliminated
as part of end-of-line conversion (see Section 33.10.1 [Coding System Basics], page 848).
• Raw bytes are non-ASCII characters with codes 128 through 255 (see Section 33.1 [Text
Representations], page 835). These characters display as octal escapes: sequences of
four glyphs, where the first glyph is the ASCII code for ‘\’, and the others are digit
characters representing the character code in octal. (A display table can specify a glyph
to use instead of ‘\’.)
• Each non-ASCII character with code above 255 is displayed literally, if the terminal
supports it. If the terminal does not support it, the character is said to be glyphless,
and it is usually displayed using a placeholder glyph. For example, if a graphical
terminal has no font for a character, Emacs usually displays a box containing the
character code in hexadecimal. See Section 39.22.5 [Glyphless Chars], page 1063.
The above display conventions apply even when there is a display table, for any character
whose entry in the active display table is nil. Thus, when you set up a display table, you
need only specify the characters for which you want special behavior.
The following variables affect how certain characters are displayed on the screen. Since
they change the number of columns the characters occupy, they also affect the indentation
functions. They 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 476).
ctl-arrow [User Option]
This buffer-local variable controls how control characters are displayed. If it is non-
nil, they are displayed as a caret followed by the character: ‘^A’. If it is nil, they
are displayed as octal escapes: a backslash followed by three octal digits, as in ‘\001’.
tab-width [User Option]
The value of this buffer-local variable is the spacing between tab stops used for dis-
playing tab characters in Emacs buffers. The value is in units of columns, and the
default is 8. Note that this feature is completely independent of the user-settable tab
stops used by the command tab-to-tab-stop. See Section 32.17.5 [Indent Tabs],
page 800.
[Usual Display], page 1059), or a vector of glyph codes (which means to display the character
c as those glyphs; see Section 39.22.4 [Glyphs], page 1062).
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 39.22.4 [Glyphs], page 1062. On graphical terminals, Emacs by default
uses arrows in the fringes to indicate truncation, so the display table has no
effect, unless you disable the fringes (see Section “Window Fringes” in the GNU
Emacs Manual).
1 The glyph for the end of a continued line (the default is ‘\’). On graphical
terminals, Emacs by default uses curved arrows in the fringes to indicate con-
tinuation, so the display table has no effect, unless you disable the fringes.
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 39.7 [Selective Display], page 980.
5 The glyph used to draw the border between side-by-side windows (the default
is ‘|’). See Section 28.6 [Splitting Windows], page 613. This currently has
effect only on text terminals; on graphical terminals, if vertical scroll bars are
supported and in use, a scroll bar separates the two windows, and if there are
no vertical scroll bars and no dividers (see Section 39.15 [Window Dividers],
page 1027), Emacs uses a thin line to indicate the border.
For example, here is how to construct a display table that mimics the effect of setting
ctl-arrow to a non-nil value (see Section 39.22.4 [Glyphs], page 1062, for the function
make-glyph-code):
(setq disptab (make-display-table))
(dotimes (i 32)
(or (= i ?\t)
(= i ?\n)
(aset disptab i
(vector (make-glyph-code ?^ 'escape-glyph)
(make-glyph-code (+ i 64) 'escape-glyph)))))
(aset disptab 127
(vector (make-glyph-code ?^ 'escape-glyph)
(make-glyph-code ?? 'escape-glyph)))))
describe-current-display-table [Command]
This command displays a description of the current display table in a help buffer.
buffer-display-table [Variable]
This variable is automatically buffer-local in all buffers; its value specifies the buffer’s
display table. If it is nil, there is no buffer display table.
standard-display-table [Variable]
The value of this variable is the standard display table, which is used when Emacs
is displaying a buffer in a window with neither a window display table nor a buffer
display table defined, or when Emacs is outputting text to the standard output or
error streams. Although its default is typically nil, in an interactive session if the
terminal cannot display curved quotes, its default maps curved quotes to ASCII ap-
proximations. See Section 24.4 [Text Quoting Style], page 515.
The disp-table library defines several functions for changing the standard display table.
39.22.4 Glyphs
A glyph is a graphical symbol which occupies a single character position on the screen. Each
glyph is represented in Lisp as a glyph code, which specifies a character and optionally a
face to display it in (see Section 39.12 [Faces], page 997). The main use of glyph codes is as
the entries of display tables (see Section 39.22.2 [Display Tables], page 1060). The following
functions are used to manipulate glyph codes:
Chapter 39: Emacs Display 1063
If a character has a non-nil entry in an active display table, the display table takes
effect; in this case, Emacs does not consult glyphless-char-display at all.
glyphless-char-display-control [User Option]
This user option provides a convenient way to set glyphless-char-display for
groups of similar characters. Do not set its value directly from Lisp code; the value
takes effect only via a custom :set function (see Section 15.3 [Variable Definitions],
page 247), which updates glyphless-char-display.
Its value should be an alist of elements (group . method), where group is a symbol
specifying a group of characters, and method is a symbol specifying how to display
them.
group should be one of the following:
c0-control
ASCII control characters U+0000 to U+001F, excluding the newline and tab
characters (normally displayed as escape sequences like ‘^A’; see Section
“How Text Is Displayed” in The GNU Emacs Manual).
c1-control
Non-ASCII, non-printing characters U+0080 to U+009F (normally
displayed as octal escape sequences like ‘\230’).
format-control
Characters of Unicode General Category [Cf], such as U+200E left-to-
right mark, but excluding characters that have graphic images, such as
U+00AD soft hyphen.
no-font Characters for which there is no suitable font, or which cannot be encoded
by the terminal’s coding system.
The method symbol should be one of zero-width, thin-space, empty-box, or
hex-code. These have the same meanings as in glyphless-char-display, above.
39.23 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 11.7.3 [Errors], page 160).
ding &optional do-not-terminate [Function]
This function beeps, or flashes the screen (see visible-bell below). It also termi-
nates any keyboard macro currently executing unless do-not-terminate is non-nil.
beep &optional do-not-terminate [Function]
This is a synonym for ding.
visible-bell [User Option]
This variable determines whether Emacs should flash the screen to represent a bell.
Non-nil means yes, nil means no. This is effective on graphical displays, and on
text terminals provided the terminal’s Termcap entry defines the visible bell capability
(‘vb’).
Chapter 39: Emacs Display 1065
window-system [Variable]
This terminal-local variable tells Lisp programs what window system Emacs is using
for displaying the frame. The possible values are
x Emacs is displaying the frame using X.
w32 Emacs is displaying the frame using native MS-Windows GUI.
ns Emacs is displaying the frame using the Nextstep interface (used on
GNUstep and macOS).
pc Emacs is displaying the frame using MS-DOS direct screen writes.
nil Emacs is displaying the frame on a character-based terminal.
initial-window-system [Variable]
This variable holds the value of window-system used for the first frame created by
Emacs during startup. (When Emacs is invoked as a daemon, it does not create any
initial frames, so initial-window-system is nil, except on MS-Windows, where it
is still w32. See Section “Initial Options” in The GNU Emacs Manual.)
39.25 Tooltips
Tooltips are special frames (see Chapter 29 [Frames], page 683) that are used to display
helpful hints (a.k.a. “tips”) related to the current position of the mouse pointer. Emacs
uses tooltips to display help strings about active portions of text (see Section 32.19.4
[Special Properties], page 808) and about various UI elements, such as menu items
(see Section 22.17.1.2 [Extended Menu Items], page 441) and tool-bar buttons (see
Section 22.17.6 [Tool Bar], page 447).
Chapter 39: Emacs Display 1066
tooltip-mode [Function]
Tooltip Mode is a minor mode that enables display of tooltips. Turning off this mode
causes the tooltips be displayed in the echo area. On text-mode (a.k.a. “TTY”)
frames, tooltips are always displayed in the echo area.
When Emacs is built with GTK+ support, it by default displays tooltips using GTK+
functions, and the appearance of the tooltips is then controlled by GTK+ settings. GTK+
tooltips can be disabled by changing the value of the variable x-gtk-use-system-tooltips
to nil. The rest of this subsection describes how to control non-GTK+ tooltips, which are
presented by Emacs itself.
Tooltips are displayed in special frames called tooltip frames, which have their own
frame parameters (see Section 29.4 [Frame Parameters], page 699). Unlike other frames,
the default parameters for tooltip frames are stored in a special variable.
The tooltip face determines the appearance of text shown in tooltips. It should gen-
erally use a variable-pitch font of size that is preferably smaller than the default frame
font.
tooltip-functions [Variable]
This abnormal hook is a list of functions to call when Emacs needs to display a
tooltip. Each function is called with a single argument event which is a copy of the
last mouse movement event. If a function on this list actually displays the tooltip,
it should return non-nil, and then the rest of the functions will not be called. The
default value of this variable is a single function tooltip-help-tips.
If you write your own function to be put on the tooltip-functions list, you may need
to know the buffer of the mouse event that triggered the tooltip display. The following
function provides that information.
Other aspects of tooltip display are controlled by several customizable settings; see
Section “Tooltips” in The GNU Emacs Manual.
Chapter 39: Emacs Display 1067
bidi-display-reordering [Variable]
If the value of this buffer-local variable is non-nil (the default), Emacs performs
bidirectional reordering for display. The reordering affects buffer text, as well as
display strings and overlay strings from text and overlay properties in the buffer
(see Section 39.9.2 [Overlay Properties], page 988, and see Section 39.16 [Display
Property], page 1028). If the value is nil, Emacs does not perform bidirectional
reordering in the buffer.
The default value of bidi-display-reordering controls the reordering of strings
which are not directly supplied by a buffer, including the text displayed in mode lines
(see Section 23.4 [Mode Line Format], page 476) and header lines (see Section 23.4.7
[Header Lines], page 484).
Text covered by display text properties, by overlays with display properties whose
value is a string, and by any other properties that replace buffer text, is treated as a single
unit when it is reordered for display. That is, the entire chunk of text covered by these
properties is reordered together. Moreover, the bidirectional properties of the characters in
such a chunk of text are ignored, and Emacs reorders them as if they were replaced with
a single character U+FFFC, known as the Object Replacement Character. This means that
placing a display property over a portion of text may change the way that the surrounding
text is reordered for display. To prevent this unexpected effect, always place such properties
on text whose directionality is identical with text that surrounds it.
Each paragraph of bidirectional text has a base direction, either right-to-left or left-to-
right. Left-to-right paragraphs are displayed beginning at the left margin of the window, and
are truncated or continued when the text reaches the right margin. Right-to-left paragraphs
are displayed beginning at the right margin, and are continued or truncated at the left
margin.
Where exactly paragraphs start and end, for the purpose of the Emacs UBA implementa-
tion, is determined by the following two buffer-local variables (note that paragraph-start
and paragraph-separate have no influence on this). By default both of these variables are
nil, and paragraphs are bounded by empty lines, i.e., lines that consist entirely of zero or
more whitespace characters followed by a newline.
bidi-paragraph-start-re [Variable]
If non-nil, this variable’s value should be a regular expression matching a line that
starts or separates two paragraphs. The regular expression is always matched after a
newline, so it is best to anchor it, i.e., begin it with a "^".
bidi-paragraph-separate-re [Variable]
If non-nil, this variable’s value should be a regular expression matching a line sepa-
rates two paragraphs. The regular expression is always matched after a newline, so
it is best to anchor it, i.e., begin it with a "^".
If you modify any of these two variables, you should normally modify both, to make
sure they describe paragraphs consistently. For example, to have each new line start a new
paragraph for bidi-reordering purposes, set both variables to "^".
By default, Emacs determines the base direction of each paragraph by looking at the
text at its beginning. The precise method of determining the base direction is specified by
the UBA; in a nutshell, the first character in a paragraph that has an explicit directionality
determines the base direction of the paragraph. However, sometimes a buffer may need to
force a certain base direction for its paragraphs. For example, buffers containing program
source code should force all paragraphs to be displayed left-to-right. You can use following
variable to do this:
Modes for program source code should set this to left-to-right. Prog mode does
this by default, so modes derived from Prog mode do not need to set this explicitly
(see Section 23.2.5 [Basic Major Modes], page 464).
Sometimes there’s a need to move point in strict visual order, either to the left or to the
right of its current screen position. Emacs provides a primitive to do that.
Bidirectional reordering can have surprising and unpleasant effects when two strings with
bidirectional content are juxtaposed in a buffer, or otherwise programmatically concatenated
into a string of text. A typical problematic case is when a buffer consists of sequences of
text fields separated by whitespace or punctuation characters, like Buffer Menu mode or
Rmail Summary Mode. Because the punctuation characters used as separators have weak
directionality, they take on the directionality of surrounding text. As result, a numeric field
that follows a field with bidirectional content can be displayed to the left of the preceding
field, messing up the expected layout. There are several ways to avoid this problem:
− Append the special character U+200E left-to-right mark, or LRM, to the end of
each field that may have bidirectional content, or prepend it to the beginning of the
following field. The function bidi-string-mark-left-to-right, described below,
comes in handy for this purpose. (In a right-to-left paragraph, use U+200F right-
to-left mark, or RLM, instead.) This is one of the solutions recommended by the
UBA.
− Include the tab character in the field separator. The tab character plays the role of
segment separator in bidirectional reordering, causing the text on either side to be
reordered separately.
− Separate fields with a display property or overlay with a property value of the form
(space . PROPS) (see Section 39.16.2 [Specified Space], page 1029). Emacs treats this
display specification as a paragraph separator, and reorders the text on either side
separately.
Chapter 39: Emacs Display 1070
When text that includes mixed right-to-left and left-to-right characters and bidirectional
controls is copied into a different location, it can change its visual appearance, and also
can affect the visual appearance of the surrounding text at destination. This is because
reordering of bidirectional text specified by the UBA has non-trivial context-dependent
effects both on the copied text and on the text at copy destination that will surround it.
Sometimes, a Lisp program may need to preserve the exact visual appearance of the
copied text at destination, and of the text that surrounds the copy. Lisp programs can use
the following function to achieve that effect.
9. It initializes the initial frame’s faces, and sets up the menu bar and tool bar if needed.
If graphical frames are supported, it sets up the tool bar even if the current frame is
not a graphical one, since a graphical frame may be created later on.
10. It use custom-reevaluate-setting to re-initialize the members of the list
custom-delayed-init-variables. These are any pre-loaded user options whose
default value depends on the run-time, rather than build-time, context. See
Section E.1 [Building Emacs], page 1156.
11. It loads the library site-start, if it exists. This is not done if the options ‘-Q’ or
‘--no-site-file’ were specified.
12. It loads your init file (see Section 40.1.2 [Init File], page 1075). This is not done if the
options ‘-q’, ‘-Q’, or ‘--batch’ were specified. If the ‘-u’ option was specified, Emacs
looks for the init file in that user’s home directory instead.
13. It loads the library default, if it exists. This is not done if inhibit-default-init is
non-nil, nor if the options ‘-q’, ‘-Q’, or ‘--batch’ were specified.
14. It loads your abbrevs from the file specified by abbrev-file-name, if that file exists
and can be read (see Section 36.3 [Abbrev Files], page 910). This is not done if the
option ‘--batch’ was specified.
15. It calls the function package-initialize to activate any optional Emacs Lisp package
that has been installed. See Section 41.1 [Packaging Basics], page 1114. However,
Emacs doesn’t initialize packages when package-enable-at-startup is nil or when
it’s started with one of the options ‘-q’, ‘-Q’, or ‘--batch’. To initialize packages in the
latter case, package-initialize should be called explicitly (e.g., via the ‘--funcall’
option).
16. It sets the variable after-init-time to the value of current-time. This variable was
set to nil earlier; setting it to the current time signals that the initialization phase is
over, and, together with before-init-time, provides the measurement of how long it
took.
17. It runs the normal hook after-init-hook.
18. If the buffer *scratch* exists and is still in Fundamental mode (as it should be by
default), it sets its major mode according to initial-major-mode.
19. If started on a text terminal, it loads the terminal-specific Lisp library (see
Section 40.1.3 [Terminal-Specific], page 1076), and runs the hook tty-setup-hook.
This is not done in --batch mode, nor if term-file-prefix is nil.
20. It displays the initial echo area message, unless you have suppressed that with
inhibit-startup-echo-area-message.
21. It processes any command-line options that were not handled earlier.
22. It now exits if the option --batch was specified.
23. If the *scratch* buffer exists and is empty, it inserts (substitute-command-keys
initial-scratch-message) into that buffer.
24. If initial-buffer-choice is a string, it visits the file (or directory) with that name.
If it is a function, it calls the function with no arguments and selects the buffer that it
returns. If one file is given as a command line argument, that file is visited and its buffer
displayed alongside initial-buffer-choice. If more than one file is given, all of the
Chapter 40: Operating System Interface 1074
files are visited and the *Buffer List* buffer is displayed alongside initial-buffer-
choice.
25. It runs emacs-startup-hook.
26. It calls frame-notice-user-settings, which modifies the parameters of the selected
frame according to whatever the init files specify.
27. It runs window-setup-hook. The only difference between this hook and
emacs-startup-hook is that this one runs after the previously mentioned
modifications to the frame parameters.
28. It displays the startup screen, which is a special buffer that contains information about
copyleft and basic Emacs usage. This is not done if inhibit-startup-screen or
initial-buffer-choice are non-nil, or if the ‘--no-splash’ or ‘-Q’ command-line
options were specified.
29. If a daemon was requested, it calls server-start. (On POSIX systems, if a background
daemon was requested, it then detaches from the controlling terminal.) See Section
“Emacs Server” in The GNU Emacs Manual.
30. If started by the X session manager, it calls emacs-session-restore passing it as
argument the ID of the previous session. See Section 40.18 [Session Management],
page 1102.
The following options affect some aspects of the startup sequence.
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 (site-start.el,
your init file, and default.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 (site-start.el,
your init file, and default.el), before loading the terminal-specific library (if started
on a text terminal) and processing the command-line action arguments.
emacs-startup-hook [Variable]
This normal hook is run, once, just after handling the command line arguments. In
batch mode, Emacs does not run this hook.
window-setup-hook [Variable]
This normal hook is very similar to emacs-startup-hook. The only difference is
that it runs slightly later, after setting of the frame parameters. See Section 40.1.1
[Startup Summary], page 1072.
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.
user-emacs-directory [Variable]
This variable holds the name of the .emacs.d directory. It is ~/.emacs.d on all
platforms but MS-DOS.
The usual role of a terminal-specific library is to enable special keys to send sequences
that Emacs can recognize. It may also need to set or add to input-decode-map if the Term-
cap or Terminfo entry does not specify all the terminal’s function keys. See Section 40.13
[Terminal Input], page 1097.
When the name of the terminal type contains a hyphen or underscore, and no library
is found whose name is identical to the terminal’s name, Emacs strips from the terminal’s
name the last hyphen or underscore 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
or underscores in the name (i.e., there is no terminal-specific library). For example, if
the terminal name is ‘xterm-256color’ and there is no term/xterm-256color.el library,
Emacs tries to load term/xterm.el. If necessary, the terminal 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.
You can also arrange to override some of the actions of the terminal-specific library by
using tty-setup-hook. This is a normal hook that Emacs runs after initializing a new text
terminal. You could use this hook to define initializations for terminals that do not have
their own libraries. See Section 23.1 [Hooks], page 453.
term-file-prefix [User Option]
If the value of this variable is non-nil, Emacs loads a terminal-specific initialization
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.
On MS-DOS, Emacs sets the TERM environment variable to ‘internal’.
term-file-aliases [User Option]
This variable is an association list mapping terminal types to their aliases. For exam-
ple, an element of the form ("vt102" . "vt100") means to treat a terminal of type
‘vt102’ like one of type ‘vt100’.
tty-setup-hook [Variable]
This variable is a normal hook that Emacs runs after initializing a new text terminal.
(This applies when Emacs starts up in non-windowed mode, and when making a tty
emacsclient connection.) The hook runs after loading your init file (if applicable)
and the terminal-specific Lisp file, so you can use it to adjust the definitions made by
that file.
For a related feature, see Section 40.1.2 [Init File], page 1075.
command-line [Function]
This function parses the command line that Emacs was called with, processes it, and
(amongst other things) 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 (see Section E.1 [Building Emacs],
page 1156), 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]
This variable is an alist of user-defined command-line options and associated handler
functions. By default it is empty, but you can add elements if you wish.
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 (see below). (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-args-left [Variable]
The value of this variable is the list of command-line arguments that have not yet
been processed.
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
Chapter 40: Operating System Interface 1079
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 treated as a file name to
visit.
The kill-emacs function is normally called via the higher-level command C-x C-c
(save-buffers-kill-terminal). See Section “Exiting” in The GNU Emacs Manual. It
is also called automatically if Emacs receives a SIGTERM or SIGHUP operating system signal
(e.g., when the controlling terminal is disconnected), or if it receives a SIGINT signal while
running in batch mode (see Section 40.17 [Batch Mode], page 1101).
kill-emacs-hook [Variable]
This normal hook is run by kill-emacs, before it kills Emacs.
Because kill-emacs can be called in situations where user interaction is impossible
(e.g., when the terminal is disconnected), functions on this hook should not attempt
to interact with the user. If you want to interact with the user when Emacs is shutting
down, use kill-emacs-query-functions, described below.
When Emacs is killed, all the information in the Emacs process, aside from files that
have been saved, is lost. Because killing Emacs inadvertently can lose a lot of work, the
save-buffers-kill-terminal command queries for confirmation if you have buffers that
need saving or subprocesses that are running. It also runs the abnormal hook kill-emacs-
query-functions:
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.
Note that ‘pwd’ is not echoed after Emacs is suspended. But it is read and executed
by the shell.
suspend-hook [Variable]
This variable is a normal hook that Emacs runs before suspending.
suspend-resume-hook [Variable]
This variable is a normal hook that Emacs runs on resuming after a suspension.
suspend-frame [Command]
This command suspends a frame. For GUI frames, it calls iconify-frame (see
Section 29.11 [Visibility of Frames], page 723); for frames on text terminals, it calls
either suspend-emacs or suspend-tty, depending on whether the frame is displayed
on the controlling terminal device or not.
Chapter 40: Operating System Interface 1082
system-configuration [Variable]
This variable holds the standard GNU configuration name for the hardware/software
configuration of your system, as a string. For example, a typical value for a 64-bit
GNU/Linux system is ‘"x86_64-unknown-linux-gnu"’.
system-type [Variable]
The value of this variable is a symbol indicating the type of operating system Emacs
is running on. The possible values are:
aix IBM’s AIX.
berkeley-unix
Berkeley BSD and its variants.
cygwin Cygwin, a POSIX layer on top of MS-Windows.
darwin Darwin (macOS).
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.)
gnu/kfreebsd
A GNU (glibc-based) system with a FreeBSD kernel.
hpux Hewlett-Packard HPUX operating system.
nacl Google Native Client (NaCl) sandboxing system.
ms-dos Microsoft’s DOS. Emacs compiled with DJGPP for MS-DOS binds
system-type to ms-dos even when you run it on MS-Windows.
usg-unix-v
AT&T Unix System V.
windows-nt
Microsoft Windows NT, 9X and later. The value of system-type is
always windows-nt, e.g., even on Windows 10.
We do not wish to add new symbols to make finer distinctions unless it is absolutely
necessary! In fact, we hope to eliminate some of these alternatives in the future.
If you need to make a finer distinction than system-type allows for, you can test
system-configuration, e.g., against a regexp.
system-name [Function]
This function returns the name of the machine you are running on, as a string.
Chapter 40: Operating System Interface 1083
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
⇒ ("PATH=/usr/local/bin:/usr/bin:/bin"
"USER=lewis"
"TERM=xterm"
"SHELL=/bin/bash"
"HOME=/home/lewis"
...)
Chapter 40: Operating System Interface 1084
(load-average t)
⇒ (1.69 0.48 0.36)
The shell command uptime returns similar information.
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.
user-real-login-name [Function]
This function returns the user name corresponding to Emacs’s real UID. This ignores
the effective UID, and the environment variables LOGNAME and USER.
month, day of month, and time of day in that order: the number of characters used
for these fields is always the same, so you can reliably use substring to extract them.
You should count characters from the beginning of the string rather than from the
end, as the year might not have exactly four digits, and additional information may
some day be added at the end.
The argument time, if given, specifies a time to format, instead of the current time.
The optional argument zone defaults to the current time zone rule. See Section 40.6
[Time Zone Rules], page 1087.
(current-time-string)
⇒ "Wed Oct 14 22:21:05 1987"
current-time [Function]
This function returns the current time, represented as a list of four integers (sec-
high sec-low microsec picosec). These integers have trailing zeros on systems
that return time with lower resolutions. On all current machines picosec is a multiple
of 1000, but this may change as higher-resolution clocks become available.
TZ to that string. If it is a list (offset abbr), where offset is an integer number of seconds
east of Universal Time and abbr is a string, the conversion uses a fixed time zone with
the given offset and abbreviation. An integer offset is treated as if it were (offset abbr),
where abbr is a numeric abbreviation on POSIX-compatible platforms and is unspecified
on MS-Windows.
The format of this list is the same as what decode-time accepts (see Section 40.7
[Time Conversion], page 1088), and is described in more detail there. Any element
that cannot be determined from the input will be set to nil. The argument string
should resemble an RFC 822 (or later) or ISO 8601 string, like “Fri, 25 Mar 2016
16:24:56 +0100” or “1998-09-12T12:21:54-0200”, but this function will attempt to
parse less well-formed time strings as well.
format-time-string format-string &optional time zone [Function]
This function converts time (or the current time, if time is omitted or nil) to a
string according to format-string. The conversion uses the time zone rule zone, which
defaults to the current time zone rule. See Section 40.6 [Time Zone Rules], page 1087.
The argument format-string may contain ‘%’-sequences which say to substitute parts
of the time. Here is a table of what the ‘%’-sequences mean:
‘%a’ This stands for the abbreviated name of the day of week.
‘%A’ This stands for the full name of the day of week.
‘%b’ This stands for the abbreviated name of the month.
‘%B’ This stands for the full name of the month.
‘%c’ This is a synonym for ‘%x %X’.
‘%C’ This stands for the century, that is, the year divided by 100, truncated
toward zero. The default field width is 2.
‘%d’ This stands for the day of month, zero-padded.
‘%D’ This is a synonym for ‘%m/%d/%y’.
‘%e’ This stands for the day of month, blank-padded.
‘%F’ This stands for the ISO 8601 date format, i.e., ‘"%Y-%m-%d"’.
‘%g’ This stands for the year corresponding to the ISO week within the century.
‘%G’ This stands for the year corresponding to the ISO week.
‘%h’ This is a synonym for ‘%b’.
‘%H’ This stands for the hour (00–23).
‘%I’ This stands for the hour (01–12).
‘%j’ This stands for the day of the year (001–366).
‘%k’ This stands for the hour (0–23), blank padded.
‘%l’ This stands for the hour (1–12), blank padded.
‘%m’ This stands for the month (01–12).
‘%M’ This stands for the minute (00–59).
‘%n’ This stands for a newline.
‘%N’ This stands for the nanoseconds (000000000–999999999). To ask for fewer
digits, use ‘%3N’ for milliseconds, ‘%6N’ for microseconds, etc. Any excess
digits are discarded, without rounding.
Chapter 40: Operating System Interface 1091
The characters ‘E’ and ‘O’ act as modifiers when used after any flags and field widths
in a ‘%’-sequence. ‘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.
To help debug programs, unrecognized ‘%’-sequences stand for themselves and are
output as-is. Programs should not rely on this behavior, as future versions of Emacs
may recognize new ‘%’-sequences as extensions.
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 863);
after strftime returns the resulting string, format-time-string decodes the string
using that same coding system.
You can also specify the field width by following the ‘%’ with a number; shorter
numbers will be padded with blanks. An optional period before the width requests
zero-padding instead. For example, "%.3Y" might produce "004 years".
Warning: This function works only with values of seconds that don’t exceed
most-positive-fixnum (see Section 3.1 [Integer Basics], page 35).
get-internal-run-time [Function]
This function returns the processor run time used by Emacs as a list of four integers:
(sec-high sec-low microsec picosec), using the same format as current-time
(see Section 40.5 [Time of Day], page 1086).
Note that the time returned by this function excludes the time Emacs was not using
the processor, and if the Emacs process has several threads, the returned value is the
sum of the processor times used up by all Emacs threads.
If the system doesn’t provide a way to determine the processor run time,
get-internal-run-time returns the same time as current-time.
emacs-init-time [Command]
This function returns the duration of the Emacs initialization (see Section 40.1.1
[Startup Summary], page 1072) in seconds, as a string. When called interactively, it
prints the duration in the echo area.
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, as a time value. If
you need the difference in units of elapsed seconds, use float-time (see Section 40.5
[Time of Day], page 1086) to convert the result into seconds.
Chapter 40: Operating System Interface 1094
time-add t1 t2 [Function]
This returns the sum of two time values, as a time value. One argument should
represent a time difference rather than a point in time, either as a list or as a single
number of elapsed seconds. Here is how to add a number of seconds to a time value:
(time-add time seconds)
time-to-days time-value [Function]
This function returns the number of days between the beginning of year 1 and time-
value.
time-to-day-in-year time-value [Function]
This returns the day number within the year corresponding to time-value.
date-leap-year-p year [Function]
This function returns t if year is a leap year.
A repeating timer nominally ought to run every repeat seconds, but remember that any
invocation of a timer can be late. Lateness of one repetition has no effect on the scheduled
time of the next repetition. For instance, if Emacs is busy computing for long enough to
cover three scheduled repetitions of the timer, and then starts to wait, it will immediately
call the timer function three times in immediate succession (presuming no other timers
trigger before or between them). If you want a timer to run again no less than n seconds
after the last invocation, don’t use the repeat argument. Instead, the timer function should
explicitly reschedule the timer.
execution of body is cut short by the timeout, then with-timeout executes all the
timeout-forms and returns the value of the last of them.
This macro works by setting a timer to run after seconds seconds. If body finishes be-
fore that time, it cancels the timer. If the timer actually runs, it terminates execution
of body, then executes timeout-forms.
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.
The function y-or-n-p-with-timeout provides a simple way to use a timer to avoid
waiting too long for an answer. See Section 20.7 [Yes-or-No Queries], page 359.
cancel-timer timer [Function]
This cancels the requested action for timer, which should be a timer—usually, one
previously returned by run-at-time or run-with-idle-timer. This cancels the
effect of that call to one of these functions; the arrival of the specified time will not
cause anything special to happen.
The list-timers command lists all the currently active timers. There’s only one com-
mand available in the buffer displayed: c (timer-list-cancel) that will cancel the timer
on the line under point.
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.
Do not write an idle timer function containing a loop which does a certain amount of
processing each time around, and exits when (input-pending-p) is non-nil. This 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.
Similarly, do not write an idle timer function that sets up another idle timer (including
the same idle timer) with secs argument less than or equal to the current idleness time.
Such a timer will run almost immediately, and continue running again and again, instead of
waiting for the next time Emacs becomes idle. The correct approach is to reschedule with
an appropriate increment of the current value of the idleness time, as described below.
current-idle-time [Function]
If Emacs is idle, this function returns the length of time Emacs has been idle, as a
list of four integers: (sec-high sec-low microsec picosec), using the same format
as current-time (see Section 40.5 [Time of Day], page 1086).
When Emacs is not idle, current-idle-time returns nil. This is a convenient way
to test whether Emacs is idle.
The main use of current-idle-time 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 my-resume-timer nil
"Timer for `my-timer-function' to reschedule itself, or nil.")
(defun my-timer-function ()
;; If the user types a command while my-resume-timer
;; is active, the next time this function is called from
;; its main idle timer, deactivate my-resume-timer.
(when my-resume-timer
(cancel-timer my-resume-timer))
...do the work for a while...
(when taking-a-break
(setq my-resume-timer
(run-with-idle-timer
;; Compute an idle time break-length
;; more than the current value.
(time-add (current-idle-time) break-length)
nil
'my-timer-function))))
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.
problems where Emacs garbles the screen, problems that are due to incorrect Termcap
entries or to undesirable settings of terminal options more often than to actual Emacs
bugs. Once you are certain which characters were actually output, you can determine
reliably whether they correspond to the Termcap specifications in use.
(open-termscript "../junk/termscript")
⇒ nil
You close the termscript file by calling this function with an argument of nil.
See also open-dribble-file in Section 40.13.2 [Recording Input], page 1098.
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
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 Terminals], page 685.
You can specify which keysyms Emacs should use for the Control, Meta, Alt, Hyper,
and Super modifiers by setting these variables:
x-ctrl-keysym [Variable]
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 Control modifier (respectively, for
Alt, 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)
come from the minibuffer is read from the standard input descriptor. Thus, Emacs behaves
much like a noninteractive application program. (The echo area output that Emacs itself
normally generates, such as command echoing, is suppressed entirely.)
Non-ASCII text written to the standard output or error descriptors is by default encoded
using locale-coding-system (see Section 33.12 [Locales], page 863) if it is non-nil; this
can be overridden by binding coding-system-for-write to a coding system of you choice
(see Section 33.10.7 [Explicit Encoding], page 859).
noninteractive [Variable]
This variable is non-nil when Emacs is running in batch mode.
emacs-save-session-functions [Variable]
Emacs supports saving state via a hook called emacs-save-session-functions.
Emacs runs this hook when the session manager tells it 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, called the session file.
Subsequently, when the session manager restarts Emacs, it loads the session file au-
tomatically (see Chapter 16 [Loading], page 263). This is performed by a function
named emacs-session-restore, which is called during startup. See Section 40.1.1
[Startup Summary], page 1072.
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-current-buffer
(switch-to-buffer \"*scratch*\")
(insert \"I am restored\"))")
nil)
Chapter 40: Operating System Interface 1103
:action-items
When this keyword is given, the title string of the actions is interpreted
as icon name.
:category category
The type of notification this is, a string. See the Desktop Notifications
Specification (http://developer.gnome.org/notification-spec/ #
categories) for a list of standard categories.
:desktop-entry filename
This specifies the name of the desktop filename representing the calling
program, like ‘"emacs"’.
:image-data (width height rowstride has-alpha bits channels data)
This is a raw data image format that describes the width, height, row-
stride, whether there is an alpha channel, bits per sample, channels and
image data, respectively.
:image-path path
This is represented either as a URI (‘file://’ is the only URI schema
supported right now) or a name in a freedesktop.org-compliant icon theme
from ‘$XDG_DATA_DIRS/icons’.
:sound-file filename
The path to a sound file to play when the notification pops up.
:sound-name name
A themable named sound from the freedesktop.org sound naming spec-
ification from ‘$XDG_DATA_DIRS/sounds’, to play when the notification
pops up. Similar to the icon name, only for sounds. An example would
be ‘"message-new-instant"’.
:suppress-sound
Causes the server to suppress playing any sounds, if it has that ability.
:resident
When set the server will not automatically remove the notification when
an action has been invoked. The notification will remain resident in the
server until it is explicitly removed by the user or by the sender. This hint
is likely only useful when the server has the :persistence capability.
:transient
When set the server will treat the notification as transient and by-pass
the server’s persistence capability, if it should exist.
:x position
:y position
Specifies the X, Y location on the screen that the notification should point
to. Both arguments must be used together.
:on-action function
Function to call when an action is invoked. The notification id and the
key of the action are passed as arguments to the function.
Chapter 40: Operating System Interface 1105
:on-close function
Function to call when the notification has been closed by timeout or by
the user. The function receive the notification id and the closing reason
as arguments:
• expired if the notification has expired
• dismissed if the notification was dismissed by the user
• close-notification if the notification was closed by a call to
notifications-close-notification
• undefined if the notification server hasn’t provided a reason
Which parameters are accepted by the notification server can be checked via
notifications-get-capabilities.
This function returns a notification id, an integer, which can be used to manipulate the
notification item with notifications-close-notification or the :replaces-id
argument of another notifications-notify call. For example:
(defun my-on-action-function (id key)
(message "Message %d, key \"%s\" pressed" id key))
⇒ my-on-action-function
(notifications-notify
:title "Title"
:body "This is <b>important</b>."
:actions '("Confirm" "I agree" "Refuse" "I disagree")
:on-action 'my-on-action-function
:on-close 'my-on-close-function)
⇒ 22
:body-hyperlinks
The server supports hyperlinks in the notifications.
:body-images
The server supports images in the notifications.
:body-markup
Supports markup in the body text.
:icon-multi
The server will render an animation of all the frames in a given image
array.
:icon-static
Supports display of exactly 1 frame of any given image array. This value
is mutually exclusive with :icon-multi.
:persistence
The server supports persistence of notifications.
:sound The server supports sounds on notifications.
Further vendor-specific caps start with :x-vendor, like :x-gnome-foo-cap.
When Emacs runs on MS-Windows as a GUI session, it supports a small subset of the
D-Bus notifications functionality via a native primitive:
To remove the notification and its icon from the taskbar, use the following function:
w32-notification-close id [Function]
This function removes the tray notification given by its unique id.
Since all these libraries emit different events on notified file changes, there is the Emacs
library filenotify which provides a unified interface. Lisp programs that want to receive
file notifications should always use this library in preference to the native ones.
file-notify-add-watch file flags callback [Function]
Add a watch for filesystem events pertaining to file. This arranges for filesystem
events pertaining to file to be reported to Emacs.
The returned value is a descriptor for the added watch. Its type depends on the
underlying library, it cannot be assumed to be an integer as in the example below. It
should be used for comparison by equal only.
If the file cannot be watched for some reason, this function signals a file-notify-
error error.
Sometimes, mounted filesystems cannot be watched for file changes. This is not
detected by this function, a non-nil return value does not guarantee that changes on
file will be notified.
flags is a list of conditions to set what will be watched for. It can include the following
symbols:
change watch for file changes
attribute-change
watch for file attribute changes, like permissions or modification time
If file is a directory, changes for all files in that directory will be notified. This does
not work recursively.
When any event happens, Emacs will call the callback function passing it a single
argument event, which is of the form
(descriptor action file [file1])
descriptor is the same object as the one returned by this function. action is the
description of the event. It could be any one of the following symbols:
created file was created
deleted file was deleted
changed file’s contents has changed; with w32notify library, reports attribute
changes as well
renamed file has been renamed to file1
attribute-changed
a file attribute was changed
stopped watching file has been stopped
Note that the w32notify library does not report attribute-changed events. When
some file’s attribute, like permissions or modification time, has changed, this library
reports a changed event. Likewise, the kqueue library does not report reliably file
attribute changes when watching a directory.
The stopped event reports, that watching the file has been stopped. This could
be because file-notify-rm-watch was called (see below), or because the file being
watched was deleted, or due to another error reported from the underlying library.
Chapter 40: Operating System Interface 1109
file and file1 are the name of the file(s) whose event is being reported. For example:
(require 'filenotify)
⇒ filenotify
(file-notify-add-watch
"/tmp" '(change attribute-change) 'my-notify-callback)
⇒ 35025468
(delete-file "/tmp/bla")
⇒ Event (35025468 deleted "/tmp/bla")
(setq desc
(file-notify-add-watch
"/tmp/foo" '(change) 'my-notify-callback))
⇒ 11359632
(file-notify-valid-p desc)
⇒ t
(file-notify-valid-p desc)
⇒ nil
dynamic-library-alist [Variable]
This is an alist of dynamic libraries and external library files implementing them.
Each element is a list of the form (library files...), where the car is a symbol
representing a supported external library, and the rest are strings giving alternate
filenames for that library.
Chapter 40: Operating System Interface 1111
Emacs tries to load the library from the files in the order they appear in the list; if
none is found, the Emacs session won’t have access to that library, and the features
it provides will be unavailable.
Image support on some platforms uses this facility. Here’s an example of setting this
variable for supporting images on MS-Windows:
(setq dynamic-library-alist
'((xpm "libxpm.dll" "xpm4.dll" "libXpm-nox4.dll")
(png "libpng12d.dll" "libpng12.dll" "libpng.dll"
"libpng13d.dll" "libpng13.dll")
(jpeg "jpeg62.dll" "libjpeg.dll" "jpeg-62.dll"
"jpeg.dll")
(tiff "libtiff3.dll" "libtiff.dll")
(gif "giflib4.dll" "libungif4.dll" "libungif.dll")
(svg "librsvg-2-2.dll")
(gdk-pixbuf "libgdk_pixbuf-2.0-0.dll")
(glib "libglib-2.0-0.dll")
(gobject "libgobject-2.0-0.dll")))
Note that image types pbm and xbm do not need entries in this variable because they
do not depend on external libraries and are always available in Emacs.
Also note that this variable is not meant to be a generic facility for accessing external
libraries; only those already known by Emacs can be loaded through it.
This variable is ignored if the given library is statically linked into Emacs.
can have handlers that treat the files specially, with their own access checking.
See Section 25.12 [Magic File Names], page 559. Also, a buffer can be read-
only even if the corresponding file is writable, and vice versa, which can result
in messages such as ‘File passwd is write-protected; try to save anyway?
(yes or no)’. See Section 27.7 [Read Only Buffers], page 590.
Authentication
Emacs has several functions that deal with passwords, e.g., read-passwd. See
Section 20.9 [Reading a Password], page 363. Although these functions do
not attempt to broadcast passwords to the world, their implementations are
not proof against determined attackers with access to Emacs internals. For
example, even if Elisp code uses clear-string to scrub a password from its
memory after using it, remnants of the password may still reside in the garbage-
collected free list. See Section 4.4 [Modifying Strings], page 54.
Code injection
Emacs can send commands to many other applications, and applications should
take care that strings sent as operands of these commands are not misinter-
preted as directives. For example, when using a shell command to rename a file
a to b, do not simply use the string mv a b, because either file name might start
with ‘-’, or might contain shell metacharacters like ‘;’. Although functions
like shell-quote-argument can help avoid this sort of problem, they are not
panaceas; for example, on a POSIX platform shell-quote-argument quotes
shell metacharacters but not leading ‘-’. On MS-Windows, quoting for ‘%’ as-
sumes none of the environment variables have ‘^’ in their name. See Section 38.2
[Shell Arguments], page 921. Typically it is safer to use call-process than a
subshell. See Section 38.3 [Synchronous Processes], page 922. And it is safer
yet to use builtin Emacs functions; for example, use (rename-file "a" "b" t)
instead of invoking mv. See Section 25.7 [Changing Files], page 541.
Coding systems
Emacs attempts to infer the coding systems of the files and network connections
it accesses. See Section 33.10 [Coding Systems], page 848. If Emacs infers
incorrectly, or if the other parties to the network connection disagree with
Emacs’s inferences, the resulting system could be unreliable. Also, even when
it infers correctly, Emacs often can use bytes that other programs cannot. For
example, although to Emacs the null byte is just a character like any other,
many other applications treat it as a string terminator and mishandle strings
or files containing null bytes.
Emacs then searches every Lisp file in the content directory for autoload magic comments
(see Section 16.5 [Autoload], page 268). These autoload definitions are saved to a file
named name-autoloads.el in the content directory. They are typically used to autoload
the principal user commands defined in the package, but they can also perform other tasks,
such as adding an element to auto-mode-alist (see Section 23.2.2 [Auto Major Mode],
page 459). Note that a package typically does not autoload every function and variable
defined within it—only the handful of commands typically called to begin using the package.
Emacs then byte-compiles every Lisp file in the package.
After installation, the installed package is loaded: Emacs adds the package’s content
directory to load-path, and evaluates the autoload definitions in name-autoloads.el.
Whenever Emacs starts up, it automatically calls the function package-initialize to
load installed packages. This is done after loading the init file and abbrev file (if any)
and before running after-init-hook (see Section 40.1.1 [Startup Summary], page 1072).
Automatic package loading is disabled if the user option package-enable-at-startup is
nil.
package-initialize &optional no-activate [Command]
This function initializes Emacs’ internal record of which packages are installed, and
loads them. The user option package-load-list specifies which packages to load; by
default, all installed packages are loaded. If called during startup, this function also
sets package-enable-at-startup to nil, to avoid accidentally loading the packages
twice. See Section “Package Installation” in The GNU Emacs Manual.
The optional argument no-activate, if non-nil, causes Emacs to update its record of
installed packages without actually loading them; it is for internal use only.
...
;;; Commentary:
...
;;;###autoload
(define-minor-mode superfrobnicator-mode
...
The name of the package is the same as the base name of the file, as written on the first
line. Here, it is ‘superfrobnicator’.
The brief description is also taken from the first line. Here, it is ‘Frobnicate and
bifurcate flanges’.
The version number comes from the ‘Package-Version’ header, if it exists, or from the
‘Version’ header otherwise. One or the other must be present. Here, the version number
is 1.3.
If the file has a ‘;;; Commentary:’ section, this section is used as the long description.
(When displaying the description, Emacs omits the ‘;;; Commentary:’ line, as well as the
leading comment characters in the commentary itself.)
If the file has a ‘Package-Requires’ header, that is used as the package dependencies.
In the above example, the package depends on the ‘flange’ package, version 1.0 or higher.
See Section D.8 [Library Headers], page 1152, for a description of the ‘Package-Requires’
header. If the header is omitted, the package has no dependencies.
The ‘Keywords’ and ‘URL’ headers are optional, but recommended. The command
describe-package uses these to add links to its output. The ‘Keywords’ header should
contain at least one standard keyword from the finder-known-keywords list.
The file ought to also contain one or more autoload magic comments, as explained
in Section 41.1 [Packaging Basics], page 1114. In the above example, a magic comment
autoloads superfrobnicator-mode.
See Section 41.4 [Package Archives], page 1117, for an explanation of how to add a
single-file package to a package archive.
A package archive is simply a directory in which the package files, and associated files,
are stored. If you want the archive to be reachable via HTTP, this directory must be
accessible to a web server. How to accomplish this is beyond the scope of this manual.
A convenient way to set up and update a package archive is via the package-x li-
brary. This is included with Emacs, but not loaded by default; type M-x load-library
RET package-x RET to load it, or add (require 'package-x) to your init file. See Section
“Lisp Libraries” in The GNU Emacs Manual.
After you create an archive, remember that it is not accessible in the Package Menu interface
unless it is in package-archives.
Maintaining a public package archive entails a degree of responsibility. When Emacs
users install packages from your archive, those packages can cause Emacs to run arbitrary
code with the permissions of the installing user. (This is true for Emacs code in general,
not just for packages.) So you should ensure that your archive is well-maintained and keep
the hosting system secure.
One way to increase the security of your packages is to sign them using a cryptographic
key. If you have generated a private/public gpg key pair, you can use gpg to sign the
package like this:
gpg -ba -o file.sig file
For a single-file package, file is the package Lisp file; for a multi-file package, it is the
package tar file. You can also sign the archive’s contents file in the same way. Make the
.sig files available in the same location as the packages. You should also make your public
key available for people to download; e.g., by uploading it to a key server such as http://
pgp.mit.edu/. When people install packages from your archive, they can use your public
key to verify the signatures.
A full explanation of these matters is outside the scope of this manual. For more informa-
tion on cryptographic keys and signing, see Section “GnuPG” in The GNU Privacy Guard
Manual. Emacs comes with an interface to GNU Privacy Guard, see Section “EasyPG” in
Emacs EasyPG Assistant Manual.
1119
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.
The “publisher” means any person or entity that distributes copies of the Document
to the public.
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 1125
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:
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,
Appendix B: GNU Free Documentation License 1126
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 Docu-
ment, 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
your option designate some or all of these sections as invariant. To do this, add their
Appendix B: GNU Free Documentation License 1127
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
document, and follow this License in all other respects regarding verbatim copying of
that document.
Appendix B: GNU Free Documentation License 1128
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of
works.
The licenses for most software and other practical works are designed to take away your
freedom to share and change the works. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change all versions of a program—to make
sure it remains free software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to any other work
released this way by its authors. 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 them 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 prevent others from denying you these rights or asking
you to surrender the rights. Therefore, you have certain responsibilities if you distribute
copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you
must pass on to the recipients the same freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copy-
right on the software, and (2) offer you this License giving you legal permission to copy,
distribute and/or modify it.
For the developers’ and authors’ protection, the GPL clearly explains that there is no
warranty for this free software. For both users’ and authors’ sake, the GPL requires that
modified versions be marked as changed, so that their problems will not be attributed
erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the
software inside them, although the manufacturer can do so. This is fundamentally incom-
patible with the aim of protecting users’ freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to use, which is pre-
cisely where it is most unacceptable. Therefore, we have designed this version of the GPL
to prohibit the practice for those products. If such problems arise substantially in other
domains, we stand ready to extend this provision to those domains in future versions of the
GPL, as needed to protect the freedom of users.
Appendix C: GNU General Public License 1132
Finally, every program is threatened constantly by software patents. States should not
allow patents to restrict development and use of software on general-purpose computers, but
in those that do, we wish to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL assures that patents cannot
be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
The “System Libraries” of an executable work include anything, other than the work as
a whole, that (a) is included in the normal form of packaging a Major Component, but
which is not part of that Major Component, and (b) serves only to enable use of the
work with that Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A “Major Component”,
in this context, means a major essential component (kernel, window system, and so
on) of the specific operating system (if any) on which the executable work runs, or a
compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code
needed to generate, install, and (for an executable work) run the object code and to
modify the work, including scripts to control those activities. However, it does not
include the work’s System Libraries, or general-purpose tools or generally available
free programs which are used unmodified in performing those activities but which are
not part of the work. For example, Corresponding Source includes interface definition
files associated with source files for the work, and the source code for shared libraries
and dynamically linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those subprograms
and other parts of the work.
The Corresponding Source need not include anything that users can regenerate auto-
matically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License ex-
plicitly affirms your unlimited permission to run the unmodified Program. The output
from running a covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your rights of fair use
or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do
so exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users’ Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under
any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
Appendix C: GNU General Public License 1134
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising rights
under this License with respect to the covered work, and you disclaim any intention
to limit operation or modification of the work as a means of enforcing, against the
work’s users, your or third parties’ legal rights to forbid circumvention of technological
measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program’s source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code; keep intact all
notices of the absence of any warranty; and give all recipients a copy of this License
along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
a. The work must carry prominent notices stating that you modified it, and giving a
relevant date.
b. The work must carry prominent notices stating that it is released under this Li-
cense and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
c. You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license
the work in any other way, but it does not invalidate such permission if you have
separately received it.
d. If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which
are not by their nature extensions of the covered work, and which are not combined
with it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting copyright are
not used to limit the access or legal rights of the compilation’s users beyond what the
individual works permit. Inclusion of a covered work in an aggregate does not cause
this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under
the terms of this License, in one of these ways:
Appendix C: GNU General Public License 1135
a. Convey the object code in, or embodied in, a physical product (including a phys-
ical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
b. Convey the object code in, or embodied in, a physical product (including a physi-
cal distribution medium), accompanied by a written offer, valid for at least three
years and valid for as long as you offer spare parts or customer support for that
product model, to give anyone who possesses the object code either (1) a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange,
for a price no more than your reasonable cost of physically performing this con-
veying of source, or (2) access to copy the Corresponding Source from a network
server at no charge.
c. Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally
and noncommercially, and only if you received the object code with such an offer,
in accord with subsection 6b.
d. Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same
way through the same place at no further charge. You need not require recipients
to copy the Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source may be on
a different server (operated by you or a third party) that supports equivalent
copying facilities, provided you maintain clear directions next to the object code
saying where to find the Corresponding Source. Regardless of what server hosts
the Corresponding Source, you remain obligated to ensure that it is available for
as long as needed to satisfy these requirements.
e. Convey the object code using peer-to-peer transmission, provided you inform other
peers where the object code and Corresponding Source of the work are being offered
to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Cor-
responding Source as a System Library, need not be included in conveying the object
code work.
A “User Product” is either (1) a “consumer product”, which means any tangible per-
sonal property which is normally used for personal, family, or household purposes, or
(2) anything designed or sold for incorporation into a dwelling. In determining whether
a product is a consumer product, doubtful cases shall be resolved in favor of coverage.
For a particular product received by a particular user, “normally used” refers to a
typical or common use of that class of product, regardless of the status of the par-
ticular user or of the way in which the particular user actually uses, or expects or is
expected to use, the product. A product is a consumer product regardless of whether
the product has substantial commercial, industrial or non-consumer uses, unless such
uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, autho-
rization keys, or other information required to install and execute modified versions of a
covered work in that User Product from a modified version of its Corresponding Source.
Appendix C: GNU General Public License 1136
The information must suffice to ensure that the continued functioning of the modified
object code is in no case prevented or interfered with solely because modification has
been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient in
perpetuity or for a fixed term (regardless of how the transaction is characterized),
the Corresponding Source conveyed under this section must be accompanied by the
Installation Information. But this requirement does not apply if neither you nor any
third party retains the ability to install modified object code on the User Product (for
example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement
to continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an implementa-
tion available to the public in source code form), and must require no special password
or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by mak-
ing exceptions from one or more of its conditions. Additional permissions that are
applicable to the entire Program shall be treated as though they were included in this
License, to the extent that they are valid under applicable law. If additional permis-
sions apply only to part of the Program, that part may be used separately under those
permissions, but the entire Program remains governed by this License without regard
to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional permissions
may be written to require their own removal in certain cases when you modify the
work.) You may place additional permissions on material, added by you to a covered
work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered
work, you may (if authorized by the copyright holders of that material) supplement
the terms of this License with terms:
a. Disclaiming warranty or limiting liability differently from the terms of sections 15
and 16 of this License; or
b. Requiring preservation of specified reasonable legal notices or author attributions
in that material or in the Appropriate Legal Notices displayed by works containing
it; or
c. Prohibiting misrepresentation of the origin of that material, or requiring that mod-
ified versions of such material be marked in reasonable ways as different from the
original version; or
Appendix C: GNU General Public License 1137
d. Limiting the use for publicity purposes of names of licensors or authors of the
material; or
e. Declining to grant rights under trademark law for use of some trade names, trade-
marks, or service marks; or
f. Requiring indemnification of licensors and authors of that material by anyone who
conveys the material (or modified versions of it) with contractual assumptions
of liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within
the meaning of section 10. If the Program as you received it, or any part of it, con-
tains a notice stating that it is governed by this License along with a term that is a
further restriction, you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you may add to a
covered work material governed by the terms of that license document, provided that
the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the
relevant source files, a statement of the additional terms that apply to those files, or a
notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a sep-
arately written license, or stated as exceptions; the above requirements apply either
way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided un-
der this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular
copyright holder is reinstated (a) provisionally, unless and until the copyright holder
explicitly and finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means prior to 60 days
after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if
the copyright holder notifies you of the violation by some reasonable means, this is the
first time you have received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after your receipt of the
notice.
Termination of your rights under this section does not terminate the licenses of parties
who have received copies or rights from you under this License. If your rights have
been terminated and not permanently reinstated, you do not qualify to receive new
licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require acceptance.
Appendix C: GNU General Public License 1138
However, nothing other than this License grants you permission to propagate or modify
any covered work. These actions infringe copyright if you do not accept this License.
Therefore, by modifying or propagating a covered work, you indicate your acceptance
of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an organization, or
substantially all assets of one, or subdividing an organization, or merging organizations.
If propagation of a covered work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever licenses to the work
the party’s predecessor in interest had or could give under the previous paragraph, plus
a right to possession of the Corresponding Source of the work from the predecessor in
interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty, or
other charge for exercise of rights granted under this License, and you may not initiate
litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent
claim is infringed by making, using, selling, offering for sale, or importing the Program
or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the
Program or a work on which the Program is based. The work thus licensed is called
the contributor’s “contributor version”.
A contributor’s “essential patent claims” are all patent claims owned or controlled by
the contributor, whether already acquired or hereafter acquired, that would be infringed
by some manner, permitted by this License, of making, using, or selling its contributor
version, but do not include claims that would be infringed only as a consequence of
further modification of the contributor version. For purposes of this definition, “con-
trol” includes the right to grant patent sublicenses in a manner consistent with the
requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor’s essential patent claims, to make, use, sell, offer for sale, import
and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or com-
mitment, however denominated, not to enforce a patent (such as an express permission
to practice a patent or covenant not to sue for patent infringement). To “grant” such
a patent license to a party means to make such an agreement or commitment not to
enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corre-
sponding Source of the work is not available for anyone to copy, free of charge and under
the terms of this License, through a publicly available network server or other readily
accessible means, then you must either (1) cause the Corresponding Source to be so
Appendix C: GNU General Public License 1139
available, or (2) arrange to deprive yourself of the benefit of the patent license for this
particular work, or (3) arrange, in a manner consistent with the requirements of this
License, to extend the patent license to downstream recipients. “Knowingly relying”
means you have actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient’s use of the covered work in a country,
would infringe one or more identifiable patents in that country that you have reason
to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey,
or propagate by procuring conveyance of, a covered work, and grant a patent license
to some of the parties receiving the covered work authorizing them to use, propagate,
modify or convey a specific copy of the covered work, then the patent license you grant
is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its cover-
age, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the
rights that are specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is in the business of
distributing software, under which you make payment to the third party based on the
extent of your activity of conveying the work, and under which the third party grants,
to any of the parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work conveyed by you (or
copies made from those copies), or (b) primarily for and in connection with specific
products or compilations that contain the covered work, unless you entered into that
arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or
other defenses to infringement that may otherwise be available to you under applicable
patent law.
12. No Surrender of Others’ Freedom.
If 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 convey a covered work so as to satisfy simultaneously
your obligations under this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to terms that
obligate you to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this License would
be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License, section 13,
concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
Appendix C: GNU General Public License 1140
The Free Software Foundation may publish revised and/or new versions of the GNU
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 that
a certain numbered version of the GNU General Public License “or any later version”
applies to it, you have the option of following the terms and conditions either of that
numbered version or of any later version published by the Free Software Foundation.
If the Program does not specify a version number of the GNU General Public License,
you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy’s public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of your
choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PER-
MITTED BY APPLICABLE 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 EX-
PRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE
OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFEC-
TIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO
MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, IN-
CIDENTAL 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 SUS-
TAINED 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 DAM-
AGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given
local legal effect according to their terms, reviewing courts shall apply local law that
most closely approximates an absolute waiver of all civil liability in connection with
the Program, unless a warranty or assumption of liability accompanies a copy of the
Program in return for a fee.
Appendix C: GNU General Public License 1141
You should have received a copy of the GNU General Public License
along with this program. If not, see https://www.gnu.org/licenses/.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it
starts in an interactive mode:
program Copyright (C) year name of author
This program 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, your program’s commands might be different; for a
GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more information on this,
and how to apply and follow the GNU GPL, see https://www.gnu.org/licenses/.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it more
useful to permit linking proprietary applications with the library. If this is what you want
to do, use the GNU Lesser General Public License instead of this License. But first, please
read https://www.gnu.org/licenses/why-not-lgpl.html.
1142
If one prefix is insufficient, your package can use two or three alternative common
prefixes, so long as they make sense.
• Put a call to provide at the end of each separate Lisp file. See Section 16.7 [Named
Features], page 273.
• If a file requires certain other Lisp programs to be loaded beforehand, then the com-
ments at the beginning of the file should say so. Also, use require to make sure they
are loaded. See Section 16.7 [Named Features], page 273.
• If a file foo uses a macro defined in another file bar, but does not use any functions or
variables defined in bar, then foo should contain the following expression:
(eval-when-compile (require 'bar))
This tells Emacs to load bar just before byte-compiling foo, so that the macro definition
is available during compilation. Using eval-when-compile avoids loading bar when
the compiled version of foo is used. It should be called before the first use of the macro
in the file. See Section 14.3 [Compiling Macros], page 238.
• Avoid loading additional libraries at run time unless they are really needed. If your file
simply cannot work without some other library, then just require that library at the
top-level and be done with it. But if your file contains several independent features,
and only one or two require the extra library, then consider putting require statements
inside the relevant functions rather than at the top-level. Or use autoload statements
to load the extra library when needed. This way people who don’t use those aspects
of your file do not need to load the extra library.
• If you need Common Lisp extensions, use the cl-lib library rather than the old cl
library. The latter does not use a clean namespace (i.e., its definitions do not start with
a ‘cl-’ prefix). If your package loads cl at run time, that could cause name clashes for
users who don’t use that package.
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 package,
because the compiler expands them before generating the byte-code. It is still better
to use the more modern cl-lib in this case, though.
• When defining a major mode, please follow the major mode conventions. See
Section 23.2.1 [Major Mode Conventions], page 456.
• When defining a minor mode, please follow the minor mode conventions. See
Section 23.3.1 [Minor Mode Conventions], page 471.
• 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’ (which stands for “predicate”). 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 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 453.
• If loading the file adds functions to hooks, define a function feature-unload-function,
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 16.9 [Unloading], page 276.
Appendix D: Tips and Conventions 1144
• 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))
• 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.
• It is likewise a bad idea for one Lisp package to advise a function in another Lisp
package (see Section 13.11 [Advising Functions], page 222).
• Avoid using eval-after-load and with-eval-after-load in libraries and packages
(see Section 16.10 [Hooks for Loading], page 277). 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 standard functions or library programs of 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 ‘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.
• 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.) People will
find Emacs more coherent if all libraries use the same conventions.
• The default file coding system for Emacs Lisp source files is UTF-8 (see Section 33.1
[Text Representations], page 835). In the rare event that your program contains char-
acters which are not in UTF-8, you should specify an appropriate coding system in the
source file’s ‘-*-’ line or local variables list. See Section “Local Variables in Files” in
The GNU Emacs Manual.
• Indent the file using the default indentation parameters.
• Don’t make a habit of putting close-parentheses on lines by themselves; Lisp program-
mers find this disconcerting.
• Please put a copyright notice and copying permission notice on the file if you distribute
copies. See Section D.8 [Library Headers], page 1152.
Appendix D: Tips and Conventions 1145
• Don’t call functions that set the mark, unless setting the mark is one of the intended
features of your program. The mark is a user-level feature, so it is incorrect to change
the mark except to supply a value for the user’s benefit. See Section 31.7 [The Mark],
page 760.
In particular, don’t use any of these functions:
• beginning-of-buffer, end-of-buffer
• replace-string, replace-regexp
• insert-file, insert-buffer
If you just want to move point, or replace a certain string, or insert a file or buffer’s
contents, without any of the other features intended for interactive users, you can
replace these functions with one or two lines of simple Lisp code.
• Use lists rather than vectors, except when there is a particular reason to use a vector.
Lisp has more facilities for manipulating lists than for vectors, and working with lists
is usually more convenient.
Vectors are advantageous for tables that are substantial in size and are accessed in
random order (not searched front to back), provided there is no need to insert or delete
elements (only lists allow that).
• The recommended way to show a message in the echo area is with the message function,
not princ. See Section 39.4 [The Echo Area], page 969.
• When you encounter an error condition, call the function error (or signal). The
function error does not return. See Section 11.7.3.1 [Signaling Errors], page 160.
Don’t use message, throw, sleep-for, or beep to report errors.
• An error message should start with a capital letter but should not end with a period.
• A question asked in the minibuffer with yes-or-no-p or y-or-n-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)))
...)
Appendix D: Tips and Conventions 1147
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’. See Section 39.4.2 [Progress], page 971, for an easy way to
generate such messages.
• Try to avoid using recursive edits. Instead, do what the Rmail e command does: use
a new local keymap that contains a command defined to switch back to the old local
keymap. Or simply switch to another buffer and let the user switch back at will. See
Section 21.13 [Recursive Editing], page 410.
(defvar foo)
Such a definition has no effect except to tell the compiler not to warn about uses of
the variable foo in this file.
• Similarly, to avoid a compiler warning about an undefined function that you know will
be defined, use a declare-function statement (see Section 13.15 [Declaring Functions],
page 232).
• If you use many functions, macros, and variables from a certain file, you can add
a require (see Section 16.7 [Named Features], page 273) for that package to avoid
compilation warnings for them, like this:
(require 'foo)
If you need only macros from some file, you can require it only at compile time (see
Section 17.5 [Eval During Compile], page 283). For instance,
(eval-when-compile
(require 'foo))
• If you bind a variable in one function, and use it or set it in another function, the
compiler warns about the latter function unless the variable has a definition. But
adding a definition would be unclean if the variable has a short name, since Lisp
packages should not define short variable names. The right thing to do is to rename
this variable to start with the name prefix used for the other functions and variables
in your package.
• The last resort for avoiding a warning, when you want to do something that is usually
a mistake but you know is not a mistake in your usage, is to put it inside with-no-
warnings. See Section 17.6 [Compiler Errors], page 284.
For a function, the first line should briefly answer the question, “What does this func-
tion do?” For a variable, the first line should briefly answer the question, “What does
this value mean?”
Don’t limit the documentation string to one line; use as many lines as you need to
explain the details of how to use the function or variable. Please use complete sentences
for the rest of the text too.
• When the user tries to use a disabled command, Emacs displays just the first paragraph
of its documentation string—everything through the first blank line. If you wish, you
can choose which information to include before the first blank line so as to make this
display useful.
• The first line should mention all the important arguments of the function, and should
mention them in the order that they are written in a function call. If the function
has many arguments, then it is not feasible to mention them all in the first line; in
that case, the first line should mention the first few arguments, including the most
important arguments.
• When a function’s documentation string mentions the value of an argument of the
function, use the argument name in capital letters as if it were a name for that value.
Thus, the documentation string of the function eval refers to its first argument as
‘FORM’, because the actual argument name is form:
Evaluate FORM and return its value.
Also write metasyntactic variables in capital letters, such as when you show the decom-
position of a list or vector into subunits, some of which may vary. ‘KEY’ and ‘VALUE’ in
the following example illustrate this practice:
The argument TABLE should be an alist whose elements
have the form (KEY . VALUE). Here, KEY is ...
• Never change the case of a Lisp symbol when you mention it in a doc string. If the
symbol’s name is foo, write “foo”, not “Foo” (which is a different symbol).
This might appear to contradict the policy of writing function argument values, but
there is no real contradiction; the argument value is not the same thing as the symbol
that the function uses to hold the value.
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), surrounding it with curved single quotes (‘..’).
There are two exceptions: write t and nil without surrounding punctuation. For
example:
CODE can be ‘lambda’, nil, or t.
See Section “Quotation Marks” in The GNU Emacs Manual, for how to enter curved
single quotes.
Appendix D: Tips and Conventions 1150
Documentation strings can also use an older single-quoting convention, which quotes
symbols with grave accent ‘ and apostrophe ’: ‘like-this’ rather than ‘like-this’.
This older convention was designed for now-obsolete displays in which grave accent and
apostrophe were mirror images. Documentation using this convention is converted to
the user’s preferred format when it is copied into a help buffer. See Section 24.3 [Keys
in Documentation], page 513.
Help mode automatically creates a hyperlink when a documentation string uses a single-
quoted symbol name, 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 single-quoted name of the
Info node (or anchor), 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 single-quoted URL, preceded by ‘URL’.
For example,
The home page for the GNU project has more information (see URL
`https://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
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 513.
• 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 ‘\\<...>’
Appendix D: Tips and Conventions 1151
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”.
• Avoid using “iff” (a mathematics term meaning “if and only if”), since many people
are unfamiliar with it and mistake it for a typo. In most cases, the meaning is clear
with just “if”. Otherwise, try to find an alternate phrasing that conveys the meaning.
• 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 represents an option users might want to set, use
defcustom. See Section 12.5 [Defining Variables], page 173.
• 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 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.
If a function has no documentation string, it 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. It is much better to
convert such comments to documentation strings, though.
‘;;;’ Comments that start with three semicolons, ‘;;;’, should start at the left mar-
gin. We use them for comments which should be considered a heading by Out-
line minor mode. By default, comments starting with at least three semicolons
(followed by a single space and a non-whitespace character) are considered head-
ings, comments starting with two or fewer are not. Historically, triple-semicolon
comments have also been used for commenting out lines within a function, but
this use is discouraged.
When commenting out entire functions, use two semicolons.
‘;;;;’ 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
‘Maintainer’
This header has the same format as the Author header. It lists the person(s)
who currently maintain(s) the file (respond to bug reports, etc.).
If there is no maintainer line, the person(s) in the Author field is/are presumed
to be the maintainers. Some files in Emacs use ‘FSF’ for the maintainer. This
means that the original author is no longer responsible for the file, and that it
is maintained as part of Emacs.
‘Created’ This optional line gives the original creation date of the file, and is for historical
interest only.
‘Version’ If you wish to record version numbers for the individual Lisp program, put them
in this line. Lisp files distributed with Emacs generally do not have a ‘Version’
header, since the version number of Emacs itself serves the same purpose. If
you are distributing a collection of multiple files, we recommend not writing
the version in every file, but only the main one.
‘Keywords’
This line lists keywords for the finder-by-keyword help command. Please use
that command to see a list of the meaningful keywords. The command M-x
Appendix D: Tips and Conventions 1154
checkdoc-package-keywords RET will find and display any keywords that are
not in finder-known-keywords. If you set the variable checkdoc-package-
keywords-flag non-nil, checkdoc commands will include the keyword verifi-
cation in its checks.
This field is how people will find your package when they’re looking for things
by topic. To separate the keywords, you can use spaces, commas, or both.
The name of this field is unfortunate, since people often assume it is the place
to write arbitrary keywords that describe their package, rather than just the
relevant Finder keywords.
‘Homepage’
‘URL’ These lines state the homepage of the library.
‘Package-Version’
If ‘Version’ is not suitable for use by the package manager, then a package can
define ‘Package-Version’; it will be used instead. This is handy if ‘Version’ is
an RCS id or something else that cannot be parsed by version-to-list. See
Section 41.1 [Packaging Basics], page 1114.
‘Package-Requires’
If this exists, it names packages on which the current package depends for
proper operation. See Section 41.1 [Packaging Basics], page 1114. This is used
by the package manager both at download time (to ensure that a complete set
of packages is downloaded) and at activation time (to ensure that a package is
only activated if all its dependencies have been).
Its format is a list of lists on a single line. The car of each sub-list is the name
of a package, as a symbol. The cadr of each sub-list is the minimum acceptable
version number, as a string that can be parse by version-to-list. An entry
that lacks a version (i.e., an entry which is just a symbol, or a sub-list of one
element) is equivalent to entry with version "0". For instance:
;; Package-Requires: ((gnus "1.0") (bubbles "2.7.2") cl-lib (seq))
The package code automatically defines a package named ‘emacs’ with the ver-
sion number of the currently running Emacs. This can be used to require a
minimal version of Emacs for a package.
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 from anything else by blank lines. 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.
‘;;; Change Log:’
This begins an optional log of changes to the file over time. Don’t put too much
information in this section—it is better to keep the detailed logs in a version
1155
You can specify other Lisp expressions to execute just before dumping by putting them
in a library named site-init.el. This file is executed after the documentation strings are
found.
If you want to preload function or variable definitions, there are three ways you can do
this and make their documentation strings accessible when you subsequently run Emacs:
• 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 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 40.1.1 [Startup Summary], page 1072. Note that if
either site-load.el or site-init.el changes load-path, the changes will be lost after
dumping. See Section 16.3 [Library Search], page 266. To make a permanent change to
load-path, use the --enable-locallisppath option of configure.
In a package that can be preloaded, it is sometimes necessary (or useful) to delay certain
evaluations until Emacs subsequently starts up. The vast majority of such cases relate to the
values of customizable variables. For example, tutorial-directory is a variable defined in
startup.el, which is preloaded. The default value is set based on data-directory. The
variable needs to access the value of data-directory when Emacs starts, not when it is
dumped, because the Emacs executable has probably been installed in a different location
since it was dumped.
custom-initialize-delay symbol value [Function]
This function delays the initialization of symbol to the next Emacs start. You nor-
mally use this function by specifying it as the :initialize property of a customizable
variable. (The argument value is unused, and is provided only for compatibility with
the form Custom expects.)
In the unlikely event that you need a more general functionality than
custom-initialize-delay provides, you can use before-init-hook (see Section 40.1.1
[Startup Summary], page 1072).
dump-emacs to-file from-file [Function]
This function dumps the current state of Emacs into an executable file to-file. It takes
symbols from from-file (this is normally the executable file temacs).
If you want to use this function in an Emacs that was already dumped, you must run
Emacs with ‘-batch’.
are kept (see Section E.3 [Garbage Collection], page 1158). Pure storage is used for certain
data in the preloaded standard Lisp files—data that should never change during actual use
of Emacs.
Pure storage is allocated only while temacs is loading the standard preloaded Lisp li-
braries. In the file emacs, it is marked as read-only (on operating systems that permit
this), so that the memory space can be shared by all the Emacs jobs running on the ma-
chine at once. Pure storage is not expandable; a fixed amount is allocated when Emacs is
compiled, and if that is not sufficient for the preloaded libraries, temacs allocates dynamic
memory for the part that didn’t fit. The resulting image will work, but garbage collection
(see Section E.3 [Garbage Collection], page 1158) is disabled in this situation, causing a
memory leak. Such an overflow normally won’t happen unless you try to preload additional
libraries or add features to the standard ones. Emacs will display a warning about the
overflow when it starts. If this happens, you should increase the compilation parameter
SYSTEM_PURESIZE_EXTRA in the file src/puresize.h and rebuild Emacs.
purecopy object [Function]
This function makes a copy in pure storage of object, and returns it. It copies a string
by simply making a new string with the same characters, but without text properties,
in pure storage. It recursively copies the contents of vectors and cons cells. It does
not make copies of other objects such as symbols, but just returns them unchanged.
It signals an error if asked to copy markers.
This function is a no-op except while Emacs is being built and dumped; it is usually
called only in preloaded Lisp files.
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 shareable 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.
Beyond the basic vector, a lot of objects like window, buffer, and frame are managed as
if they were vectors. The corresponding C data structures include the union vectorlike_
header field whose size member contains the subtype enumerated by enum pvec_type and
an information about how many Lisp_Object fields this structure contains and what the
size of the rest data is. This information is needed to calculate the memory footprint of an
object, and used by the vector allocation code while iterating over the vector blocks.
It is quite common to use some storage for a while, then release it by (for example)
killing a buffer or deleting the last pointer to an object. Emacs provides a garbage collector
to reclaim this abandoned storage. The garbage collector operates by finding and marking
all Lisp objects that are still accessible to Lisp programs. To begin with, it assumes all
the symbols, their values and associated function definitions, and any data presently on the
stack, are accessible. Any objects that can be reached indirectly through other accessible
objects are also accessible.
When marking is finished, all objects still unmarked are garbage. No matter what the
Lisp program or the user does, it is impossible to refer to them, since there is no longer a
way to reach them. Their space might as well be reused, since no one will miss them. The
second (sweep) phase of the garbage collector arranges to reuse them.
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. Unreachable vectors from vector blocks are coalesced to
create largest possible free areas; if a free area spans a complete 4k block, that block is
freed. Otherwise, the free area is recorded in a free list array, where each entry corresponds
to a free list of areas of the same size. Large vectors, buffers, and other large objects are
allocated and freed individually.
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 un-
til 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 with information on amount of space in use, where
each entry has the form ‘(name size used)’ or ‘(name size used free)’. In the
entry, name is a symbol describing the kind of objects this entry represents, size is
the number of bytes used by each one, used is the number of those objects that were
found live in the heap, and optional free is the number of those objects that are not
live but that Emacs keeps around for future allocations. So an overall result is:
((conses cons-size used-conses free-conses)
(symbols symbol-size used-symbols free-symbols)
(miscs misc-size used-miscs free-miscs)
Appendix E: GNU Emacs Internals 1160
free-strings
The number of string headers for which space has been obtained from the
operating system, but that are not currently being used.
byte-size This is used for convenience and equals to sizeof (char).
used-bytes The total size of all string data in bytes.
vector-size Internal size of a vector header, i.e., sizeof (struct Lisp_Vector).
used-vectors
The number of vector headers allocated from the vector blocks.
slot-size Internal size of a vector slot, always equal to sizeof (Lisp_Object).
used-slots The number of slots in all used vectors.
free-slots The number of free slots in all vector blocks.
float-size Internal size of a float object, i.e., sizeof (struct Lisp_Float). (Do
not confuse it with the native platform float or double.)
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.
interval-size
Internal size of an interval object, i.e., sizeof (struct interval).
used-intervals
The number of intervals in use.
free-intervals
The number of intervals for which space has been obtained from the
operating system, but that are not currently being used.
buffer-size Internal size of a buffer, i.e., sizeof (struct buffer). (Do not confuse
with the value returned by buffer-size function.)
used-buffers
The number of buffer objects in use. This includes killed buffers invisible
to users, i.e., all buffers in all_buffers list.
unit-size The unit of heap space measurement, always equal to 1024 bytes.
total-size Total heap size, in unit-size units.
free-size Heap space which is not currently used, in unit-size units.
If there was overflow in pure space (see Section E.2 [Pure Storage], page 1157),
garbage-collect returns nil, because a real garbage collection cannot be done.
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.
gc-cons-threshold [User Option]
The value of this variable is the number of bytes of storage that must be allocated for
Lisp objects after one garbage collection in order to trigger another garbage collection.
You can use the result returned by garbage-collect to get an information about
size of the particular object type; space allocated to the contents of buffers does not
count. Note that the subsequent garbage collection does not happen immediately
when the threshold is exhausted, but only the next time the Lisp interpreter is called.
The initial threshold value is GC_DEFAULT_THRESHOLD, defined in alloc.c. Since it’s
defined in word_size units, the value is 400,000 for the default 32-bit configuration
and 800,000 for the 64-bit one. If you specify a larger value, garbage collection will
happen less often. This reduces the amount of time spent garbage collecting, but
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 1/10th
of GC_DEFAULT_THRESHOLD. A value less than this minimum will remain in effect only
until the subsequent garbage collection, at which time garbage-collect will set the
threshold back to the minimum.
gc-cons-percentage [User Option]
The value of this variable specifies the amount of consing before a garbage collection
occurs, as a fraction of the current heap size. This criterion and gc-cons-threshold
apply in parallel, and garbage collection occurs only when both criteria are satisfied.
As the heap size increases, the time to perform a garbage collection increases. Thus,
it can be desirable to do them less frequently in proportion.
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 nearly 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.
memory-info [Function]
This functions returns an amount of total system memory and how much of it is free.
On an unsupported system, the value may be nil.
Appendix E: GNU Emacs Internals 1163
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.
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 session.
Appendix E: GNU Emacs Internals 1164
misc-objects-consed [Variable]
The total number of miscellaneous objects that have been allocated so far in this
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.
E.6 C Dialect
The C part of Emacs is portable to C99 or later: C11-specific features such as
‘<stdalign.h>’ and ‘_Noreturn’ are not used without a check, typically at configuration
time, and the Emacs build procedure provides a substitute implementation if necessary.
Some C11 features, such as anonymous structures and unions, are too difficult to emulate,
so they are avoided entirely.
At some point in the future the base C dialect will no doubt change to C11.
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)
Appendix E: GNU Emacs Internals 1165
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.
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 must be more than min but less than 8.
interactive
This is an interactive specification, a string such as might be used as the argu-
ment of interactive in a Lisp function (see Section 21.2.1 [Using Interactive],
page 369). In the case of or, it is 0 (a null pointer), indicating that or cannot
be called interactively. A value of "" indicates a function that should receive no
arguments when called interactively. If the value begins with a ‘"(’, the string
is evaluated as a Lisp form. For example:
DEFUN ("foo", Ffoo, Sfoo, 0, 3,
"(list (read-char-by-name \"Insert character: \")\
(prefix-numeric-value current-prefix-arg)\
t)",
doc: /* ... */)
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 1148) apply to C code documentation strings too.
The documentation string can be followed by a list of C function attributes for
the C function that implements the primitive, like this:
Appendix E: GNU Emacs Internals 1166
of memory that becomes read-only (on certain operating systems) as a result of dumping
Emacs. See Section E.2 [Pure Storage], page 1157.
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:
defsubr (&sname);
Here sname 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 want to make a Lisp variable that is defined in C behave like one declared with
defcustom, add an appropriate entry to cus-start.el.
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, 0,
doc: /* Return non-nil if COORDINATES are in WINDOW.
...
or `right-margin' is returned. */)
(register Lisp_Object coordinates, Lisp_Object window)
{
struct window *w;
struct frame *f;
int x, y;
Lisp_Object lx, ly;
w = decode_live_window (window);
f = XFRAME (w->frame);
CHECK_CONS (coordinates);
lx = Fcar (coordinates);
ly = Fcdr (coordinates);
CHECK_NUMBER (lx);
CHECK_NUMBER (ly);
x = FRAME_PIXEL_X_FROM_CANON_X (f, lx) + FRAME_INTERNAL_BORDER_WIDTH (f);
y = FRAME_PIXEL_Y_FROM_CANON_Y (f, ly) + FRAME_INTERNAL_BORDER_WIDTH (f);
Appendix E: GNU Emacs Internals 1168
...
...
default:
emacs_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.
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 or pure, give it a non-nil side-effect-
free or pure property, respectively (see Section 9.4.2 [Standard Properties], page 126).
tioned in load-path (see Section 16.3 [Library Search], page 266), where Emacs will find
it.
If you wish to verify the conformance of a module to the Emacs dynamic module API,
invoke Emacs with the --module-assertions option. See Section “Initial Options” in The
GNU Emacs Manual.
int plugin_is_GPL_compatible;
The emacs-module.h file is installed into your system’s include tree as part of the Emacs
installation. Alternatively, you can find it in the Emacs source tree.
Next, write an initialization function for the module.
int emacs_module_init (struct emacs runtime *runtime) [Function]
Emacs calls this function when it loads a module. If a module does not export a
function named emacs_module_init, trying to load the module will signal an error.
The initialization function should return zero if the initialization succeeds, non-zero
otherwise. In the latter case, Emacs will signal an error, and the loading of the
module will fail. If the user presses C-g during the initialization, Emacs ignores the
return value of the initialization function and quits (see Section 21.11 [Quitting],
page 407). (If needed, you can catch user quitting inside the initialization function,
see [should quit], page 1177.)
The argument runtime is a pointer to a C struct that includes 2 public fields: size,
which provides the size of the structure in bytes; and get_environment, which pro-
vides a pointer to a function that allows the module initialization function access to
the Emacs environment object and its interfaces.
The initialization function should perform whatever initialization is required for the
module. In addition, it can perform the following tasks:
Compatibility verification
A module can verify that the Emacs executable which loads the module
is compatible with the module, by comparing the size member of the
runtime structure with the value compiled into the module:
int
emacs_module_init (struct emacs_runtime *ert)
{
if (ert->size < sizeof (*ert))
return 1;
}
If the size of the runtime object passed to the module is smaller than what
it expects, it means the module was compiled for an Emacs version newer
(later) than the one which attempts to load it, i.e. the module might be
incompatible with the Emacs binary.
Appendix E: GNU Emacs Internals 1170
In addition, a module can verify the compatibility of the module API with
what the module expects. The following sample code assumes it is part
of the emacs_module_init function shown above:
emacs_env *env = ert->get_environment (ert);
if (env->size < sizeof (*env))
return 2;
This calls the get_environment function using the pointer provided in
the runtime structure to retrieve a pointer to the API’s environment, a
C struct which also has a size field holding the size of the structure in
bytes.
Finally, you can write a module that will work with older versions of
Emacs, by comparing the size of the environment passed by Emacs with
known sizes, like this:
emacs_env *env = ert->get_environment (ert);
if (env->size >= sizeof (struct emacs_env_26))
emacs_version = 26; /* Emacs 26 or later. */
else if (env->size >= sizeof (struct emacs_env_25))
emacs_version = 25;
else
return 2; /* Unknown or unsupported version. */
This works because later Emacs versions always add members to the
environment, never remove any members, so the size can only grow with
new Emacs releases. Given the version of Emacs, the module can use
only the parts of the module API that existed in that version, since those
parts are identical in later versions.
We recommend that modules always perform the compatibility verifi-
cation, unless they do their job entirely in the initialization function,
and don’t access any Lisp objects or use any Emacs functions accessible
through the environment structure.
Binding module functions to Lisp symbols
This gives the module functions names so that Lisp code could call it
by that name. We describe how to do this in Section E.8.2 [Module
Functions], page 1170, below.
argument number), and args is a pointer to the array of the function arguments.
The argument data points to additional data required by the function, which was
arranged when make_function (see below) was called to create an Emacs function
from module_func.
Module functions use the type emacs_value to communicate Lisp objects between
Emacs and the module (see Section E.8.3 [Module Values], page 1172). The API,
described below and in the following subsections, provides facilities for conversion
between basic C data types and the corresponding emacs_value objects.
A module function always returns a value. If the function returns normally, the Lisp
code which called it will see the Lisp object corresponding to the emacs_value value
the function returned. However, if the user typed C-g, or if the module function or
its callees signaled an error or exited nonlocally (see Section E.8.5 [Module Nonlocal],
page 1177), Emacs will ignore the returned value and quit or throw as it does when
Lisp code encounters the same situations.
After writing your C code for a module function, you should make a Lisp function object
from it using the make_function function, whose pointer is provided in the environment
(recall that the pointer to the environment is returned by get_environment). This is
normally done in the module initialization function (see [module initialization function],
page 1169), after verifying the API compatibility.
Finally, you should bind the Lisp function to a symbol, so that Lisp code could call your
function by name. For that, use the module API function intern (see [intern], page 1176)
whose pointer is also provided in the environment that module functions can access.
Appendix E: GNU Emacs Internals 1172
Combining the above steps, code that arranges for a C function module_func to be
callable as module-func from Lisp will look like this, as part of the module initialization
function:
emacs_env *env = ert->get_environment (ert);
emacs_value func = env->make_function (env, min_arity, max_arity,
module_func, docstring, data);
emacs_value symbol = env->intern (env, "module-func");
emacs_value args[] = {symbol, func};
env->funcall (env, env->intern (env, "defalias"), 2, args);
This makes the symbol module-func known to Emacs by calling env->intern, then invokes
defalias from Emacs to bind the function to that symbol. Note that it is possible to use
fset instead of defalias; the differences are described in Section 13.4 [Defining Functions],
page 209.
Using the module API, it is possible to define more complex function and data types:
interactive functions, inline functions, macros, etc. However, the resulting C code will be
cumbersome and hard to read. Therefore, we recommend that you limit the module code
which creates functions and data structures to the absolute minimum, and leave the rest
for a Lisp package that will accompany your module, because doing these additional tasks
in Lisp is much easier, and will produce a much more readable code. For example, given a
module function module-func defined as above, one way of making an interactive command
module-cmd based on it is with the following simple Lisp wrapper:
(defun module-cmd (&rest args)
"Documentation string for the command."
(interactive spec)
(apply 'module-func args))
The Lisp package which goes with your module could then load the module using the
module-load primitive (see Section 16.11 [Dynamic Modules], page 278) when the package
is loaded into Emacs.
The emacs_env pointer will usually come from the first argument to the module function, or
from the call to get_environment if you need the environment in the module initialization
function.
Most of the functions described below became available in Emacs 25, the first Emacs
release that supported dynamic modules. For the few functions that became available in
later Emacs releases, we mention the first Emacs version that supported them.
The following API functions extract values of various C data types from emacs_value
objects. They all raise the wrong-type-argument error condition (see Section 2.6 [Type
Predicates], page 29) if the argument emacs_value object is not of the type expected by
the function. See Section E.8.5 [Module Nonlocal], page 1177, for details of how signaling
errors works in Emacs modules, and how to catch error conditions inside the module before
they are reported to Emacs. The API function type_of (see Section E.8.4 [Module Misc],
page 1175) can be used to obtain the type of a emacs_value object.
the other extraction functions described here, as appropriate for the Lisp data type
stored in that element of the vector.
void vec_set (emacs env *env, emacs value vector, ptrdiff t [Function]
index, emacs value value)
This function stores value in the element of vector whose index is index. It raises the
args-out-of-range error condition if the value of index is invalid.
The following API functions create emacs_value objects from basic C data types. They
all return the created emacs_value object.
The API does not provide functions to manipulate Lisp data structures, for example,
create lists with cons and list (see Section 5.4 [Building Lists], page 72), extract list
members with car and cdr (see Section 5.3 [List Elements], page 69), create vectors with
vector (see Section 6.5 [Vector Functions], page 105), etc. For these, use intern and
funcall, described in the next subsection, to call the corresponding Lisp functions.
Normally, emacs_value objects have a rather short lifetime: it ends when the emacs_
env pointer used for their creation goes out of scope. Occasionally, you may need to create
global references: emacs_value objects that live as long as you wish. Use the following two
functions to manage such objects.
void set_user_ptr (emacs env *env, emacs value value, void *ptr) [Function]
This function sets the C pointer embedded in the user-ptr object represented by
value to ptr.
bool eq (emacs env *env, emacs value val1, emacs value val2) [Function]
This function returns true if the Lisp objects represented by val1 and val2 are iden-
tical, false otherwise. This is the same as the Lisp function eq (see Section 2.7
[Equality Predicates], page 32), but avoids the need to intern the objects represented
by the arguments.
There are no API functions for other equality predicates, so you will need to use
intern and funcall, described below, to perform more complex equality tests.
emacs_value funcall (emacs env *env, emacs value func, ptrdiff t [Function]
nargs, emacs value *args)
This function calls the specified func passing it nargs arguments from the array
pointed to by args. The argument func can be a function symbol (e.g., returned
by intern described above), a module function returned by make_function (see
Section E.8.2 [Module Functions], page 1170), a subroutine written in C, etc. If nargs
is zero, args can be a NULL pointer.
The function returns the value that func returned.
If your module includes potentially long-running code, it is a good idea to check from time
to time in that code whether the user wants to quit, e.g., by typing C-g (see Section 21.11
Appendix E: GNU Emacs Internals 1177
[Quitting], page 407). The following function, which is available since Emacs 26.1, is pro-
vided for that purpose.
enum emacs_funcall_exit non local exit check (emacs env *env) [Function]
This function returns the kind of nonlocal exit condition stored in env. The possible
values are:
emacs_funcall_exit_return
The last API function exited normally.
emacs_funcall_exit_signal
The last API function signaled an error.
emacs_funcall_exit_throw
The last API function exited via throw.
Appendix E: GNU Emacs Internals 1178
string, cons cell, float, vectorlike or miscellaneous object. Each of these data types has the
corresponding tag value. All tags are enumerated by enum Lisp_Type and placed into a 3-bit
bitfield of the Lisp_Object. The rest of the bits is the value itself. Integers are immediate,
i.e., directly represented by those value bits, and all other objects are represented by the
C pointers to a corresponding object allocated from the heap. Width of the Lisp_Object
is platform- and configuration-dependent: usually it’s equal to the width of an underlying
platform pointer (i.e., 32-bit on a 32-bit machine and 64-bit on a 64-bit one), but also
there is a special configuration where Lisp_Object is 64-bit but all pointers are 32-bit.
The latter trick was designed to overcome the limited range of values for Lisp integers on a
32-bit system by using 64-bit long long type for Lisp_Object.
The following C data structures are defined in lisp.h to represent the basic data types
beyond integers:
struct Lisp_Cons
Cons cell, an object used to construct lists.
struct Lisp_String
String, the basic object to represent a sequence of characters.
struct Lisp_Vector
Array, a fixed-size set of Lisp objects which may be accessed by an index.
struct Lisp_Symbol
Symbol, the unique-named entity commonly used as an identifier.
struct Lisp_Float
Floating-point value.
union Lisp_Misc
Miscellaneous kinds of objects which don’t fit into any of the above.
These types are the first-class citizens of an internal type system. Since the tag space is
limited, all other types are the subtypes of either Lisp_Vectorlike or Lisp_Misc. Vector
subtypes are enumerated by enum pvec_type, and nearly all complex objects like windows,
buffers, frames, and processes fall into this category. The rest of special types, includ-
ing markers and overlays, are enumerated by enum Lisp_Misc_Type and form the set of
subtypes of Lisp_Misc.
Below there is a description of a few subtypes of Lisp_Vectorlike. Buffer object repre-
sents the text to display and edit. Window is the part of display structure which shows the
buffer or is used as a container to recursively place other windows on the same frame. (Do
not confuse Emacs Lisp window object with the window as an entity managed by the user
interface system like X; in Emacs terminology, the latter is called frame.) Finally, process
object is used to manage the subprocesses.
next A pointer to the next buffer, in the chain of all buffers, including killed buffers.
This chain is used only for allocation and garbage collection, in order to collect
killed buffers properly.
pt
pt_byte The character and byte positions of point in a buffer.
begv
begv_byte
The character and byte positions of the beginning of the accessible range of
text in the buffer.
zv
zv_byte The character and byte positions of the end of the accessible range of text in
the buffer.
base_buffer
In an indirect buffer, this points to the base buffer. In an ordinary buffer, it is
null.
local_flags
This field contains flags indicating that certain variables are local in this buffer.
Such variables are declared in the C code using DEFVAR_PER_BUFFER, and their
buffer-local bindings are stored in fields in the buffer structure itself. (Some of
these fields are described in this table.)
modtime The modification time of the visited file. It is set when the file is written or read.
Before writing the buffer into a file, this field is compared to the modification
time of the file to see if the file has changed on disk. See Section 27.5 [Buffer
Modification], page 587.
auto_save_modified
The time when the buffer was last auto-saved.
last_window_start
The window-start position in the buffer as of the last time the buffer was
displayed in a window.
clip_changed
This flag indicates that narrowing has changed in the buffer. See Section 30.4
[Narrowing], page 753.
prevent_redisplay_optimizations_p
This flag indicates that redisplay optimizations should not be used to display
this buffer.
overlay_center
This field holds the current overlay center position. See Section 39.9.1 [Manag-
ing Overlays], page 985.
overlays_before
overlays_after
These fields hold, respectively, a list of overlays that end at or before the current
overlay center, and a list of overlays that end after the current overlay center.
Appendix E: GNU Emacs Internals 1182
mode_name
Pretty name of the major mode, e.g., "Lisp".
keymap
abbrev_table
syntax_table
category_table
display_table
These fields store the buffer’s local keymap (see Chapter 22 [Keymaps],
page 415), abbrev table (see Section 36.1 [Abbrev Tables], page 908),
syntax table (see Chapter 35 [Syntax Tables], page 892), category table (see
Section 35.8 [Categories], page 905), and display table (see Section 39.22.2
[Display Tables], page 1060).
downcase_table
upcase_table
case_canon_table
These fields store the conversion tables for converting text to lower case, upper
case, and for canonicalizing text for case-fold search. See Section 4.9 [Case
Tables], page 65.
minor_modes
An alist of the minor modes of this buffer.
pt_marker
begv_marker
zv_marker
These fields are only used in an indirect buffer, or in a buffer that is the base
of an indirect buffer. Each holds a marker that records pt, begv, and zv
respectively, for this buffer when the buffer is not current.
Appendix E: GNU Emacs Internals 1184
mode_line_format
header_line_format
case_fold_search
tab_width
fill_column
left_margin
auto_fill_function
truncate_lines
word_wrap
ctl_arrow
bidi_display_reordering
bidi_paragraph_direction
selective_display
selective_display_ellipses
overwrite_mode
abbrev_mode
mark_active
enable_multibyte_characters
buffer_file_coding_system
cache_long_line_scans
point_before_scroll
left_fringe_width
right_fringe_width
fringes_outside_margins
scroll_bar_width
indicate_empty_lines
indicate_buffer_boundaries
fringe_indicator_alist
fringe_cursor_alist
scroll_up_aggressively
scroll_down_aggressively
cursor_type
cursor_in_non_selected_windows
These fields store the values of Lisp variables that are automatically buffer-
local (see Section 12.11 [Buffer-Local Variables], page 185), whose corresponding
variable names have underscores replaced with dashes. For instance, mode_
line_format stores the value of mode-line-format.
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.
mini Non-zero if this window is a minibuffer window, a window showing the mini-
buffer or the echo area.
pseudo_window_p
Non-zero if this window is a pseudo window. A pseudo window is either a
window used to display the menu bar or the tool bar (when Emacs uses toolkits
that don’t display their own menu bar and tool bar) or a window showing a
tooltip on a tooltip frame. Pseudo windows are in general not accessible from
Lisp code.
parent Internally, Emacs arranges windows in a tree; each group of siblings has a parent
window whose area includes all the siblings. This field points to the window’s
parent in that tree, as a Lisp object. For the root window of the tree and a
minibuffer window this is always nil.
Parent windows do not display buffers, and play little role in display except to
shape their child windows. Emacs Lisp programs cannot directly manipulate
parent windows; they operate on the windows at the leaves of the tree, which
actually display buffers.
contents For a leaf window and windows showing a tooltip, this is the buffer, as a Lisp
object, that the window is displaying. For an internal (“parent”) window, this
is its first child window. For a pseudo window showing a menu or tool bar this
is nil. It is also nil for a window that has been deleted.
next
prev The next and previous sibling of this window as Lisp objects. next is nil if the
window is the right-most or bottom-most in its group; prev is nil if it is the
left-most or top-most in its group. Whether the sibling is left/right or up/down
is determined by the horizontal field of the sibling’s parent: if it’s non-zero,
the siblings are arranged horizontally.
As a special case, next of a frame’s root window points to the frame’s minibuffer
window, provided this is not a minibuffer-only or minibuffer-less frame. On such
frames prev of the minibuffer window points to that frame’s root window. In
any other case, the root window’s next and the minibuffer window’s (if present)
prev fields are nil.
left_col The left-hand edge of the window, measured in columns, relative to the leftmost
column (column 0) of the window’s native frame.
top_line The top edge of the window, measured in lines, relative to the topmost line
(line 0) of the window’s native frame.
pixel_left
pixel_top
The left-hand and top edges of this window, measured in pixels, relative to the
top-left corner (0, 0) of the window’s native frame.
total_cols
total_lines
The total width and height of the window, measured in columns and lines
respectively. The values include scroll bars and fringes, dividers and/or the
separator line on the right of the window (if any).
Appendix E: GNU Emacs Internals 1186
pixel_width;
pixel_height;
The total width and height of the window measured in pixels.
start A marker pointing to the position in the buffer that is the first character (in the
logical order, see Section 39.26 [Bidirectional Display], page 1067) 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.
old_pointm
The value of pointm at the last redisplay time.
force_start
If this flag is non-nil, it says that the window has been scrolled explicitly by
the Lisp program, and the value of the the window’s start was set for redisplay
to honor. 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.
optional_new_start
This is similar to force_start, but the next redisplay will only obey it if point
stays visible.
start_at_line_beg
Non-nil means current value of start was the beginning of a line when it was
chosen.
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-zero value means the window’s buffer was modified when the window
was last updated.
vertical_scroll_bar_type
horizontal_scroll_bar_type
The types of this window’s vertical and horizontal scroll bars.
Appendix E: GNU Emacs Internals 1187
scroll_bar_width
scroll_bar_height
The width of this window’s vertical scroll bar and the height of this window’s
horizontal scroll bar, in pixels.
left_margin_cols
right_margin_cols
The widths of the left and right margins in this window. A value of zero means
no margin.
left_fringe_width
right_fringe_width
The pixel widths of the left and right fringes in this window. A value of −1
means use the values of the frame.
fringes_outside_margins
A non-zero value means the fringes outside the display margins; othersize they
are between the margin and the text.
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 non-zero.
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-zero value if window_end_pos and window_end_vpos
are truly valid. This is zero if nontrivial redisplay is pre-empted, since in that
case the display that window_end_pos was computed for did not get onto the
screen.
cursor A structure describing where the cursor is in this window.
last_cursor_vpos
The window-relative vertical position of the line showing the cursor as of the
last redisplay that finished.
phys_cursor
A structure describing where the cursor of this window physically is.
phys_cursor_type
phys_cursor_height
phys_cursor_width
The type, height, and width of the 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 off. This is used for
blinking the cursor.
Appendix E: GNU Emacs Internals 1188
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. When only the current line is hscrolled,
this describes how much the current line is scrolled.
min_hscroll
Minimum value of hscroll, set by the user via set-window-hscroll (see
Section 28.23 [Horizontal Scrolling], page 669). When only the current line is
hscrolled, this describes the horizontal scrolling of lines other than the current
one.
vscroll Vertical scroll amount, in pixels. Normally, this is 0.
dedicated
Non-nil if this window is dedicated to its buffer.
combination_limit
This window’s combination limit, meaningful only for a parent window. If this
is t, then it is not allowed to delete this window and recombine its child windows
with other siblings of this window.
window_parameters
The alist of this window’s parameters.
display_table
The window’s display table, or nil if none is specified for it.
update_mode_line
Non-zero means this window’s mode line needs to be updated.
mode_line_height
header_line_height
The height in pixels of the mode line and the header line, or −1 if not known.
base_line_number
The line number of a certain position in the buffer, or zero. 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 zero meaning
none is known. If it is −1, don’t display the line number as long as the window
shows that buffer.
column_number_displayed
The column number currently displayed in this window’s mode line, or −1 if
column numbers are not being displayed.
current_matrix
desired_matrix
Glyph matrices describing the current and desired display of this window.
Appendix E: GNU Emacs Internals 1189
decoding_carryover
Size of carryover in decoding.
encode_coding_system
Coding-system for encoding the output to this process.
encoding_buf
A working buffer for encoding.
inherit_coding_system_flag
Flag to set coding-system of the process buffer from the coding system used
to decode process output.
type Symbol indicating the type of process: real, network, serial.
• Prefer the Emacs-defined type EMACS_INT for representing values converted to or from
Emacs Lisp fixnums, as fixnum arithmetic is based on EMACS_INT.
• When representing a system value (such as a file size or a count of seconds since the
Epoch), prefer the corresponding system type (e.g., off_t, time_t). Do not assume
that a system type is signed, unless this assumption is known to be safe. For example,
although off_t is always signed, time_t need not be.
• Prefer the Emacs-defined type printmax_t for representing values that might be any
signed integer that can be printed, using a printf-family function.
• Prefer intmax_t for representing values that might be any signed integer value.
• Prefer bool, false and true for booleans. Using bool can make programs easier to
read and a bit faster than using int. Although it is also OK to use int, 0 and 1,
this older style is gradually being phased out. When using bool, respect the limi-
tations of the replacement implementation of bool, as documented in the source file
lib/stdbool.in.h. In particular, boolean bitfields should be of type bool_bf, not
bool, so that they work correctly even when compiling Objective C with standard
GCC.
• In bitfields, prefer unsigned int or signed int to int, as int is less portable: it might
be signed, and might not be. Single-bit bit fields should be unsigned int or bool_bf
so that their values are 0 or 1.
1192
coding-system-error
The message is ‘Invalid coding system’. See Section 33.10.3 [Lisp and Coding
Systems], page 851.
cyclic-function-indirection
The message is ‘Symbol's chain of function indirections contains a
loop’. See Section 10.1.4 [Function Indirection], page 131.
cyclic-variable-indirection
The message is ‘Symbol's chain of variable indirections contains a
loop’. See Section 12.15 [Variable Aliases], page 198.
dbus-error
The message is ‘D-Bus error’. This is only defined if Emacs was compiled
with D-Bus support. See Section “Errors and Events” in D-Bus integration in
Emacs.
end-of-buffer
The message is ‘End of buffer’. See Section 30.2.1 [Character Motion],
page 743.
end-of-file
The message is ‘End of file during parsing’. Note that this is not a subcat-
egory of file-error, because it pertains to the Lisp reader, not to file I/O.
See Section 19.3 [Input Functions], page 325.
file-already-exists
This is a subcategory of file-error. See Section 25.4 [Writing to Files],
page 528.
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 541.
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 521.
file-missing
This is a subcategory of file-error. It occurs when an operation attempts to
act on a file that is missing. See Section 25.7 [Changing Files], page 541.
compression-error
This is a subcategory of file-error, which results from problems handling a
compressed file. See Section 16.1 [How Programs Do Loading], page 263.
file-locked
This is a subcategory of file-error. See Section 25.5 [File Locks], page 530.
Appendix F: Standard Errors 1194
file-supersession
This is a subcategory of file-error. See Section 27.6 [Modification Time],
page 588.
file-notify-error
This is a subcategory of file-error. It happens, when a file could not be
watched for changes. See Section 40.20 [File Notifications], page 1107.
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
The message is ‘Invalid function’. See Section 10.1.4 [Function Indirection],
page 131.
invalid-read-syntax
The message is ‘Invalid read syntax’. See Section 2.1 [Printed Representa-
tion], page 8.
invalid-regexp
The message is ‘Invalid regexp’. See Section 34.3 [Regular Expressions],
page 868.
mark-inactive
The message is ‘The mark is not active now’. See Section 31.7 [The Mark],
page 760.
no-catch The message is ‘No catch for tag’. See Section 11.7.1 [Catch and Throw],
page 158.
scan-error
The message is ‘Scan error’. This happens when certain syntax-parsing func-
tions find invalid syntax or mismatched parentheses. Conventionally raised with
three argument: a human-readable error message, the start of the obstacle that
cannot be moved over, and the end of the obstacle. See Section 30.2.6 [List
Motion], page 750, and See Section 35.6 [Parsing Expressions], page 900.
search-failed
The message is ‘Search failed’. See Chapter 34 [Searching and Matching],
page 865.
setting-constant
The message is ‘Attempt to set a constant symbol’. This happens when at-
tempting to assign values to nil, t, most-positive-fixnum, most-negative-
fixnum, and keyword symbols. It also happens when attempting to assign
values to enable-multibyte-characters and some other symbols whose di-
rect assignment is not allowed for some reason. See Section 12.2 [Constant
Variables], page 169.
text-read-only
The message is ‘Text is read-only’. This is a subcategory of buffer-read-
only. See Section 32.19.4 [Special Properties], page 808.
Appendix F: Standard Errors 1195
undefined-color
The message is ‘Undefined color’. See Section 29.22 [Color Names], page 735.
user-error
The message is the empty string. See Section 11.7.3.1 [Signaling Errors],
page 160.
user-search-failed
This is like ‘search-failed’, but doesn’t trigger the debugger, like
‘user-error’. See Section 11.7.3.1 [Signaling Errors], page 160, and See
Chapter 34 [Searching and Matching], page 865. This is used for searching in
Info files, See Section “Search Text” in Info.
void-function
The message is ‘Symbol's function definition is void’. See Section 13.9
[Function Cells], page 221.
void-variable
The message is ‘Symbol's value as variable is void’. See Section 12.7 [Ac-
cessing Variables], page 177.
wrong-number-of-arguments
The message is ‘Wrong number of arguments’. See Section 13.2.3 [Argument
List], page 206.
wrong-type-argument
The message is ‘Wrong type argument’. See Section 2.6 [Type Predicates],
page 29.
1196
Helper-help-map
A full keymap used by the help utility package.
It has the same keymap in its value cell and in its function cell.
input-decode-map
The keymap for translating keypad and function keys.
If there are none, then it contains an empty sparse keymap. See Section 22.14
[Translation Keymaps], page 434.
key-translation-map
A keymap for translating keys. This one overrides ordinary key bindings, unlike
local-function-key-map. See Section 22.14 [Translation Keymaps], page 434.
kmacro-keymap
A sparse keymap for keys that follows the C-x C-k prefix search.
See Section “Keyboard Macros” in The GNU Emacs Manual.
local-function-key-map
The keymap for translating key sequences to preferred alternatives.
If there are none, then it contains an empty sparse keymap. See Section 22.14
[Translation Keymaps], page 434.
menu-bar-file-menu
menu-bar-edit-menu
menu-bar-options-menu
global-buffers-menu-map
menu-bar-tools-menu
menu-bar-help-menu
These keymaps display the main, top-level menus in the menu bar.
Some of them contain sub-menus. For example, the Edit menu contains
menu-bar-search-menu, etc. See Section 22.17.5 [Menu Bar], page 446.
minibuffer-inactive-mode-map
A full keymap used in the minibuffer when it is not active.
See Section “Editing in the Minibuffer” in The GNU Emacs Manual.
mode-line-coding-system-map
mode-line-input-method-map
mode-line-column-line-number-mode-map
These keymaps control various areas of the mode line.
See Section 23.4 [Mode Line Format], page 476.
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 in
C-h b (display-bindings), where it describes the main use of the C-c prefix
key.
mouse-appearance-menu-map
A sparse keymap used for the S-mouse-1 key.
mule-keymap
The global keymap used for the C-x RET prefix key.
Appendix G: Standard Keymaps 1198
narrow-map
A sparse keymap for subcommands of the prefix C-x n.
prog-mode-map
The keymap used by Prog mode.
See Section 23.2.5 [Basic Major Modes], page 464.
query-replace-map
multi-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. multi-query-
replace-map extends query-replace-map for multi-buffer replacements. See
Section 34.7 [Search and Replace], page 887.
search-map
A sparse keymap that provides global bindings for search-related commands.
special-mode-map
The keymap used by Special mode.
See Section 23.2.5 [Basic Major Modes], page 464.
tool-bar-map
The keymap defining the contents of the tool bar.
See Section 22.17.6 [Tool Bar], page 447.
universal-argument-map
A sparse keymap used while processing C-u.
See Section 21.12 [Prefix Command Arguments], page 408.
vc-prefix-map
The global keymap used for the C-x v prefix key.
x-alternatives-map
A sparse keymap used to map certain keys under graphical frames.
The function x-setup-function-keys uses this.
1199
after-save-hook
before-save-hook
write-contents-functions
write-file-functions
See Section 25.2 [Saving Buffers], page 525.
after-setting-font-hook
Hook run after a frame’s font changes.
auto-save-hook
See Section 26.2 [Auto-Saving], page 574.
before-hack-local-variables-hook
hack-local-variables-hook
See Section 12.12 [File Local Variables], page 191.
buffer-access-fontify-functions
See Section 32.19.7 [Lazy Properties], page 815.
buffer-list-update-hook
Hook run when the buffer list changes (see Section 27.8 [Buffer List], page 591).
buffer-quit-function
Function to call to quit the current buffer.
change-major-mode-hook
See Section 12.11.2 [Creating Buffer-Local], page 186.
command-line-functions
See Section 40.1.4 [Command-Line Arguments], page 1077.
delayed-warnings-hook
The command loop runs this soon after post-command-hook (q.v.).
focus-in-hook
focus-out-hook
See Section 29.10 [Input Focus], page 720.
delete-frame-functions
See Section 29.7 [Deleting Frames], page 718.
delete-terminal-functions
See Section 29.2 [Multiple Terminals], page 685.
pop-up-frame-function
split-window-preferred-function
See Section 28.13.4 [Choosing Window Options], page 638.
echo-area-clear-hook
See Section 39.4.4 [Echo Area Customization], page 973.
find-file-hook
find-file-not-found-functions
See Section 25.1.1 [Visiting Functions], page 521.
font-lock-extend-after-change-region-function
See Section 23.6.9.2 [Region to Refontify], page 499.
Appendix H: Standard Hooks 1201
font-lock-extend-region-functions
See Section 23.6.9 [Multiline Font Lock], page 497.
font-lock-fontify-buffer-function
font-lock-fontify-region-function
font-lock-mark-block-function
font-lock-unfontify-buffer-function
font-lock-unfontify-region-function
See Section 23.6.4 [Other Font Lock Variables], page 493.
fontification-functions
See Section 39.12.7 [Automatic Face Assignment], page 1009.
frame-auto-hide-function
See Section 28.16 [Quitting Windows], page 651.
kill-buffer-hook
kill-buffer-query-functions
See Section 27.10 [Killing Buffers], page 594.
kill-emacs-hook
kill-emacs-query-functions
See Section 40.2.1 [Killing Emacs], page 1079.
menu-bar-update-hook
See Section 22.17.5 [Menu Bar], page 446.
minibuffer-setup-hook
minibuffer-exit-hook
See Section 20.14 [Minibuffer Misc], page 366.
mouse-leave-buffer-hook
Hook run when about to switch windows with a mouse command.
mouse-position-function
See Section 29.16 [Mouse Position], page 730.
prefix-command-echo-keystrokes-functions
An abnormal hook run by prefix commands (such as C-u) which should return
a string describing the current prefix state. For example, C-u produces ‘C-u-’
and ‘C-u 1 2 3-’. Each hook function is called with no arguments and should
return a string describing the current prefix state, or nil if there’s no prefix
state. See Section 21.12 [Prefix Command Arguments], page 408.
prefix-command-preserve-state-hook
Hook run when a prefix command needs to preserve the prefix by passing the
current prefix command state to the next command. For example, C-u needs
to pass the state to the next command when the user types C-u - or follows
C-u with a digit.
pre-redisplay-functions
Hook run in each window just before redisplaying it. See Section 39.2 [Forcing
Redisplay], page 967.
Appendix H: Standard Hooks 1202
post-command-hook
pre-command-hook
See Section 21.1 [Command Overview], page 368.
post-gc-hook
See Section E.3 [Garbage Collection], page 1158.
post-self-insert-hook
See Section 23.3.2 [Keymaps and Minor Modes], page 473.
suspend-hook
suspend-resume-hook
suspend-tty-functions
resume-tty-functions
See Section 40.2.2 [Suspending Emacs], page 1080.
syntax-begin-function
syntax-propertize-extend-region-functions
syntax-propertize-function
font-lock-syntactic-face-function
See Section 23.6.8 [Syntactic Font Lock], page 496. See Section 35.4 [Syntax
Properties], page 899.
temp-buffer-setup-hook
temp-buffer-show-function
temp-buffer-show-hook
See Section 39.8 [Temporary Displays], page 981.
tty-setup-hook
See Section 40.1.3 [Terminal-Specific], page 1076.
window-configuration-change-hook
window-scroll-functions
window-size-change-functions
See Section 28.28 [Window Hooks], page 681.
1203
Index
" +
‘"’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
‘"’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 ‘+’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869
# ,
‘##’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 , (with backquote). . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
‘#$’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 ,@ (with backquote) . . . . . . . . . . . . . . . . . . . . . . . . . . 136
‘#'’ syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
‘#(’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
‘#:’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 –
‘#@count’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
‘#^’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 --disable-build-details
‘#n#’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 option to configure . . . . . . . . . . . . . . . . . . . . . . . 1156
‘#n=’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 --enable-locallisppath option
to configure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1157
$
‘$’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 968
.
‘$’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871 ‘.’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
‘.’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
.#, lock file names . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
% .emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1075
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
‘%’ in format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
/
/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
& /= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
‘&’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883 /dev/tty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
&optional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
&rest. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
;
‘;’ for commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
’
‘'’ for quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
<
< . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
( <= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
‘(’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
‘(...)’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 =
‘(?:’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
) >
‘)’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
>= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
*
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 ?
‘*’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 ‘?’ in character constant . . . . . . . . . . . . . . . . . . . . . . . 10
‘*’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868 ? in minibuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
*get_user_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175 ‘?’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869
*scratch* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Index 1204
@ |
‘@’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 ‘|’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
[ 1
‘[’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869 1+ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
[. . . ] (Edebug) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 1- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
] 2
‘]’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869
2C-mode-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
2D box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999
^
‘^’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 3
‘^’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 870 3D box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999
‘ A
` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 abbrev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
‘ (list substitution) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 abbrev properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
abbrev table properties . . . . . . . . . . . . . . . . . . . . . . . 914
abbrev tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
\ abbrev tables in modes . . . . . . . . . . . . . . . . . . . . . . . 458
‘\’ in character constant . . . . . . . . . . . . . . . . . . . . . . . 11 abbrev-all-caps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912
‘\’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 968 abbrev-expand-function . . . . . . . . . . . . . . . . . . . . . 912
‘\’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 abbrev-expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
‘\’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871 abbrev-file-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
‘\’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883 abbrev-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
‘\’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 abbrev-insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
‘\’ in symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 abbrev-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196
‘\'’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875 abbrev-minor-mode-table-alist . . . . . . . . . . . . . 913
\( in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 abbrev-prefix-mark . . . . . . . . . . . . . . . . . . . . . . . . . . 911
‘\<’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876 abbrev-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
‘\=’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875 abbrev-start-location . . . . . . . . . . . . . . . . . . . . . . 912
‘\>’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876 abbrev-start-location-buffer . . . . . . . . . . . . . . 912
‘\_<’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876 abbrev-symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
‘\_>’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876 abbrev-table-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
‘\`’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875 abbrev-table-name-list . . . . . . . . . . . . . . . . . . . . . 909
abbrev-table-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
‘\a’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
abbrev-table-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
‘\b’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
abbreviate-file-name . . . . . . . . . . . . . . . . . . . . . . . 550
‘\b’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
abbreviated file names . . . . . . . . . . . . . . . . . . . . . . . . 550
‘\B’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
abbrevs, looking up and expanding . . . . . . . . . . . . 911
‘\e’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
abbrevs-changed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
‘\f’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
abnormal hook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
‘\n’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
abort-recursive-edit . . . . . . . . . . . . . . . . . . . . . . . 412
‘\n’ in print. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
aborting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
‘\n’ in replacement. . . . . . . . . . . . . . . . . . . . . . . . . . . . 883
abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
‘\r’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
absolute edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
‘\s’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
absolute file name. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
‘\s’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
absolute frame edges . . . . . . . . . . . . . . . . . . . . . . . . . . 692
‘\S’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
absolute frame position . . . . . . . . . . . . . . . . . . . . . . . 692
‘\t’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
absolute position. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
‘\v’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
accept input from processes . . . . . . . . . . . . . . . . . . . 942
‘\w’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
accept-change-group . . . . . . . . . . . . . . . . . . . . . . . . 832
‘\W’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
accept-process-output . . . . . . . . . . . . . . . . . . . . . . 943
Index 1205
assoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 B
assoc-default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 back-to-indentation . . . . . . . . . . . . . . . . . . . . . . . . 800
assoc-delete-all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 background-color, a frame parameter . . . . . . . . 715
assoc-string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 background-mode, a frame parameter . . . . . . . . . 714
association list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 backing store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
assq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 backquote (list substitution) . . . . . . . . . . . . . . . . . . 135
assq-delete-all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 backquote-style patterns . . . . . . . . . . . . . . . . . . . . . . 152
asynchronous subprocess . . . . . . . . . . . . . . . . . . . . . . 926 backslash in character constants . . . . . . . . . . . . . . . . 11
atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 backslash in regular expressions . . . . . . . . . . . . . . . 873
atom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 backslash in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
atomic changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831 backslash in symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
atomic windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658 backspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
atoms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 backtrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
attributes of text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802 backtrace from emacsclient’s --eval . . . . . . . . . . 290
Auto Fill mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790 backtrace-debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
auto-coding-alist . . . . . . . . . . . . . . . . . . . . . . . . . . . 856 backtrace-frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
auto-coding-functions . . . . . . . . . . . . . . . . . . . . . . 856 backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
auto-coding-regexp-alist . . . . . . . . . . . . . . . . . . . 855 backtracking and POSIX regular expressions . . 881
auto-fill-chars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791 backtracking and regular expressions . . . . . . . . . . 868
backup file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
auto-fill-function . . . . . . . . . . . . . . . . . . . . . . . . . . 790
backup files, rename or copy . . . . . . . . . . . . . . . . . . 571
auto-hide-function, a frame parameter . . . . . . 709
backup-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
auto-hscroll-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
backup-by-copying . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
auto-lower, a frame parameter . . . . . . . . . . . . . . . 711
backup-by-copying-when-linked . . . . . . . . . . . . . 571
auto-mode-alist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 backup-by-copying-when-mismatch . . . . . . . . . . . 571
auto-raise, a frame parameter . . . . . . . . . . . . . . . 711 backup-by-copying-when-
auto-raise-tool-bar-buttons . . . . . . . . . . . . . . . 449 privileged-mismatch . . . . . . . . . . . . . . . . . . . . . . 571
auto-resize-tool-bars . . . . . . . . . . . . . . . . . . . . . . 449 backup-directory-alist . . . . . . . . . . . . . . . . . . . . . 570
auto-save-default . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 backup-enable-predicate . . . . . . . . . . . . . . . . . . . . 570
auto-save-file-name-p . . . . . . . . . . . . . . . . . . . . . . 574 backup-file-name-p . . . . . . . . . . . . . . . . . . . . . . . . . . 573
auto-save-hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 backup-inhibited . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
auto-save-interval . . . . . . . . . . . . . . . . . . . . . . . . . . 576 backups and auto-saving . . . . . . . . . . . . . . . . . . . . . . 569
auto-save-list-file-name . . . . . . . . . . . . . . . . . . . 577 backward-button . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1053
auto-save-list-file-prefix . . . . . . . . . . . . . . . . 577 backward-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
auto-save-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 backward-delete-char-untabify . . . . . . . . . . . . . 773
auto-save-timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 backward-delete-char-untabify-method . . . . . 773
auto-save-visited-file-name . . . . . . . . . . . . . . . 575 backward-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
auto-selection of window . . . . . . . . . . . . . . . . . . . . . . 675 backward-prefix-chars . . . . . . . . . . . . . . . . . . . . . . 900
auto-window-vscroll . . . . . . . . . . . . . . . . . . . . . . . . 669 backward-sexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 backward-to-indentation . . . . . . . . . . . . . . . . . . . . 800
autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 backward-up-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
autoload by prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 backward-word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
autoload cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 backward-word-strictly . . . . . . . . . . . . . . . . . . . . . 745
autoload cookie, and safe values of variable . . . . 193 balance-windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
autoload errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 balance-windows-area . . . . . . . . . . . . . . . . . . . . . . . 611
balanced parenthesis motion . . . . . . . . . . . . . . . . . . 750
autoload object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
balancing parentheses . . . . . . . . . . . . . . . . . . . . . . . . 1058
autoload, when to use . . . . . . . . . . . . . . . . . . . . . . . . . 272
balancing window sizes. . . . . . . . . . . . . . . . . . . . . . . . 611
autoload-compute-prefixes. . . . . . . . . . . . . . . . . . 272
barf-if-buffer-read-only . . . . . . . . . . . . . . . . . . . 591
autoload-do-load . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
base 64 encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
autoloadp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 base buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
automatic face assignment . . . . . . . . . . . . . . . . . . . 1009 base coding system . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
automatically buffer-local . . . . . . . . . . . . . . . . . . . . . 185 base direction of a paragraph . . . . . . . . . . . . . . . . 1068
base for reading an integer . . . . . . . . . . . . . . . . . . . . . 35
base location, package archive . . . . . . . . . . . . . . . . 1117
base remapping, faces . . . . . . . . . . . . . . . . . . . . . . . . 1007
base64-decode-region . . . . . . . . . . . . . . . . . . . . . . . 825
base64-decode-string . . . . . . . . . . . . . . . . . . . . . . . 825
Index 1207
M make-help-screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
M-g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 make-indirect-buffer . . . . . . . . . . . . . . . . . . . . . . . 596
M-o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 make-keymap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
M-s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 make-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
M-x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 make-local-variable . . . . . . . . . . . . . . . . . . . . . . . . 186
Maclisp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 make-marker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 make-mutex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
macro argument evaluation . . . . . . . . . . . . . . . . . . . 240 make-nearby-temp-file . . . . . . . . . . . . . . . . . . . . . . 554
macro call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 make-network-process . . . . . . . . . . . . . . . . . . . . . . . 953
macro call evaluation . . . . . . . . . . . . . . . . . . . . . . . . . 132 make-obsolete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
macro caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 make-obsolete-variable . . . . . . . . . . . . . . . . . . . . . 198
macro compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 make-overlay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985
macro descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 make-pipe-process . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
macro expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 make-process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
macro, how to define . . . . . . . . . . . . . . . . . . . . . . . . . . 238 make-progress-reporter . . . . . . . . . . . . . . . . . . . . . 971
macroexpand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 make-record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
macroexpand-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 make-ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
macroexpand-all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 make-serial-process . . . . . . . . . . . . . . . . . . . . . . . . 959
macrop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 make-sparse-keymap . . . . . . . . . . . . . . . . . . . . . . . . . . 418
macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 make-string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
macros, at compile time . . . . . . . . . . . . . . . . . . . . . . . 284 make-symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
magic autoload comment . . . . . . . . . . . . . . . . . . . . . . 270 make-symbolic-link . . . . . . . . . . . . . . . . . . . . . . . . . . 543
magic file names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 make-syntax-table . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
magic-fallback-mode-alist. . . . . . . . . . . . . . . . . . 461 make-temp-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
magic-mode-alist . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 make-temp-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
mail-host-address . . . . . . . . . . . . . . . . . . . . . . . . . . 1083 make-text-button . . . . . . . . . . . . . . . . . . . . . . . . . . . 1051
main window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654 make-thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
main window of a frame . . . . . . . . . . . . . . . . . . . . . . 654 make-translation-table . . . . . . . . . . . . . . . . . . . . . 847
major mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 make-translation-table-from-alist . . . . . . . . 848
major mode command . . . . . . . . . . . . . . . . . . . . . . . . 455 make-translation-table-from-vector . . . . . . . 848
major mode conventions . . . . . . . . . . . . . . . . . . . . . . 456 make-variable-buffer-local . . . . . . . . . . . . . . . . 187
major mode hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 make-vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
major mode keymap . . . . . . . . . . . . . . . . . . . . . . . . . . 422 make-xwidget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1048
major mode, automatic selection . . . . . . . . . . . . . . 459 make_float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174
major-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 make_function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1171
make-abbrev-table . . . . . . . . . . . . . . . . . . . . . . . . . . . 908 make_global_ref . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174
make-auto-save-file-name . . . . . . . . . . . . . . . . . . . 575 make_integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174
make-backup-file-name . . . . . . . . . . . . . . . . . . . . . . 573 make_string. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174
make-backup-file-name-function . . . . . . . . . . . . 570 make_user_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175
make-backup-files . . . . . . . . . . . . . . . . . . . . . . . . . . . 570 making backup files . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
make-bool-vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 making buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1051
make-button. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1051 makunbound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
make-byte-code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 malicious use of directional overrides . . . . . . . . . 1070
make-category-set . . . . . . . . . . . . . . . . . . . . . . . . . . . 907 managing overlays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985
make-category-table . . . . . . . . . . . . . . . . . . . . . . . . 907 manipulating buttons . . . . . . . . . . . . . . . . . . . . . . . . 1052
make-char-table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 map-char-table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
make-composed-keymap . . . . . . . . . . . . . . . . . . . . . . . 420 map-charset-chars . . . . . . . . . . . . . . . . . . . . . . . . . . . 846
make-condition-variable . . . . . . . . . . . . . . . . . . . . 917 map-keymap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
make-directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 map-y-or-n-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
make-display-table . . . . . . . . . . . . . . . . . . . . . . . . 1060 mapatoms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
make-finalizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 mapbacktrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
make-frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684 mapc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
make-frame-invisible . . . . . . . . . . . . . . . . . . . . . . . 723 mapcan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
make-frame-on-display . . . . . . . . . . . . . . . . . . . . . . 686 mapcar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
make-frame-visible . . . . . . . . . . . . . . . . . . . . . . . . . . 723 mapconcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
make-frame-visible event . . . . . . . . . . . . . . . . . . . . 389 maphash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
make-glyph-code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063 mapped frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
make-hash-table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 mapping functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Index 1230
X XBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1037
X display names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686 XML DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
X Window System . . . . . . . . . . . . . . . . . . . . . . . . . . . 1065 XPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1038
x-alt-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 xwidget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1048
x-alternatives-map . . . . . . . . . . . . . . . . . . . . . . . . 1198 xwidget-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1048
x-bitmap-file-path . . . . . . . . . . . . . . . . . . . . . . . . 1000 xwidget-info . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1049
x-close-connection . . . . . . . . . . . . . . . . . . . . . . . . . . 687 xwidget-plist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1048
x-color-defined-p . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 xwidget-query-on-exit-flag . . . . . . . . . . . . . . . 1049
x-color-values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736 xwidget-resize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1049
x-ctrl-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 xwidget-size-request . . . . . . . . . . . . . . . . . . . . . . 1049
x-defined-colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 xwidget-webkit-execute-script . . . . . . . . . . . . 1049
x-display-color-p . . . . . . . . . . . . . . . . . . . . . . . . . . . 738 xwidget-webkit-execute-script-rv . . . . . . . . 1049
x-display-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686 xwidget-webkit-get-title . . . . . . . . . . . . . . . . . . 1049
x-dnd-known-types . . . . . . . . . . . . . . . . . . . . . . . . . . . 734 xwidget-webkit-goto-uri . . . . . . . . . . . . . . . . . . . 1049
x-dnd-test-function . . . . . . . . . . . . . . . . . . . . . . . . 734 xwidgetp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1048
x-dnd-types-alist . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
x-double-buffered-p . . . . . . . . . . . . . . . . . . . . . . . . 724
x-family-fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1012 Y
x-focus-frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721 y-or-n-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
x-get-resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737 y-or-n-p-with-timeout . . . . . . . . . . . . . . . . . . . . . . 360
x-gtk-use-system-tooltips . . . . . . . . . . . . . . . . 1066 yank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
x-hyper-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 yank suppression. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
x-list-fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1012 yank-excluded-properties . . . . . . . . . . . . . . . . . . . 778
x-meta-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 yank-handled-properties . . . . . . . . . . . . . . . . . . . . 778
x-open-connection . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 yank-pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
x-parse-geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716 yank-undo-function . . . . . . . . . . . . . . . . . . . . . . . . . . 779
x-pointer-shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733 yanking and text properties . . . . . . . . . . . . . . . . . . . 778
x-popup-dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
yes-or-no questions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
x-popup-menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
yes-or-no-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
x-resource-class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
x-resource-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
x-sensitive-text-pointer-shape . . . . . . . . . . . . 733
x-server-vendor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741 Z
x-server-version . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740 z-group, a frame parameter . . . . . . . . . . . . . . . . . . . 704
x-setup-function-keys . . . . . . . . . . . . . . . . . . . . . 1198 Z-order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
x-stretch-cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714 zerop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
x-super-keysym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 zlib-available-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
X11 keysyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 zlib-decompress-region . . . . . . . . . . . . . . . . . . . . . 824