Professional Documents
Culture Documents
Short Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 Lisp Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4 Strings and Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6 Sequences, Arrays, and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . 99
7 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
10 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
12 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
13 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
14 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
15 Customization Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
16 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
17 Byte Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
18 Compilation of Lisp to Native Code . . . . . . . . . . . . . . . . . . . . . 312
19 Debugging Lisp Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
20 Reading and Printing Lisp Objects . . . . . . . . . . . . . . . . . . . . . 352
21 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
22 Command Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
23 Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
24 Major and Minor Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
25 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
26 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
27 Backups and Auto-Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
28 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
29 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
30 Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
31 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
32 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
33 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.1 Integer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2 Floating-Point Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3 Type Predicates for Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.4 Comparison of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.5 Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.6 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.7 Rounding Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.8 Bitwise Operations on Integers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.9 Standard Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.10 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
v
5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.1 Lists and Cons Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.2 Predicates on Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.3 Accessing Elements of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.4 Building Cons Cells and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.5 Modifying List Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.6 Modifying Existing List Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.6.1 Altering List Elements with setcar . . . . . . . . . . . . . . . . . . . . . . . 85
5.6.2 Altering the CDR of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.6.3 Functions that Rearrange Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.7 Using Lists as Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.8 Association Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.9 Property Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
5.9.1 Property Lists and Association Lists . . . . . . . . . . . . . . . . . . . . . . 97
5.9.2 Property Lists Outside Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
7.1 Record Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
7.2 Backward Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
9 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
9.1 Symbol Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
9.2 Defining Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
9.3 Creating and Interning Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
9.4 Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.4.1 Accessing Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.4.2 Standard Symbol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
9.5 Shorthands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.5.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
10 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
10.1 Kinds of Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
10.1.1 Self-Evaluating Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
10.1.2 Symbol Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
10.1.3 Classification of List Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
10.1.4 Symbol Function Indirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
10.1.5 Evaluation of Function Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . 144
10.1.6 Lisp Macro Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
10.1.7 Special Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
10.1.8 Autoloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
10.2 Quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
10.3 Backquote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
10.4 Eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
10.5 Deferred and Lazy Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
12 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
12.1 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
12.2 Variables that Never Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
12.3 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
12.4 When a Variable is Void . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
12.5 Defining Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
12.6 Tips for Defining Variables Robustly. . . . . . . . . . . . . . . . . . . . . . . . . 191
12.7 Accessing Variable Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
12.8 Setting Variable Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
12.9 Running a function when a variable is changed. . . . . . . . . . . . . . . 195
12.9.1 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
12.10 Scoping Rules for Variable Bindings . . . . . . . . . . . . . . . . . . . . . . . . 195
12.10.1 Dynamic Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
12.10.2 Proper Use of Dynamic Binding . . . . . . . . . . . . . . . . . . . . . . . 197
12.10.3 Lexical Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
12.10.4 Using Lexical Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
12.10.5 Converting to Lexical Binding . . . . . . . . . . . . . . . . . . . . . . . . . 200
12.11 Buffer-Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
12.11.1 Introduction to Buffer-Local Variables . . . . . . . . . . . . . . . . . 202
12.11.2 Creating and Deleting Buffer-Local Bindings . . . . . . . . . . . 203
12.11.3 The Default Value of a Buffer-Local Variable . . . . . . . . . . 206
12.12 File Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
12.13 Directory Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
12.14 Connection Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
12.15 Variable Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
12.16 Variables with Restricted Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
12.17 Generalized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
12.17.1 The setf Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
12.17.2 Defining new setf forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
13 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
13.1 What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
13.2 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
13.2.1 Components of a Lambda Expression . . . . . . . . . . . . . . . . . . . 223
13.2.2 A Simple Lambda Expression Example . . . . . . . . . . . . . . . . . 224
13.2.3 Features of Argument Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
13.2.4 Documentation Strings of Functions . . . . . . . . . . . . . . . . . . . . 226
13.3 Naming a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
13.4 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
13.5 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
13.6 Mapping Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
13.7 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
13.8 Generic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
13.9 Accessing Function Cell Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
13.10 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
13.11 Advising Emacs Lisp Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
13.11.1 Primitives to manipulate advices . . . . . . . . . . . . . . . . . . . . . . 241
13.11.2 Advising Named Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
viii
14 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
14.1 A Simple Example of a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
14.2 Expansion of a Macro Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
14.3 Macros and Byte Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
14.4 Defining Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
14.5 Common Problems Using Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
14.5.1 Wrong Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
14.5.2 Evaluating Macro Arguments Repeatedly . . . . . . . . . . . . . . . 258
14.5.3 Local Variables in Macro Expansions . . . . . . . . . . . . . . . . . . . 260
14.5.4 Evaluating Macro Arguments in Expansion . . . . . . . . . . . . . 260
14.5.5 How Many Times is the Macro Expanded? . . . . . . . . . . . . . . 261
14.6 Indenting Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
16 Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
16.1 How Programs Do Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
16.2 Load Suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
16.3 Library Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
16.4 Loading Non-ASCII Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
16.5 Autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
16.5.1 Autoload by Prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
16.5.2 When to Use Autoload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
16.6 Repeated Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
16.7 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
16.8 Which File Defined a Certain Symbol. . . . . . . . . . . . . . . . . . . . . . . . 297
16.9 Unloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
ix
21 Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
21.1 Introduction to Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
21.2 Reading Text Strings with the Minibuffer . . . . . . . . . . . . . . . . . . . . 365
21.3 Reading Lisp Objects with the Minibuffer . . . . . . . . . . . . . . . . . . . 370
21.4 Minibuffer History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
21.5 Initial Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
21.6 Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
21.6.1 Basic Completion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
21.6.2 Completion and the Minibuffer . . . . . . . . . . . . . . . . . . . . . . . . . 376
21.6.3 Minibuffer Commands that Do Completion . . . . . . . . . . . . . 378
21.6.4 High-Level Completion Functions . . . . . . . . . . . . . . . . . . . . . . . 380
21.6.5 Reading File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
21.6.6 Completion Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
21.6.7 Programmed Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
21.6.8 Completion in Ordinary Buffers . . . . . . . . . . . . . . . . . . . . . . . . 389
21.7 Yes-or-No Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
21.8 Asking Multiple-Choice Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
21.9 Reading a Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
21.10 Minibuffer Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
21.11 Minibuffer Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
21.12 Minibuffer Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
21.13 Recursive Minibuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
21.14 Inhibiting Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
21.15 Minibuffer Miscellany . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
xi
23 Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
23.1 Key Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
23.2 Keymap Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
23.3 Format of Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
23.4 Creating Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
23.5 Inheritance and Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
23.6 Prefix Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
23.7 Active Keymaps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
23.8 Searching the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
23.9 Controlling the Active Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
23.10 Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
23.11 Functions for Key Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
23.12 Changing Key Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
23.13 Remapping Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
23.14 Keymaps for Translating Sequences of Events . . . . . . . . . . . . . . . 470
23.14.1 Interaction with normal keymaps . . . . . . . . . . . . . . . . . . . . . . 472
23.15 Commands for Binding Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
23.16 Scanning Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
23.17 Menu Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
23.17.1 Defining Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
23.17.1.1 Simple Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
23.17.1.2 Extended Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
23.17.1.3 Menu Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
23.17.1.4 Alias Menu Items. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
23.17.2 Menus and the Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
23.17.3 Menus and the Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
23.17.4 Menu Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
23.17.5 The Menu Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
23.17.6 Tool bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
23.17.7 Modifying Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
23.17.8 Easy Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
25 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
25.1 Documentation Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
25.2 Access to Documentation Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
25.3 Substituting Key Bindings in Documentation . . . . . . . . . . . . . . . . 554
25.4 Text Quoting Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
25.5 Describing Characters for Help Messages . . . . . . . . . . . . . . . . . . . . 557
25.6 Help Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
25.7 Documentation Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
xiv
26 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
26.1 Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
26.1.1 Functions for Visiting Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
26.1.2 Subroutines of Visiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
26.2 Saving Buffers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
26.3 Reading from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
26.4 Writing to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
26.5 File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
26.6 Information about Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
26.6.1 Testing Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
26.6.2 Distinguishing Kinds of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
26.6.3 Truenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
26.6.4 File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
26.6.5 Extended File Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
26.6.6 Locating Files in Standard Places . . . . . . . . . . . . . . . . . . . . . . . 584
26.7 Changing File Names and Attributes . . . . . . . . . . . . . . . . . . . . . . . . 584
26.8 Files and Secondary Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
26.9 File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
26.9.1 File Name Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
26.9.2 Absolute and Relative File Names . . . . . . . . . . . . . . . . . . . . . . 592
26.9.3 Directory Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
26.9.4 Functions that Expand Filenames. . . . . . . . . . . . . . . . . . . . . . . 594
26.9.5 Generating Unique File Names . . . . . . . . . . . . . . . . . . . . . . . . . 597
26.9.6 File Name Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
26.9.7 Standard File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
26.10 Contents of Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
26.11 Creating, Copying and Deleting Directories . . . . . . . . . . . . . . . . . 603
26.12 Making Certain File Names “Magic” . . . . . . . . . . . . . . . . . . . . . . . 604
26.13 File Format Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
26.13.1 Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
26.13.2 Round-Trip Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
26.13.3 Piecemeal Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
28 Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
28.1 Buffer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
28.2 The Current Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
28.3 Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
28.4 Buffer File Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
28.5 Buffer Modification. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
28.6 Buffer Modification Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
28.7 Read-Only Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
28.8 The Buffer List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
28.9 Creating Buffers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
28.10 Killing Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
28.11 Indirect Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
28.12 Swapping Text Between Two Buffers . . . . . . . . . . . . . . . . . . . . . . . 642
28.13 The Buffer Gap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
29 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
29.1 Basic Concepts of Emacs Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 644
29.2 Windows and Frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
29.3 Selecting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
29.4 Window Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
29.5 Resizing Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
29.6 Preserving Window Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
29.7 Splitting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
29.8 Deleting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
29.9 Recombining Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
29.10 Cyclic Ordering of Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
29.11 Buffers and Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
29.12 Switching to a Buffer in a Window . . . . . . . . . . . . . . . . . . . . . . . . . 675
29.13 Displaying a Buffer in a Suitable Window . . . . . . . . . . . . . . . . . . 677
29.13.1 Choosing a Window for Displaying a Buffer . . . . . . . . . . . . 678
29.13.2 Action Functions for Buffer Display. . . . . . . . . . . . . . . . . . . . 680
29.13.3 Action Alists for Buffer Display. . . . . . . . . . . . . . . . . . . . . . . . 684
29.13.4 Additional Options for Displaying Buffers. . . . . . . . . . . . . . 687
29.13.5 Precedence of Action Functions . . . . . . . . . . . . . . . . . . . . . . . . 690
29.13.6 The Zen of Buffer Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
29.14 Window History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
29.15 Dedicated Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
29.16 Quitting Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
29.17 Side Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
29.17.1 Displaying Buffers in Side Windows . . . . . . . . . . . . . . . . . . . 704
29.17.2 Side Window Options and Functions. . . . . . . . . . . . . . . . . . . 705
29.17.3 Frame Layouts with Side Windows . . . . . . . . . . . . . . . . . . . . 706
29.18 Atomic Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
29.19 Windows and Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
29.20 The Window Start and End Positions . . . . . . . . . . . . . . . . . . . . . . 711
29.21 Textual Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
29.22 Vertical Fractional Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
29.23 Horizontal Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
xvi
30 Frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
30.1 Creating Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
30.2 Multiple Terminals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
30.3 Frame Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
30.3.1 Frame Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
30.3.2 Frame Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
30.3.3 Frame Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
30.3.4 Frame Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
30.3.5 Implied Frame Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
30.4 Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
30.4.1 Access to Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
30.4.2 Initial Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
30.4.3 Window Frame Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
30.4.3.1 Basic Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
30.4.3.2 Position Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
30.4.3.3 Size Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
30.4.3.4 Layout Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
30.4.3.5 Buffer Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
30.4.3.6 Frame Interaction Parameters. . . . . . . . . . . . . . . . . . . . . . 763
30.4.3.7 Mouse Dragging Parameters . . . . . . . . . . . . . . . . . . . . . . . 764
30.4.3.8 Window Management Parameters . . . . . . . . . . . . . . . . . . 765
30.4.3.9 Cursor Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
30.4.3.10 Font and Color Parameters . . . . . . . . . . . . . . . . . . . . . . . 768
30.4.4 Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
30.5 Terminal Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
30.6 Frame Titles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
30.7 Deleting Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
30.8 Finding All Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
30.9 Minibuffers and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
30.10 Input Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
30.11 Visibility of Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
30.12 Raising, Lowering and Restacking Frames . . . . . . . . . . . . . . . . . . 779
30.13 Frame Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
30.14 Child Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
30.15 Mouse Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
30.16 Mouse Position. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
30.17 Pop-Up Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
30.18 Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
30.19 Pointer Shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
30.20 Window System Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
30.21 Drag and Drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
30.22 Color Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
xvii
31 Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
31.1 Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
31.2 Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
31.2.1 Motion by Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
31.2.2 Motion by Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
31.2.3 Motion to an End of the Buffer . . . . . . . . . . . . . . . . . . . . . . . . . 800
31.2.4 Motion by Text Lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
31.2.5 Motion by Screen Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
31.2.6 Moving over Balanced Expressions . . . . . . . . . . . . . . . . . . . . . . 805
31.2.7 Skipping Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
31.3 Excursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
31.4 Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
32 Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
32.1 Overview of Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
32.2 Predicates on Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
32.3 Functions that Create Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
32.4 Information from Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
32.5 Marker Insertion Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
32.6 Moving Marker Positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
32.7 The Mark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
32.8 The Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
33 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
33.1 Examining Text Near Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
33.2 Examining Buffer Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
33.3 Comparing Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
33.4 Inserting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
33.5 User-Level Insertion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
33.6 Deleting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
33.7 User-Level Deletion Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
33.8 The Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
33.8.1 Kill Ring Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
33.8.2 Functions for Killing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
33.8.3 Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
33.8.4 Functions for Yanking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
33.8.5 Low-Level Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
33.8.6 Internals of the Kill Ring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
33.9 Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
33.10 Maintaining Undo Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840
33.11 Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
33.12 Margins for Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 844
33.13 Adaptive Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
xviii
38 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
38.1 Basic Thread Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
38.2 Mutexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984
38.3 Condition Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984
38.4 The Thread List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985
39 Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
39.1 Functions that Create Subprocesses. . . . . . . . . . . . . . . . . . . . . . . . . . 987
39.2 Shell Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989
39.3 Creating a Synchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990
39.4 Creating an Asynchronous Process . . . . . . . . . . . . . . . . . . . . . . . . . . 995
39.5 Deleting Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1000
39.6 Process Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1001
39.7 Sending Input to Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1004
39.8 Sending Signals to Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
39.9 Receiving Output from Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
39.9.1 Process Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1008
39.9.2 Process Filter Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1010
39.9.3 Decoding Process Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1011
39.9.4 Accepting Output from Processes . . . . . . . . . . . . . . . . . . . . . . 1012
39.9.5 Processes and Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1013
39.10 Sentinels: Detecting Process Status Changes. . . . . . . . . . . . . . . 1014
39.11 Querying Before Exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016
39.12 Accessing Other Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016
39.13 Transaction Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1018
39.14 Network Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019
39.15 Network Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1022
39.16 Datagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023
39.17 Low-Level Network Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023
39.17.1 make-network-process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023
xxi
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1298
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 [No value for “VERSION”] of the GNU Emacs Lisp Reference Manual,
corresponding to Emacs version 28.2.
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. If you wish to
contribute new code (or send a patch to fix a problem), use M-x submit-emacs-patch.
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 184.
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 25
[Documentation], page 551).
See Section 13.2 [Lambda Expressions], page 223, 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.
emacs-repository-version [Variable]
A string that gives the repository revision from which Emacs was built. If Emacs was
built outside revision control, the value is nil.
emacs-repository-branch [Variable]
A string that gives the repository branch from which Emacs was built. In the most
cases this is "master". If Emacs was built outside revision control, the value is nil.
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
‘#@N’ Skip the next ‘N’ characters (see Section 2.3 [Comments], page 10). This is used
in byte-compiled files, and is not meant to be used in Emacs Lisp source files.
‘#f’ Indicates that the following form isn’t readable by the Emacs Lisp reader. This
is only in text for display purposes (when that would look prettier than alterna-
tive ways of indicating an unreadable form) and will never appear in any Lisp
file.
2.3 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 301). It isn’t meant for source files,
however.
See Section D.7 [Comment Tips], page 1237, for conventions for formatting comments.
and ‘?\e’, respectively. (‘?\s’ followed by a dash has a different meaning—it applies the
Super modifier to the following character.) Thus,
?\a ⇒ 7 ; control-g, C-g
?\b ⇒ 8 ; backspace, BS, C-h
?\t ⇒ 9 ; tab, TAB, C-i
?\n ⇒ 10 ; newline, C-j
?\v ⇒ 11 ; vertical tab, C-k
?\f ⇒ 12 ; formfeed character, C-l
?\r ⇒ 13 ; carriage return, RET, C-m
?\e ⇒ 27 ; escape character, ESC, C-[
?\s ⇒ 32 ; space character, SPC
?\\ ⇒ 92 ; backslash character, \
?\d ⇒ 127 ; delete character, DEL
These sequences which start with backslash are also known as escape sequences, because
backslash plays the role of an escape character; this 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 should also add a backslash before Unicode
characters which resemble the previously mentioned ASCII ones, to avoid confusing people
reading your code. Emacs will highlight some non-escaped commonly confused characters
such as ‘‘’ to encourage this. 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.4.8.2 [Non-ASCII in
Strings], page 20.
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 18
The printed representation of a vector consists of a left square bracket, the elements,
and a right square bracket. This is also the read syntax. Like numbers and strings, vectors
are considered constants for evaluation.
[1 "two" (three)] ; A vector of three elements.
⇒ [1 "two" (three)]
See Section 6.4 [Vectors], page 114, for functions that work with vectors.
reason is that the primitive function may be called directly from C code. Calls to the
redefined function from Lisp will use the new definition, but calls from C code may still use
the built-in definition. Therefore, we discourage redefinition of primitive functions.
The term function refers to all Emacs functions, whether written in Lisp or C. See
Section 2.4.13 [Function Type], page 23, for information about the functions written in
Lisp.
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.
An autoload object is usually created with the function autoload, which stores the
object in the function cell of a symbol. See Section 16.5 [Autoload], page 290, for more
details.
This makes a list whose second element is the list itself. Here’s how you can see that it
really works:
(prog1 nil
(setq x '#1=(a #1#)))
(eq x (cadr x))
⇒ t
The Lisp printer can produce this syntax to record circular and shared structure in a
Lisp object, if you bind the variable print-circle to a non-nil value. See Section 20.6
[Output Variables], page 360.
(eq ?A ?A)
⇒ t
For equal, equality is defined 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))
Comparing circular lists may therefore cause deep recursion that leads to an error, and
this may result in counterintuitive behavior such as (equal a b) returning t whereas (equal
b a) signals an error.
2.9 Mutability
Some Lisp objects should never change. For example, the Lisp expression "aaa" yields
a string, but you should not change its contents. And some objects cannot be changed;
for example, although you can create a new number by calculating one, Lisp provides no
operation to change the value of an existing number.
Other Lisp objects are mutable: it is safe to change their values via destructive operations
involving side effects. For example, an existing marker can be changed by moving the marker
to point to somewhere else.
Although numbers never change and all markers are mutable, some types have members
some of which are mutable and others not. These types include conses, vectors, and strings.
For example, although "cons" and (symbol-name 'cons) both yield strings that should
not be changed, (copy-sequence "cons") and (make-string 3 ?a) both yield mutable
strings that can be changed via later calls to aset.
A mutable object stops being mutable if it is part of an expression that is evaluated.
For example:
(let* ((x (list 0.5))
(y (eval (list 'quote x))))
(setcar x 1.5) ;; The program should not do this.
y)
Although the list (0.5) was mutable when it was created, it should not have been changed
via setcar because it was given to eval. The reverse does not occur: an object that should
not be changed never becomes mutable afterwards.
If a program attempts to change objects that should not be changed, the resulting
behavior is undefined: the Lisp interpreter might signal an error, or it might crash or
behave unpredictably in other ways.2
When similar constants occur as parts of a program, the Lisp interpreter might save
time or space by reusing existing constants or their components. For example, (eq "abc"
"abc") returns t if the interpreter creates only one instance of the string literal "abc", and
returns nil if it creates two instances. Lisp programs should be written so that they work
regardless of whether this optimization is in use.
2
This is the behavior specified for languages like Common Lisp and C for constants, and this differs from
languages like JavaScript and Python where an interpreter is required to signal an error if a program
attempts to change an immutable object. Ideally the Emacs Lisp interpreter will evolve in latter direction.
37
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 exponen-
tial 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. Floating-point computations
often involve rounding errors, as the numbers have a fixed amount of precision.
functions may be either numbers or markers, we often give these arguments the name
number-or-marker. When the argument value is a marker, its position value is used and its
buffer is ignored.
In Emacs Lisp, text characters are represented by integers. Any integer between zero and
the value of (max-char), inclusive, is considered to be valid as a character. See Section 34.5
[Character Codes], page 904.
Integers in Emacs Lisp are not limited to the machine word size. Under the hood,
though, there are two kinds of integers: smaller ones, called fixnums, and larger ones, called
bignums. Although Emacs Lisp code ordinarily should not depend on whether an integer is
a fixnum or a bignum, older Emacs versions support only fixnums, some functions in Emacs
still accept only fixnums, and older Emacs Lisp code may have trouble when given bignums.
For example, while older Emacs Lisp code could safely compare integers for numeric equality
with eq, the presence of bignums means that equality predicates like eql and = should now
be used to compare integers.
The range of values for bignums is limited by the amount of main memory, by machine
characteristics such as the size of the word used to represent a bignum’s exponent, and by
the integer-width variable. These limits are typically much more generous than the limits
for fixnums. A bignum is never numerically equal to a fixnum; Emacs always represents an
integer in fixnum range as a fixnum, not a bignum.
The range of values for a fixnum depends on the machine. The minimum range is
−536,870,912 to 536,870,911 (30 bits; i.e., −229 to 229 − 1), but many machines provide a
wider range.
most-positive-fixnum [Variable]
The value of this variable is the greatest “small” integer that Emacs Lisp can handle.
Typical values are 229 − 1 on 32-bit and 261 − 1 on 64-bit platforms.
most-negative-fixnum [Variable]
The value of this variable is the numerically least “small” integer that Emacs Lisp
can handle. It is negative. Typical values are −229 on 32-bit and −261 on 64-bit
platforms.
integer-width [Variable]
The value of this variable is a nonnegative integer that controls whether Emacs signals
a range error when a large integer would be calculated. Integers with absolute values
less than 2n , where n is this variable’s value, do not signal a range error. Attempts to
create larger integers typically signal a range error, although there might be no signal
if a larger integer can be created cheaply. Setting this variable to a large number can
be costly if a computation creates huge integers.
modern platforms, floating-point operations follow the IEEE-754 standard closely; however,
results are not always rounded correctly on some obsolescent platforms, notably 32-bit x86.
The read syntax for floating-point numbers requires either a decimal point, an exponent,
or both. Optional signs (‘+’ or ‘-’) precede the number and its exponent. For example,
‘1500.0’, ‘+15e2’, ‘15.0e+2’, ‘+1500000e-3’, and ‘.15e4’ are five ways of writing a floating-
point number whose value is 1500. They are all equivalent. Like Common Lisp, Emacs Lisp
requires at least one digit after a decimal point in a floating-point number that does not
have an exponent; ‘1500.’ is an integer, not a floating-point number.
Emacs Lisp treats -0.0 as numerically equal to ordinary zero with respect to numeric
comparisons like =. This follows the IEEE floating-point standard, which says -0.0 and 0.0
are numerically equal even though other operations can distinguish them.
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. A NaN is never numerically equal to any value, not
even to itself. NaNs carry a sign and a significand, and non-numeric functions treat two
NaNs as equal when their signs and significands agree. Significands of NaNs are machine-
dependent, as are the digits in their string representation.
When NaNs and signed zeros are involved, non-numeric functions like eql, equal,
sxhash-eql, sxhash-equal and gethash determine whether values are indistinguishable,
not whether they are numerically equal. For example, when x and y are the same NaN,
(equal x y) returns t whereas (= x y) uses numeric comparison and returns nil; con-
versely, (equal 0.0 -0.0) returns nil whereas (= 0.0 -0.0) returns t.
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.
Chapter 3: Numbers 40
logb x [Function]
This function returns the binary exponent of x. More precisely, if x is finite and
nonzero, the value is the logarithm base 2 of |x|, rounded down to an integer. If x is
zero or infinite, the value is infinity; if x is a NaN, the value is a NaN.
(logb 10)
⇒ 3
(logb 10.0e20)
⇒ 69
(logb 0)
⇒ -1.0e+INF
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.
(truncate 1.7)
⇒ 1
(truncate -1.2)
⇒ -1
(truncate -1.7)
⇒ -1
⇒ 1
(* 1)
⇒ 1
(* 1 2 3 4)
⇒ 24
⇒ 1
(% -9 -4)
⇒ -1
(ash 7 -1) ⇒ 3
...000111
⇒
...000011
(ash -7 1) ⇒ -14
...111001
⇒
...110010
(ash -7 -1) ⇒ -4
...111001
⇒
...111100
Here are examples of shifting left or right by two bits:
Chapter 3: Numbers 48
; binary values
(ash 5 2) ; 5 = . . . 000101
⇒ 20 ; = . . . 010100
(ash -5 2) ; -5 = . . . 111011
⇒ -20 ; = . . . 101100
(ash 5 -2)
⇒ 1 ; = . . . 000001
(ash -5 -2)
⇒ -2 ; = . . . 111110
(logand 14 13 4) ; 14 = . . . 001110
; 13 = . . . 001101
; 4 = . . . 000100
⇒ 4 ; 4 = . . . 000100
(logand)
⇒ -1 ; -1 = . . . 111111
(logior 12 5) ; 12 = . . . 001100
; 5 = . . . 000101
⇒ 13 ; 13 = . . . 001101
(logior 12 5 7) ; 12 = . . . 001100
; 5 = . . . 000101
; 7 = . . . 000111
⇒ 15 ; 15 = . . . 001111
(logxor 12 5) ; 12 = . . . 001100
; 5 = . . . 000101
⇒ 9 ; 9 = . . . 001001
(logxor 12 5 7) ; 12 = . . . 001100
; 5 = . . . 000101
; 7 = . . . 000111
⇒ 14 ; 14 = . . . 001110
expt x y [Function]
This function returns x raised to power y. If both arguments are integers and y is
nonnegative, the result is an integer; in this case, overflow signals an error, 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 51
See Chapter 33 [Text], page 820, for information about functions that display strings
or copy them into buffers. See Section 2.4.3 [Character Type], page 11, and Section 2.4.8
[String Type], page 19, for information about the syntax of characters and strings. See
Chapter 34 [Non-ASCII Characters], page 900, for functions to convert between text repre-
sentations and to encode and decode character codes. Also, note that length should not be
used for computing the width of a string on display; use string-width (see Section 40.10
[Size of Displayed Text], page 1064) instead.
The result is not ("" "two" "words" ""), which would rarely be useful. If you need
such a result, use an explicit value for separators:
(split-string " two words "
split-string-default-separators)
⇒ ("" "two" "words" "")
(split-string "Soup is good food" "o")
⇒ ("S" "up is g" "" "d f" "" "d")
(split-string "Soup is good food" "o" t)
⇒ ("S" "up is g" "d f" "d")
(split-string "Soup is good food" "o+")
⇒ ("S" "up is g" "d f" "d")
Empty matches do count, except that split-string will not look for a final empty
match when it already reached the end of the string using a non-empty match or
when string is empty:
(split-string "aooob" "o*")
⇒ ("" "a" "" "b" "")
(split-string "ooaboo" "o*")
⇒ ("" "" "a" "b" "")
(split-string "" "")
⇒ ("")
However, when separators can match the empty string, omit-nulls is usually t, so
that the subtleties in the three previous examples are rarely relevant:
(split-string "Soup is good food" "o*" t)
⇒ ("S" "u" "p" " " "i" "s" " " "g" "d" " " "f" "d")
(split-string "Nice doggy!" "" t)
⇒ ("N" "i" "c" "e" " " "d" "o" "g" "g" "y" "!")
(split-string "" "" t)
⇒ nil
Somewhat odd, but predictable, behavior can occur for certain “non-greedy” values
of separators that can prefer empty matches over non-empty matches. Again, such
values rarely occur in practice:
(split-string "ooo" "o*" t)
⇒ nil
(split-string "ooo" "\\|o+" t)
⇒ ("o" "o" "o")
split-string-default-separators [Variable]
The default value of separators for split-string. Its usual value is
"[ \f\t\n\r\v]+".
index idx. It will automatically convert a pure-ASCII string to a multibyte string (see
Section 34.1 [Text Representations], page 900) if needed, but we recommend to always make
sure string is multibyte (e.g., by using string-to-multibyte, see Section 34.3 [Converting
Representations], page 902), if char is a non-ASCII character, not a raw byte.
A more powerful function is store-substring:
store-substring string idx obj [Function]
This function alters part of the contents of the specified string, by storing obj starting
at character index idx. The argument obj may be either a character (in which case
the function behaves exactly as aset) or a (smaller) string. If obj is a multibyte
string, we recommend to make sure string is also multibyte, even if it’s pure-ASCII.
Since it is impossible to change the number of characters in an existing string, it is en
error if obj consists of more characters than would fit in string starting at character
index idx.
To clear out a string that contained a password, use clear-string:
clear-string string [Function]
This makes string a unibyte string and clears its contents to zeros. It may also change
string’s length.
For technical reasons, a unibyte and a multibyte string are equal if and only if they
contain the same sequence of character codes and all these codes are either in the
range 0 through 127 (ASCII) or 160 through 255 (eight-bit-graphic). However,
when a unibyte string is converted to a multibyte string, all characters with codes
in the range 160 through 255 are converted to characters with higher codes, whereas
ASCII characters remain unchanged. Thus, a unibyte string and its conversion to
multibyte are only equal if the string is all ASCII. Character codes 160 through
255 are not entirely proper in multibyte text, even though they can occur. As a
consequence, the situation where a unibyte and a multibyte string are equal without
both being all ASCII is a technical oddity that very few Emacs Lisp programmers
ever get confronted with. See Section 34.1 [Text Representations], page 900.
the lesser character of these two is the character from string1, then string1 is less, and
this function returns t. If the lesser character is the one from string2, then string1 is
greater, and this function returns nil. If the two strings match entirely, the value is
nil.
Pairs of characters are compared according to their character codes. Keep in mind
that lower case letters have higher numeric values in the ASCII character set than
their upper case counterparts; digits and many punctuation characters have a lower
numeric value than upper case letters. An ASCII character is less than any non-ASCII
character; a unibyte non-ASCII character is always less than any multibyte non-ASCII
character (see Section 34.1 [Text Representations], page 900).
(string< "abc" "abd")
⇒ t
(string< "abd" "abc")
⇒ nil
(string< "123" "abc")
⇒ t
When the strings have different lengths, and they match up to the length of string1,
then the result is t. If they match up to the length of string2, the result is nil. A
string of no characters is less than any other string.
(string< "" "abc")
⇒ t
(string< "ab" "abc")
⇒ t
(string< "abc" "")
⇒ nil
(string< "abc" "ab")
⇒ nil
(string< "" "")
⇒ nil
Symbols are also allowed as arguments, in which case their print names are compared.
string-lessp string1 string2 [Function]
string-lessp is another name for string<.
string-greaterp string1 string2 [Function]
This function returns the result of comparing string1 and string2 in the opposite
order, i.e., it is equivalent to calling (string-lessp string2 string1).
string-collate-lessp string1 string2 &optional locale ignore-case [Function]
This function returns t if string1 is less than string2 in collation order. A collation
order is not only determined by the lexicographic order of the characters 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, punctuation and whitespace characters might be ignored for sorting (see
Section 6.1 [Sequence Functions], page 99):
(sort (list "11" "12" "1 1" "1 2" "1.1" "1.2") 'string-collate-lessp)
⇒ ("11" "1 1" "1.1" "12" "1 2" "1.2")
Chapter 4: Strings and Characters 61
This behavior is system-dependent; e.g., punctuation and whitespace are never ig-
nored on Cygwin, regardless of locale.
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. The locale value of "POSIX" or "C" lets string-collate-lessp behave like
string-lessp:
(sort (list "11" "12" "1 1" "1 2" "1.1" "1.2")
(lambda (s1 s2) (string-collate-lessp s1 s2 "POSIX")))
⇒ ("1 1" "1 2" "1.1" "1.2" "11" "12")
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-lessp.
string-version-lessp string1 string2 [Function]
This function compares strings lexicographically, except it treats sequences of nu-
merical characters as if they comprised a base-ten number, and then compares the
numbers. So ‘foo2.png’ is “smaller” than ‘foo12.png’ according to this predicate,
even if ‘12’ is lexicographically “smaller” than ‘2’.
string-prefix-p string1 string2 &optional ignore-case [Function]
This function returns non-nil if string1 is a prefix of string2; i.e., if string2 starts
with string1. If the optional argument ignore-case is non-nil, the comparison ignores
case differences.
string-suffix-p suffix string &optional ignore-case [Function]
This function returns non-nil if suffix is a suffix of string; i.e., if string ends with
suffix. If the optional argument ignore-case is non-nil, the comparison ignores case
differences.
string-search needle haystack &optional start-pos [Function]
Return the position of the first instance of needle in haystack, both of which are
strings. If start-pos is non-nil, start searching from that position in needle. Return
nil if no match was found. This function only considers the characters in the strings
when doing the comparison; text properties are ignored. Matching is always case-
sensitive.
compare-strings string1 start1 end1 string2 start2 end2 &optional [Function]
ignore-case
This function compares a specified part of string1 with a specified part of string2.
The specified part of string1 runs from index start1 (inclusive) up to index end1
(exclusive); nil for start1 means the start of the string, while nil for end1 means
the length of the string. Likewise, the specified part of string2 runs from index start2
up to index end2.
Chapter 4: Strings and Characters 62
The strings are compared by the numeric values of their characters. For instance, str1
is considered less than str2 if its first differing character has a smaller numeric value.
If ignore-case is non-nil, characters are converted to upper-case, using the current
buffer’s case-table (see Section 4.10 [Case Tables], page 72), before comparing them.
Unibyte strings are converted to multibyte for comparison (see Section 34.1 [Text
Representations], page 900), so that a unibyte string and its conversion to multibyte
are always regarded as equal.
If the specified portions of the two strings match, the value is t. Otherwise, the value
is an integer which indicates how many leading characters agree, and which string
is less. Its absolute value is one plus the number of characters that agree at the
beginning of the two strings. The sign is negative if string1 (or its specified portion)
is less.
string-distance string1 string2 &optional bytecompare [Function]
This function returns the Levenshtein distance between the source string string1
and the target string string2. The Levenshtein distance is the number of single-
character changes—deletions, insertions, or replacements—required to transform the
source string into the target string; it is one possible definition of the edit distance
between strings.
Letter-case of the strings is significant for the computed distance, but their text prop-
erties are ignored. If the optional argument bytecompare is non-nil, the function
calculates the distance in terms of bytes instead of characters. The byte-wise compar-
ison uses the internal Emacs representation of characters, so it will produce inaccurate
results for multibyte strings that include raw bytes (see Section 34.1 [Text Represen-
tations], page 900); make the strings unibyte by encoding them (see Section 34.10.7
[Explicit Encoding], page 925) if you need accurate results with raw bytes.
assoc-string key alist &optional case-fold [Function]
This function works like assoc, except that key must be a string or symbol, and
comparison is done using compare-strings. Symbols are converted to strings before
testing. If case-fold is non-nil, key and the elements of alist are converted to upper-
case before comparison. Unlike assoc, this function can also match elements of the
alist that are strings or symbols rather than conses. In particular, alist can be a list
of strings or symbols rather than an actual alist. See Section 5.8 [Association Lists],
page 92.
See also the function compare-buffer-substrings in Section 33.3 [Comparing Text],
page 824, for a way to compare text in buffers. The function string-match, which matches
a regular expression against a string, can be used for a kind of string comparison; see
Section 35.4 [Regexp Search], page 945.
and string-to-unibyte convert the text representation of a string (see Section 34.3
[Converting Representations], page 902).
See Chapter 25 [Documentation], page 551, for functions that produce textual
descriptions of text characters and general input events (single-key-description and
text-char-description). These are used primarily for making help messages.
Here are some other functions that can convert to or from a string:
concat This function converts a vector or a list into a string. See Section 4.3 [Creating
Strings], page 53.
vconcat This function converts a string into a vector. See Section 6.5 [Vector Functions],
page 114.
append This function converts a string into a list. See Section 5.4 [Building Lists],
page 79.
byte-to-string
This function converts a byte of character data into a unibyte string. See
Section 34.3 [Converting Representations], page 902.
used if the exponent would be less than −4 or greater than or equal to the
precision (default: 6). By default, trailing zeros are removed from the fractional
portion of the result and a decimal-point character appears only if it is followed
by a digit.
‘%%’ Replace the specification with a single ‘%’. This format specification is unusual
in that its only form is plain ‘%%’ and that it does not use a value. For example,
(format "%% %d" 30) returns "% 30".
Any other format character results in an ‘Invalid format operation’ error.
Here are several examples, which assume the typical text-quoting-style settings:
(format "The octal value of %d is %o,
and the hex value is %x." 18 18 18)
⇒ "The octal value of 18 is 22,
and the hex value is 12."
(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 nonnegative number, so that it always has a
sign. A space character as flag inserts a space before a nonnegative number. (Otherwise,
nonnegative numbers start with the first digit.) These flags are useful for ensuring that
nonnegative 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 nonzero results
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.
Chapter 4: Strings and Characters 67
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.
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"
format just nonnegative integers you can also use ‘#x%x’ and ‘#o%o’. Other formats may be
problematic; for example, ‘%d’ and ‘%g’ can mishandle NaNs and can lose precision and type,
and ‘#x%x’ and ‘#o%o’ can mishandle negative integers. See Section 20.3 [Input Functions],
page 355.
The functions described in this section accept a fixed set of specification characters.
The next section describes a function format-spec which can accept custom specification
characters, such as ‘%a’ or ‘%z’.
including their text properties, if any; if it is delete, those format specifications are
removed from the output; any other non-nil value is handled like ignore, but any
occurrences of ‘%%’ are also left verbatim in the output.
If the optional argument split is non-nil, instead of returning a single string,
format-spec will split the result into a list of strings, based on where the
substitutions were performed. For instance:
(format-spec "foo %b bar" '((?b . "zot")) nil t)
⇒ ("foo " "zot" " bar")
The syntax of format specifications accepted by format-spec is similar, but not identical,
to that accepted by format. In both cases, a format specification is a sequence of characters
beginning with ‘%’ and ending with an alphabetic letter such as ‘s’.
Unlike format, which assigns specific meanings to a fixed set of specification characters,
format-spec accepts arbitrary specification characters and treats them all equally. For
example:
(setq my-site-info
(list (cons ?s system-name)
(cons ?t (symbol-name system-type))
(cons ?c system-configuration)
(cons ?v emacs-version)
(cons ?e invocation-name)
(cons ?p (number-to-string (emacs-pid)))
(cons ?a user-mail-address)
(cons ?n user-full-name)))
‘0’ This flag causes any padding specified by the width to consist of ‘0’ characters
instead of spaces.
‘-’ This flag causes any padding specified by the width to be inserted on the right
rather than the left.
‘<’ This flag causes the substitution to be truncated on the left to the given width
and precision, if specified.
‘>’ This flag causes the substitution to be truncated on the right to the given width,
if specified.
‘^’ This flag converts the substituted text to upper case (see Section 4.9 [Case
Conversion], page 70).
Chapter 4: Strings and Characters 70
‘_ (underscore)’
This flag converts the substituted text to lower case (see Section 4.9 [Case
Conversion], page 70).
The result of using contradictory flags (for instance, both upper and lower case) is
undefined.
As is the case with format, a format specification can include a width, which is a decimal
number that appears after any flags, and a precision, which is a decimal-point ‘.’ followed
by a decimal number that appears after any flags and width.
If a substitution contains fewer characters than its specified width, it is padded on the
left:
(format-spec "%8a is padded on the left with spaces"
'((?a . "alpha")))
⇒ " alpha is padded on the left with spaces"
If a substitution contains more characters than its specified precision, it is truncated on
the right:
(format-spec "%.2a is truncated on the right"
'((?a . "alpha")))
⇒ "al is truncated on the right"
Here is a more complicated example that combines several aforementioned features:
(setq my-battery-info
(list (cons ?p "73") ; Percentage
(cons ?L "Battery") ; Status
(cons ?t "2:23") ; Remaining time
(cons ?c "24330") ; Capacity
(cons ?r "10.6"))) ; Rate of discharge
can specify a different case conversion mapping by specifying a case table (see Section 4.10
[Case Tables], page 72).
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 36.2.1
[Syntax Class Table], page 959).
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 34.6 [Character Properties], page 905.
See Section 4.5 [Text Comparison], page 58, 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 36 [Syntax Tables], page 958. 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.
75
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.
(car '(a b c))
⇒ a
(car '())
⇒ nil
cdr cons-cell [Function]
This function returns the value referred to by the second slot of the cons cell cons-cell.
In other words, it returns the cdr of cons-cell.
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
car-safe object [Function]
This function lets you take the car of a cons cell while avoiding errors for other data
types. It returns the car of object if object is a cons cell, nil otherwise. This is in
contrast to car, which signals an error if object is not a list.
(car-safe object)
≡
(let ((x object))
(if (consp x)
(car x)
nil))
cdr-safe object [Function]
This function lets you take the cdr of a cons cell while avoiding errors for other data
types. It returns the cdr of object if object is a cons cell, nil otherwise. This is in
contrast to cdr, which signals an error if object is not a list.
(cdr-safe object)
≡
(let ((x object))
(if (consp x)
(cdr x)
nil))
pop listname [Macro]
This macro provides a convenient way to examine the car of a list, and take it off
the list, all at once. It operates on the list stored in listname. It removes the first
element from the list, saves the cdr into listname, then returns the removed element.
In the simplest case, listname is an unquoted symbol naming a list; in that case, this
macro is equivalent to (prog1 (car listname) (setq listname (cdr listname))).
x
⇒ (a b c)
Chapter 5: Lists 78
(pop x)
⇒ a
x
⇒ (b c)
More generally, listname can be a generalized variable. In that case, this macro saves
into listname using setf. See Section 12.17 [Generalized Variables], page 217.
For the push macro, which adds an element to a list, See Section 5.5 [List Variables],
page 83.
nth n list [Function]
This function returns the nth element of list. Elements are numbered starting with
zero, so the car of list is element number zero. If the length of list is n or less, the
value is nil.
(nth 2 '(1 2 3 4))
⇒ 3
(nth 10 '(1 2 3 4))
⇒ nil
trees
⇒ (pine oak)
more-trees
⇒ (maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
⇒ t
You can see how append works by looking at a box diagram. The variable trees is set
to the list (pine oak) and then the variable more-trees is set to the list (maple birch
pine oak). However, the variable trees continues to refer to the original list:
more-trees trees
| |
| --- --- --- --- -> --- --- --- ---
--> | | |--> | | |--> | | |--> | | |--> nil
--- --- --- --- --- --- --- ---
| | | |
| | | |
--> maple -->birch --> pine --> oak
An empty sequence contributes nothing to the value returned by append. As a conse-
quence of this, a final nil argument forces a copy of the previous argument:
trees
⇒ (pine oak)
(setq wood (append trees nil))
⇒ (pine oak)
wood
⇒ (pine oak)
(eq wood trees)
⇒ nil
This once was the usual way to copy a list, before the function copy-sequence was invented.
See Chapter 6 [Sequences Arrays Vectors], page 99.
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 229), we can append
all the lists in a list of lists:
(apply 'append '((a b c) nil (x y z) nil))
⇒ (a b c x y z)
If no sequences are given, nil is returned:
(append)
⇒ nil
Here are some examples where the final argument is not a list:
(append '(x y) 'z)
⇒ (x y . z)
(append '(x y) [z])
⇒ (x y . [z])
Chapter 5: Lists 82
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.
copy-tree tree &optional vecp [Function]
This function returns a copy of the tree tree. If tree is a cons cell, this makes a new
cons cell with the same car and cdr, then recursively copies the car and cdr in
the same way.
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).
flatten-tree tree [Function]
This function returns a “flattened” copy of tree, that is, a list containing all the non-
nil terminal nodes, or leaves, of the tree of cons cells rooted at tree. Leaves in the
returned list are in the same order as in tree.
(flatten-tree '(1 (2 . 3) nil (4 5 (6)) 7))
⇒(1 2 3 4 5 6 7)
ensure-list object [Function]
This function returns object as a list. If object is already a list, the function returns
it; otherwise, the function returns a one-element list containing object.
This is usually useful if you have a variable that may or may not be a list, and you
can then say, for instance:
(dolist (elem (ensure-list foo))
(princ elem))
number-sequence from &optional to separation [Function]
This function returns a list of numbers starting with from and incrementing by
separation, and ending at or just before to. separation can be positive or negative and
defaults to 1. If to is nil or numerically equal to from, the value is the one-element
list (from). If to is less than from with a positive separation, or greater than from
with a negative separation, the value is nil because those arguments specify an empty
sequence.
If separation is 0 and to is neither nil nor numerically equal to from,
number-sequence signals an error, since those arguments specify an infinite
sequence.
All arguments are numbers. Floating-point arguments can be tricky, because floating-
point arithmetic is inexact. For instance, depending on the machine, it may quite well
happen that (number-sequence 0.4 0.6 0.2) returns the one element list (0.4),
whereas (number-sequence 0.4 0.8 0.2) returns a list with three elements. The nth
element of the list is computed by the exact formula (+ from (* n separation)).
Thus, if one wants to make sure that to is included in the list, one can pass an
expression of this exact type for to. Alternatively, one can replace to with a slightly
larger value (or a slightly more negative value if separation is negative).
Some examples:
(number-sequence 4 9)
Chapter 5: Lists 83
⇒ (4 5 6 7 8 9)
(number-sequence 9 4 -1)
⇒ (9 8 7 6 5 4)
(number-sequence 9 4 -2)
⇒ (9 7 5)
(number-sequence 8)
⇒ (8)
(number-sequence 8 5)
⇒ nil
(number-sequence 5 8 -1)
⇒ nil
(number-sequence 1.5 6 2)
⇒ (1.5 3.5 5.5)
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:
Chapter 5: Lists 86
Here is a graphical depiction of the shared structure of the two lists in the variables x1
and x2, showing why replacing b changes them both:
x1:
-------------- -------------- --------------
| car | cdr | | car | cdr | | car | cdr |
| a | o------->| b | o------->| c | nil |
| | | -->| | | | | |
-------------- | -------------- --------------
|
x2: |
-------------- |
| car | cdr | |
| z | o----
| | |
--------------
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 (list 1 2 3))
⇒ (1 2 3)
(setcdr x '(4))
⇒ (4)
x
⇒ (1 4)
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 (list '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 |
| | | | | | | | |
-------------- -------------- --------------
Chapter 5: Lists 88
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 (list '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------
| | |
---------------
(nconc x 'z)
⇒ (1 2 3 . z)
x
⇒ (1 2 3 . z)
However, the other arguments (all but the last) should be mutable lists.
(symbol-function 'add-foo)
⇒ (lambda (x) (nconc '(foo) x))
(symbol-function 'add-foo)
⇒ (lambda (x) (nconc '(foo 1 2 3 4) x))
Common Lisp note: Common Lisp has functions union (which avoids duplicate
elements) and intersection for set operations. In Emacs Lisp, variants of
these facilities are provided by the cl-lib library. See Section “Lists as Sets”
in Common Lisp Extensions.
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 87).
(setq sample-list (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 (list 4) that delq attempts to match and the (4) in the
sample-list are equal but not eq:
(delq (list 4) sample-list)
⇒ (a c (4))
If you want to delete elements that are equal to a given value, use delete (see below).
The following three functions are like memq, delq and remq, but use equal rather than
eq to compare elements. See Section 2.8 [Equality Predicates], page 33.
Both the values and the keys in an alist may be any Lisp objects. For example, in
the following alist, the symbol a is associated with the number 1, and the string "b" is
associated with the list (2 3), which is the cdr of the alist element:
((a . 1) ("b" 2 3))
Sometimes it is better to design an alist to store the associated value in the car of the
cdr of the element. Here is an example of such an alist:
((rose red) (lily white) (buttercup yellow))
Here we regard red as the value associated with rose. One advantage of this kind of alist
is that you can store other related information—even a list of other items—in the cdr of
the cdr. One disadvantage is that you cannot use rassq (see below) to find the element
containing a given value. When neither of these considerations is important, the choice is
a matter of taste, as long as you are consistent about it for any given alist.
The same alist shown above could be regarded as having the associated value in the cdr
of the element; the value associated with rose would be the list (red).
Association lists are often used to record information that you might otherwise keep on
a stack, since new associations may be added easily to the front of the list. When searching
an association list for an association with a given key, the first one found is returned, if
there is more than one.
In Emacs Lisp, it is not an error if an element of an association list is not a cons cell.
The alist search functions simply ignore such elements. Many other versions of Lisp signal
errors in such cases.
Note that property lists are similar to association lists in several respects. A property
list behaves like an association list in which each key can occur only once. See Section 5.9
[Property Lists], page 97, for a comparison of property lists and association lists.
assoc key alist &optional testfn [Function]
This function returns the first association for key in alist, comparing key against the
alist elements using testfn if it is a function, and equal otherwise (see Section 2.8
[Equality Predicates], page 33). If testfn is a function, it is called with two arguments:
the car of an element from alist and key. The function returns nil if no association
in alist has a car equal to key, as tested by testfn. For example:
(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
⇒ ((pine . cones) (oak . acorns) (maple . seeds))
(assoc 'oak trees)
⇒ (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 58.
rassoc value alist [Function]
This function returns the first association with value value in alist. It returns nil if
no association in alist has a cdr equal to value.
rassoc is like assoc except that it compares the cdr of each alist association instead
of the car. You can think of this as reverse assoc, finding the key for a given value.
assq key alist [Function]
This function is like assoc in that it returns the first association for key in alist, but
it makes the comparison using eq. assq returns nil if no association in alist has a
car eq to key. This function is used more often than assoc, since eq is faster than
equal and most alists use symbols as keys. See Section 2.8 [Equality Predicates],
page 33.
(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
⇒ ((pine . cones) (oak . acorns) (maple . seeds))
(assq 'pine trees)
⇒ (pine . cones)
On the other hand, assq is not usually useful in alists where the keys may not be
symbols:
(setq leaves
'(("simple leaves" . oak)
("compound leaves" . horsechestnut)))
(let-alist colors
(if (eq .rose 'red)
.lily.belladonna))
⇒ yellow
Nesting let-alist inside each other is allowed, but the code in the inner let-alist
can’t access the variables bound by the outer let-alist.
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
See also string-bytes, in Section 34.1 [Text Representations], page 900.
If you need to compute the width of a string on display, you should use string-width
(see Section 40.10 [Size of Displayed Text], page 1064), not length, since length only counts
the number of characters, but does not account for the display width of each character.
length< sequence length [Function]
Return non-nil if sequence is shorter than length. This may be more efficient than
computing the length of sequence if sequence is a long list.
length> sequence length [Function]
Return non-nil if sequence is longer than length.
length= sequence length [Function]
Return non-nil if the length of sequence is equal to length.
elt sequence index [Function]
This function returns the element of sequence indexed by index. Legitimate values
of index are integers ranging from 0 up to one less than the length of sequence. If
sequence is a list, out-of-range values behave as for nth. See [Definition of nth],
page 78. Otherwise, out-of-range values trigger an args-out-of-range error.
(elt [1 2 3 4] 2)
⇒ 3
(elt '(1 2 3 4) 2)
⇒ 3
;; We use string to show clearly which character elt returns.
(string (elt "1234" 2))
⇒ "3"
(elt [1 2 3 4] 4)
error Args out of range: [1 2 3 4], 4
(elt [1 2 3 4] -1)
error Args out of range: [1 2 3 4], -1
This function generalizes aref (see Section 6.3 [Array Functions], page 112) and nth
(see [Definition of nth], page 78).
copy-sequence seqr [Function]
This function returns a copy of seqr, which should be either a sequence or a record.
The copy is the same type of object as the original, and it has the same elements in
the same order. However, if seqr is empty, like a string or a vector of zero length, the
value returned by this function might not be a copy, but an empty object of the same
type and identical to seqr.
Chapter 6: Sequences, Arrays, and Vectors 101
Storing a new element into the copy does not affect the original seqr, and vice versa.
However, the elements of the copy are not copies; they are identical (eq) to the
elements of the original. Therefore, changes made within these elements, as found via
the copy, are also visible in the original.
If the argument is a string with text properties, the property list in the copy is itself
a copy, not shared with the original’s property list. However, the actual values of the
properties are shared. See Section 33.19 [Text Properties], page 858.
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 79, concat in Section 4.3 [Cre-
ating Strings], page 53, and vconcat in Section 6.5 [Vector Functions], page 114, for
other ways to copy sequences.
(setq bar (list 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
(setq x [1 2 3 4])
⇒ [1 2 3 4]
(reverse x)
⇒ [4 3 2 1]
x
⇒ [1 2 3 4]
(setq x "xyzzy")
⇒ "xyzzy"
(reverse x)
⇒ "yzzyx"
x
⇒ "xyzzy"
For the vector, it is even simpler because you don’t need setq:
(setq x (copy-sequence [1 2 3 4]))
⇒ [1 2 3 4]
(nreverse x)
⇒ [4 3 2 1]
x
⇒ [4 3 2 1]
Chapter 6: Sequences, Arrays, and Vectors 103
Note that unlike reverse, this function doesn’t work with strings. Although you can
alter string data by using aset, it is strongly encouraged to treat strings as immutable
even when they are mutable. See Section 2.9 [Mutability], page 36.
(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 33.15 [Sorting], page 847, for more functions that perform sorting. See
documentation in Section 25.2 [Accessing Documentation], page 552, for a useful
example of sort.
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 234, for more details about using cl-defgeneric
for adding extensions.
seq-elt sequence index [Function]
This function returns the element of sequence at the specified index, which is an
integer whose valid value range is zero to one less than the length of sequence. For
out-of-range values on built-in sequence types, seq-elt behaves like elt. For the
details, see [Definition of elt], page 100.
(seq-elt [1 2 3 4] 2)
⇒ 3
seq-elt returns places settable using setf (see Section 12.17.1 [Setting Generalized
Variables], page 217).
(setq vec [1 2 3 4])
(setf (seq-elt vec 2) 5)
vec
⇒ [1 2 5 4]
seq-length sequence [Function]
This function returns the number of elements in sequence. For built-in sequence types,
seq-length behaves like length. See [Definition of length], page 99.
seqp object [Function]
This function returns non-nil if object is a sequence (a list or array), or any additional
type of sequence defined via seq.el generic functions. This is an extensible variant
of sequencep.
(seqp [1 2])
⇒ t
Chapter 6: Sequences, Arrays, and Vectors 105
(seqp 2)
⇒ nil
(seq-intersection [2 3 4 5] [1 3 5 6 7])
⇒ (3 5)
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.4.8 [String
Type], page 19), vectors (see Section 2.4.9 [Vector Type], page 21), bool-vectors (see
Section 2.4.11 [Bool-Vector Type], page 22), and char-tables (see Section 2.4.10 [Char-
Table Type], page 22). 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 112).
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 33.19 [Text Properties], page 858.
• 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 52.
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 22.8.1 [Key Sequence Input], page 432.
(arrayp [a])
⇒ t
(arrayp "asdf")
⇒ t
(arrayp (syntax-table)) ;; A char-table.
⇒ t
aref arr index [Function]
This function returns the indexth element of the array or record arr. The first element
is at index zero.
(setq primes [2 3 5 7 11 13])
⇒ [2 3 5 7 11 13]
(aref primes 4)
⇒ 11
(aref "abcdefg" 1)
⇒ 98 ; ‘b’ is ASCII code 98.
See also the function elt, in Section 6.1 [Sequence Functions], page 99.
aset array index object [Function]
This function sets the indexth element of array to be object. It returns object.
(setq w (vector 'foo 'bar 'baz))
⇒ [foo bar baz]
(aset w 0 'fu)
⇒ fu
w
⇒ [fu bar baz]
The general sequence functions copy-sequence and length are often useful for objects
known to be arrays. See Section 6.1 [Sequence Functions], page 99.
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 52.) Vectors are used in Emacs for many purposes: as key sequences (see Section 23.1
[Key Sequences], page 451), as symbol-lookup tables (see Section 9.3 [Creating Symbols],
page 132), as part of the representation of a byte-compiled function (see Chapter 17 [Byte
Compilation], page 301), 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 142. Vectors written with square
brackets should not be modified via aset or other destructive operations. See Section 2.9
[Mutability], page 36.
Here are examples illustrating these principles:
(setq avector [1 two '(three) "four" [five]])
⇒ [1 two '(three) "four" [five]]
(eval avector)
⇒ [1 two '(three) "four" [five]]
(eq avector (eval avector))
⇒ t
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 '(three) "four" [five]]
(append avector nil)
⇒ (1 two '(three) "four" [five])
6.6 Char-Tables
A char-table is much like a vector, except that it is indexed by character codes. Any valid
character code, without modifiers, can be used as an index in a char-table. You can access
a char-table’s elements with aref and aset, as with any array. In addition, a char-table
can have extra slots to hold additional data not associated with particular character codes.
Like vectors, char-tables are constants when evaluated, and can hold elements of any type.
Chapter 6: Sequences, Arrays, and Vectors 116
A char-table can specify an element value for a single character code; it can also specify
a value for an entire character set.
value)
accumulator)))
(syntax-table))
accumulator)
⇒
(((2597602 4194303) (2)) ((2597523 2597601) (3))
... (65379 (5 . 65378)) (65378 (4 . 65379)) (65377 (1))
... (12 (0)) (11 (3)) (10 (12)) (9 (0)) ((0 8) (3)))
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.
There are also some bool-vector set operation functions, described below:
bool-vector-subsetp a b [Function]
Return t if every t value in a is also t in b, nil otherwise. All arguments should be
bool vectors of the same length.
bool-vector-count-consecutive a b i [Function]
Return the number of consecutive elements in a equal b starting at i. a is a bool
vector, b is t or nil, and i is an index into a.
bool-vector-count-population a [Function]
Return the number of elements that are t in bool vector a.
The newest element in the ring always has index 0. Higher indices correspond to older
elements. Indices are computed modulo the ring length. Index −1 corresponds to the oldest
element, −2 to the next-oldest, and so forth.
If you are careful not to exceed the ring size, you can use the ring as a first-in-first-out
queue. For example:
(let ((fifo (make-ring 5)))
(mapc (lambda (obj) (ring-insert fifo obj))
'(0 one "two"))
(list (ring-remove fifo) t
(ring-remove fifo) t
(ring-remove fifo)))
⇒ (0 t one t "two")
122
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.4.18 [Type Descriptors], page 24. 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 142.
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 92) 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 124. (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 132).
: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 126
You can also create a hash table using the printed representation for hash tables. The
Lisp reader can read this printed representation, provided each element in the specified
hash table has a valid read syntax (see Section 2.1 [Printed Representation], page 8). For
instance, the following specifies a hash table containing the keys key1 and key2 (both
symbols) associated with val1 (a symbol) and 300 (a number) respectively.
#s(hash-table size 30 data (key1 val1 key2 300))
Note, however, that when using this in Emacs Lisp code, it’s undefined whether this
creates a new hash table or not. If you want to create a new hash table, you should always
use make-hash-table (see Section 10.1.1 [Self-Evaluating Forms], page 142).
The printed representation for a hash table consists of ‘#s’ followed by a list beginning with
‘hash-table’. The rest of the list should consist of zero or more property-value pairs speci-
fying the hash table’s properties and initial contents. The properties and values are read lit-
erally. Valid property names are size, test, weakness, rehash-size, rehash-threshold,
and data. The data property should be a list of key-value pairs for the initial contents;
the other properties have the same meanings as the matching make-hash-table keywords
(:size, :test, etc.), described above.
Note that you cannot specify a hash table whose initial contents include objects that
have no read syntax, such as buffers and frames. Such objects may be added to the hash
table after it is created.
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 184, and Chapter 13 [Functions], page 221. For the precise read syntax for symbols,
see Section 2.4.4 [Symbol Type], page 14.
You can test whether an arbitrary Lisp object is a symbol with symbolp:
keymap (see Chapter 23 [Keymaps], page 451), or autoload object (see Section 10.1.8 [Au-
toloading], page 146). To get the contents of a symbol’s function cell, use the function
symbol-function (see Section 13.9 [Function Cells], page 238).
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 135.
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>
As previously noted, Emacs Lisp allows the same symbol to be defined both as a variable
(e.g., with defvar) and as a function or macro (e.g., with defun). Such definitions do not
conflict.
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.
value of a variable. Uninterned symbols are sometimes useful in generating Lisp code, see
below.
In Emacs Lisp, an obarray is actually a vector. Each element of the vector is a bucket;
its value is either an interned symbol whose name hashes to that bucket, or 0 if the bucket is
empty. Each interned symbol has an internal link (invisible to the user) to the next symbol
in the bucket. Because these links are invisible, there is no way to find all the symbols in an
obarray except using mapatoms (below). The order of symbols in a bucket is not significant.
In an empty obarray, every element is 0, so you can create an obarray with (make-vector
length 0). This is the only valid way to create an obarray. Prime numbers as lengths tend
to result in good hashing; lengths one less than a power of two are also good.
Do not try to put symbols in an obarray yourself. This does not work—only intern
can enter a symbol in an obarray properly.
Common Lisp note: Unlike Common Lisp, Emacs Lisp does not provide for
interning the same name in several different “packages”, thus creating multiple
symbols with the same name but different packages. Emacs Lisp provides a
different namespacing system called “shorthands” (see Section 9.5 [Shorthands],
page 138).
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!
Creating an uninterned symbol is useful in generating Lisp code, because an uninterned
symbol used as a variable in the code you generate cannot clash with any variables used in
other Lisp programs.
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
gensym &optional prefix [Function]
This function returns a symbol using make-symbol, whose name is made by appending
gensym-counter to prefix and incrementing that counter, guaranteeing that no two
calls to this function will generate a symbol with the same name. The prefix defaults
to "g".
Chapter 9: Symbols 134
(setq count 0)
⇒ 0
(defun count-syms (s)
(setq count (1+ count)))
⇒ count-syms
(mapatoms 'count-syms)
⇒ nil
count
⇒ 1871
See documentation in Section 25.2 [Accessing Documentation], page 552, for another
example using mapatoms.
char-table-extra-slots
The value, if non-nil, specifies the number of extra slots in the named char-
table type. See Section 6.6 [Char-Tables], page 115.
customized-face
face-defface-spec
saved-face
theme-face
These properties are used to record a face’s standard, saved, customized, and
themed face specs. Do not set them directly; they are managed by defface
and related functions. See Section 40.12.2 [Defining Faces], page 1073.
customized-value
saved-value
standard-value
theme-value
These properties are used to record a customizable variable’s standard value,
saved value, customized-but-unsaved value, and themed values. Do not set
them directly; they are managed by defcustom and related functions. See
Section 15.3 [Variable Definitions], page 267.
disabled If the value is non-nil, the named function is disabled as a command. See
Section 22.14 [Disabling Commands], page 448.
face-documentation
The value stores the documentation string of the named face. This is set auto-
matically by defface. See Section 40.12.2 [Defining Faces], page 1073.
history-length
The value, if non-nil, specifies the maximum minibuffer history length for the
named history list variable. See Section 21.4 [Minibuffer History], page 371.
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 22.3
[Interactive Call], page 410.
menu-enable
The value is an expression for determining whether the named menu item should
be enabled in menus. See Section 23.17.1.1 [Simple Menu Items], page 476.
mode-class
If the value is special, the named major mode is special. See Section 24.2.1
[Major Mode Conventions], page 494.
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 203.
Chapter 9: Symbols 138
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 24.1.2
[Setting Hooks], page 491.
pure If the value is non-nil, the named function is considered to be pure (see
Section 13.1 [What Is a Function], page 221). 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 1244).
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 208.
safe-function
If the value is non-nil, the named function is considered generally safe for
evaluation. See Section 13.16 [Function Safety], page 253.
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 208.
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 208.
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 221), 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 253).
undo-inhibit-region
If non-nil, the named function prevents the undo operation from being re-
stricted to the active region, if undo is invoked immediately after the function.
See Section 33.9 [Undo], page 837.
variable-documentation
If non-nil, this specifies the named variable’s documentation string. This is set
automatically by defvar and related functions. See Section 40.12.2 [Defining
Faces], page 1073.
9.5 Shorthands
The symbol shorthands, sometimes known as “renamed symbols”, are symbolic forms found
in Lisp source. They’re just like regular symbolic forms, except that when the Lisp reader
encounters them, it produces symbols which have a different and usually longer print name
(see Section 9.1 [Symbol Components], page 130).
Chapter 9: Symbols 139
;; Local Variables:
;; read-symbol-shorthands: (("snu-" . "some-nice-string-utils-"))
;; End:
Even though the two excerpts look different, they are quite identical after the Lisp reader
processes them. Both will lead to the very same symbols being interned (see Section 9.3
[Creating Symbols], page 132). Thus loading or byte-compiling any of the two files has
equivalent results. The shorthands snu-split and snu-lines used in the second version
are not interned in the obarray. This is easily seen by moving point to the location where
the shorthands are used and waiting for ElDoc (see Section “Local Variables in Files” in
Chapter 9: Symbols 140
The GNU Emacs Manual) to hint at the true full name of the symbol under point in the
echo area.
Since read-symbol-shorthands is a file-local variable, it is possible that multiple li-
braries depending on some-nice-string-utils-lines.el refer to the same symbols under
different shorthands, or not using shorthands at all. In the next example, the my-tricks.el
library refers to the symbol some-nice-string-utils-lines using the sns- prefix instead
of snu-.
(defun t-reverse-lines (s) (string-join (reverse (sns-lines s)) "\n")
;; Local Variables:
;; read-symbol-shorthands: (("t-" . "my-tricks-")
;; ("sns-" . "some-nice-string-utils-"))
;; End:
9.5.1 Exceptions
There are two exceptions to rules governing Shorthand transformations:
• Symbol forms comprised entirely of characters in the Emacs Lisp symbol constituent
class (see Section 36.2.1 [Syntax Class Table], page 959) are not transformed. For
example, it’s possible to use - or /= as shorthand prefixes, but that won’t shadow the
arithmetic functions of those names.
• Symbol forms whose names start with ‘#_’ are not transformed.
141
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 20.3 [Input Functions], page 355.
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 221, 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 184).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 185).
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 22 [Command
Loop], page 401.
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 142
(eval 'a)
⇒ 123
a
⇒ 123
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 184.
condition-case
see Section 11.7.3.3 [Handling Errors], page 177,
defconst see Section 12.5 [Defining Variables], page 189,
defvar see Section 12.5 [Defining Variables], page 189,
function see Section 13.7 [Anonymous Functions], page 233,
if see Section 11.2 [Conditionals], page 155,
interactive
see Section 22.3 [Interactive Call], page 410,
lambda see Section 13.2 [Lambda Expressions], page 223,
let
let* see Section 12.3 [Local Variables], page 185,
or see Section 11.3 [Combining Conditions], page 157,
prog1
prog2
progn see Section 11.1 [Sequencing], page 154,
quote see Section 10.2 [Quoting], page 147,
save-current-buffer
see Section 28.2 [Current Buffer], page 626,
save-excursion
see Section 31.3 [Excursions], page 807,
save-restriction
see Section 31.4 [Narrowing], page 808,
setq see Section 12.8 [Setting Variables], page 193,
setq-default
see Section 12.11.2 [Creating Buffer-Local], page 203,
unwind-protect
see Section 11.7 [Nonlocal Exits], page 172,
while see Section 11.5 [Iteration], page 169,
Common Lisp note: Here are some comparisons of special forms in GNU Emacs
Lisp and Common Lisp. setq, if, and catch are special forms in both Emacs
Lisp and Common Lisp. save-excursion is a special form in Emacs Lisp,
but doesn’t exist in Common Lisp. throw is a special form in Common Lisp
(because it must be able to throw multiple values), but it is a function in Emacs
Lisp (which doesn’t have multiple values).
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
Chapter 10: Evaluation 147
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 290.
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
⇒ 'foo
'(quote foo)
⇒ 'foo
['foo]
⇒ ['foo]
Although the expressions (list '+ 1 2) and '(+ 1 2) both yield lists equal to (+ 1 2),
the former yields a freshly-minted mutable list whereas the latter yields a list built from
conses that might be shared and should not be modified. See Section 10.1.1 [Self-Evaluating
Forms], page 142.
Other quoting constructs include function (see Section 13.7 [Anonymous Functions],
page 233), which causes an anonymous lambda expression written in Lisp to be compiled,
and ‘`’ (see Section 10.3 [Backquote], page 147), 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:
Chapter 10: Evaluation 148
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.
Chapter 10: Evaluation 149
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 284).
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.
Programs Do Loading], page 286) to specify this function, but it is more robust to
use the read-function argument.
eval-region does not move point. It always returns nil.
eval-buffer &optional buffer-or-name stream filename unibyte [Command]
print
This is similar to eval-region, but the arguments provide different optional features.
eval-buffer operates on the entire accessible portion of buffer buffer-or-name (see
Section “Narrowing” in The GNU Emacs Manual). buffer-or-name can be a buffer,
a buffer name (a string), or nil (or omitted), which means to use the current buffer.
stream is used as in eval-region, unless stream is nil and print non-nil. In that
case, values that result from evaluating the expressions are still discarded, but the
output of the output functions is printed in the echo area. filename is the file name
to use for load-history (see Section 16.9 [Unloading], page 298), and defaults to
buffer-file-name (see Section 28.4 [Buffer File Name], page 630). If unibyte is
non-nil, read converts strings to unibyte whenever possible.
eval-current-buffer is an alias for this command.
max-lisp-eval-depth [User Option]
This variable defines the maximum depth allowed in calls to eval, apply, and funcall
before an error is signaled (with error message "Lisp nesting exceeds max-lisp-
eval-depth").
This limit, with the associated error when it is exceeded, is one way Emacs Lisp avoids
infinite recursion on an ill-defined function. If you increase the value of max-lisp-
eval-depth too much, such code can cause stack overflow instead. On some systems,
this overflow can be handled. In that case, normal Lisp evaluation is interrupted and
control is transferred back to the top level command loop (top-level). Note that
there is no way to enter Emacs Lisp debugger in this situation. See Section 19.1.1
[Error Debugging], page 316.
The depth limit counts internal uses of eval, apply, and funcall, such as for calling
the functions mentioned in Lisp expressions, and recursive evaluation of function call
arguments and function body forms, as well as explicit calls in Lisp code.
The default value of this variable is 800. If you set it to a value less than 100, Lisp
will reset it to 100 if the given value is reached. Entry to the Lisp debugger increases
the value, if there is little room left, to make sure the debugger itself has room to
execute.
max-specpdl-size provides another limit on nesting. See [Local Variables], page 188.
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.)
This variable is obsolete, and will be removed in a future version, since it constantly
enlarges the memory footprint of the Emacs process. For that reason, we recommend
against using it.
Chapter 10: Evaluation 151
Example:
(defun f (number)
(thunk-let ((derived-number
(progn (message "Calculating 1 plus 2 times %d" number)
(1+ (* 2 number)))))
(if (> number 10)
derived-number
number)))
(f 5)
⇒ 5
(f 12)
a Calculating 1 plus 2 times 12
⇒ 25
Because of the special nature of lazily bound variables, it is an error to set them (e.g.
with setq).
a Calculating z...
a Calculating y...
a Calculating x...
a Finished calculating x
a Finished calculating y
a Finished calculating z
⇒ 8
thunk-let and thunk-let* use thunks implicitly: their expansion creates helper sym-
bols and binds them to thunks wrapping the binding expressions. All references to the orig-
Chapter 10: Evaluation 153
inal variables in the body forms are then replaced by an expression that calls thunk-force
with the according helper variable as the argument. So, any code using thunk-let or
thunk-let* could be rewritten to use thunks, but in many cases using these macros results
in nicer code than using thunks explicitly.
154
11 Control Structures
A Lisp program consists of a set of expressions, or forms (see Section 10.1 [Forms], page 142).
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 255).
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 158).
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 154.)
Chapter 11: Control Structures 156
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 157
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))))
in Common Lisp Extensions) that overcomes their limitations and introduces the pattern
matching programming style. The limitations that pcase overcomes are:
• The cond form chooses among alternatives by evaluating the predicate condition of
each of its clauses (see Section 11.2 [Conditionals], page 155). The primary limitation
is that variables let-bound in condition are not available to the clause’s body-forms.
Another annoyance (more an inconvenience than a limitation) is that when a series of
condition predicates implement equality tests, there is a lot of repeated code. (cl-case
solves this inconvenience.)
• 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”).
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 196).
If symbol is part of a sequencing pattern seqpat (e.g., by using and, below),
the binding is also available to the portion of seqpat following the appearance
of symbol. This usage has some caveats, see [caveats], page 163.
Two symbols to avoid are t, which behaves like _ (above) and is deprecated,
and nil, which signals an error. Likewise, it makes no sense to bind keyword
symbols (see Section 12.2 [Constant Variables], page 184).
(cl-type type)
Matches if expval is of type type, which is a type descriptor as accepted by
cl-typep (see Section “Type Predicates” in Common Lisp Extensions). Ex-
amples:
(cl-type integer)
(cl-type (integer 0 10))
(pred function)
Matches if the predicate function returns non-nil when called on expval. The
test can be negated with the syntax (pred (not function)). The predicate
function can have one of the following forms:
function name (a symbol)
Call the named function with one argument, expval.
Example: integerp
lambda expression
Call the anonymous function with one argument, expval (see
Section 13.2 [Lambda Expressions], page 223).
Example: (lambda (n) (= 42 n))
function call with n args
Call the function (the first element of the function call) with n
arguments (the other elements) and an additional n+1-th argument
that is expval.
Example: (= 42)
In this example, the function is =, n is one, and the actual function
call becomes: (= 42 expval).
(app function pattern)
Matches if function called on expval returns a value that matches pattern.
function can take one of the forms described for pred, above. Unlike pred,
however, app tests the result against pattern, rather than against a boolean
truth value.
Chapter 11: Control Structures 161
(guard boolean-expression)
Matches if boolean-expression evaluates to non-nil.
(let pattern expr)
Evaluates expr to get exprval and matches if exprval matches pattern. (It is
called let because pattern can bind symbols to values using symbol.)
A sequencing pattern (also known as seqpat) is a pattern that processes its sub-pattern
arguments in sequence. There are two for pcase: and and or. They behave in a similar
manner to the special forms that share their name (see Section 11.3 [Combining Conditions],
page 157), but instead of processing values, they process sub-patterns.
(and pattern1...)
Attempts to match pattern1 . . . , in order, until one of them fails to match. In
that case, and likewise fails to match, and the rest of the sub-patterns are not
tested. If all sub-patterns match, and matches.
(or pattern1 pattern2...)
Attempts to match pattern1, pattern2, . . . , in order, until one of them succeeds.
In that case, or likewise matches, and the rest of the sub-patterns are not tested.
To present a consistent environment to body-forms (thus avoiding an evaluation
error on match), the set of variables bound by the pattern is the union of the
variables bound by each sub-pattern. If a variable is not bound by the sub-
pattern that matched, then it is bound to nil.
(and
(pred integerp)
n ; bind n to expval
(guard (<= -9 n 9)))
First, pred matches if (integerp expval) evaluates to non-nil. Next, n is a symbol
pattern that matches anything and binds n to expval. Lastly, guard matches if the boolean
expression (<= -9 n 9) (note the reference to n) evaluates to non-nil. If all these sub-
patterns match, and matches.
The next pred (lines 4-5) evaluates (string-match RX expval) and matches if the result
is non-nil, which means that expval has the desired form: key:NUMBER. Again, failing this,
pred fails and and, too.
Lastly (in this series of and sub-patterns), app evaluates (match-string 1 expval) (line
6) to get a temporary value tmp (i.e., the “NUMBER” substring) and tries to match tmp
against pattern val (line 7). Since that is a symbol pattern, it matches unconditionally and
additionally binds val to tmp.
Now that app has matched, all and sub-patterns have matched, and so and matches.
Likewise, once and has matched, or matches and does not proceed to try sub-pattern let
(line 8).
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 221).
patterns let-binds. This makes sense because, for and to match, all the sub-patterns
must match.
When seqpat is or, things are different: or matches at the first sub-pattern that
matches; the rest of the sub-patterns are ignored. It makes no sense for each sub-
pattern to let-bind a different set of symbols because the body forms have no way
to distinguish which sub-pattern matched and choose among the different sets. For
example, the following is invalid:
(require 'cl-lib)
(pcase (read-number "Enter an integer: ")
((or (and (pred cl-evenp)
e-num) ; bind e-num to expval
o-num) ; bind o-num to expval
(list e-num o-num)))
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:
(require 'cl-lib)
(pcase (read-number "Enter an integer: ")
((and num ; line 1
(or (and (pred cl-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).
Typically, body rewrites the invoked pattern to use more basic patterns. Although all
patterns eventually reduce to core patterns, body need not use core patterns straight away.
The following example defines two patterns, named less-than and integer-less-than.
(pcase-defmacro less-than (n)
"Matches if EXPVAL is a number less than N."
`(pred (> ,n)))
(qpat1 . qpat2)
Matches if expval is a cons cell whose car matches qpat1 and whose cdr matches
qpat2. This readily generalizes to lists as in (qpat1 qpat2 ...).
[qpat1 qpat2 ... qpatm]
Matches if expval is a vector of length m whose 0..(m-1)th elements match
qpat1, qpat2 . . . qpatm, respectively.
symbol
keyword
number
string Matches if the corresponding element of expval is equal to the specified literal
object.
,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 198):
(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
Chapter 11: Control Structures 168
bindings is a list of bindings of the form (pattern exp), where exp is an expression
to evaluate and pattern is a pcase pattern. The variable bindings are produced
by destructuring binding of elements of pattern to the values of the corresponding
elements of the evaluated exp.
Unlike pcase-let, but similarly to let*, each exp is matched against its correspond-
ing pattern before processing the next element of bindings, so the variable bindings
introduced in each one of the bindings are available in the exps of the bindings that
follow it, additionally to being available in body.
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:
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
This moves forward one line and continues moving by lines until it reaches an empty
line. It is peculiar in that the while has no body, just the end test (which also does
the real work of moving point).
The dolist and dotimes macros provide convenient ways to write two common kinds
of loops.
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.
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
Chapter 11: Control Structures 172
-1)
(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).
Chapter 11: Control Structures 173
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 185). Likewise, throw restores the buffer and position saved by
save-excursion (see Section 31.3 [Excursions], page 807), 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 182).
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 22.13 [Recursive Editing],
page 446).
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.
(defun search-foo ()
(catch 'loop
(let ((i 0))
(while (< i 10)
(let ((j 0))
(while (< j 10)
(if (foo i j)
(throw 'loop (list i j)))
(setq j (1+ j))))
(setq i (1+ i))))))
If foo ever returns non-nil, we stop immediately and return a list of i and j. If foo always
returns nil, the catch returns normally, and the value is nil, since that is the result of the
while.
Here are two tricky examples, slightly different, showing two return points at once. First,
two return points with the same tag, hack:
(defun catch2 (tag)
(catch tag
(throw 'hack 'yes)))
⇒ catch2
(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.
Chapter 11: Control Structures 175
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 182.) 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 172.
Common Lisp note: Emacs Lisp has nothing like the Common Lisp concept of
continuable errors.
If there is no applicable handler for the error, it terminates the current command and
returns control to the editor command loop. (The command loop has an implicit handler
for all kinds of errors.) The command loop’s handler uses the error symbol and associated
data to print an error message. You can use the variable command-error-function to
control how this is done:
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 19.1.1 [Error Debugging], page 316) 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.
If an error is handled by some condition-case form, this ordinarily prevents the de-
bugger from being run, even if debug-on-error says this error should invoke the debugger.
If you want to be able to debug errors that are caught by a condition-case, set the
variable debug-on-signal to a non-nil value. You can also specify that a particular
handler should let the debugger run first, by writing debug among the conditions, like this:
(condition-case nil
(delete-file filename)
((debug error) nil))
The effect of debug here is only to prevent condition-case from suppressing the call to the
debugger. Any given error will invoke the debugger only if debug-on-error and the other
usual filtering mechanisms say it should. See Section 19.1.1 [Error Debugging], page 316.
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 172), 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).
Each of the handlers is a list of the form (conditions body...). Here conditions
is an error condition name to be handled, or a list of condition names (which can
include debug to allow the debugger to run before the handler). A condition name of
t matches any condition. body is one or more Lisp expressions to be executed when
this handler handles an error. Here are examples of handlers:
Chapter 11: Control Structures 179
(error nil)
((arith-error file-error)
(message
"Either division by zero or failure to open a file"))
Each error that occurs has an error symbol that describes what kind of error it
is, and which describes also a list of condition names (see Section 11.7.3.4 [Error
Symbols], page 181). Emacs searches all the active condition-case forms for a
handler that specifies one or more of these condition names; the innermost matching
condition-case handles the error. Within this condition-case, the first applicable
handler handles the error.
After executing the body of the handler, the condition-case returns normally, using
the value of the last form in the handler body as the overall value.
The argument var is a variable. condition-case does not bind this variable when
executing the protected-form, only when it handles an error. At that time, it binds
var locally to an error description, which is a list giving the particulars of the error.
The error description has the form (error-symbol . data). The handler can refer to
this list to decide what to do. For example, if the error is for failure opening a file, the
file name is the second element of data—the third element of the error description.
If var is nil, that means no variable is bound. Then the error symbol and associated
data are not available to the handler.
As a special case, one of the handlers can be a list of the form (:success body...),
where body is executed with var (if non-nil) bound to the return value of protected-
form when that expression terminates without error.
Sometimes it is necessary to re-throw a signal caught by condition-case, for some
outer-level handler to catch. Here’s how to do that:
(signal (car err) (cdr err))
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 176.
Here is an example of using condition-case to handle the error that results from
dividing by zero. The handler displays the error message (but without a beep), then returns
a very large number.
(defun safe-divide (dividend divisor)
(condition-case err
;; Protected form.
(/ dividend divisor)
Chapter 11: Control Structures 180
;; The handler.
(arith-error ; Condition.
;; Display the usual message for this error.
(message "%s" (error-message-string err))
1000000)))
⇒ safe-divide
(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:
(setq baz 34)
⇒ 34
(condition-case err
(if (eq baz 35)
t
;; This is a call to the function error.
(error "Rats! The variable %s was %s, not 35" 'baz baz))
;; This is the handler; it is not a form.
(error (princ (format "The error was: %s" err))
2))
a The error was: (error "Rats! The variable baz was 34, not 35")
⇒ 2
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 176.
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 176) 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:
Chapter 11: Control Structures 182
(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 1286, for a list of the main error symbols and
their conditions.
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 628). 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 39 [Processes], page 987) 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.
184
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 130). 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 130. 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 189). 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 195.
The special forms let and let* exist to create local bindings:
(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* ((y 1)
(z y)) ; Use the just-established value of y.
(list y z))
⇒ (1 1)
This is only useful when lexical binding is in effect, and you want to create closures
that refer to bindings that would otherwise not yet be in effect when using let*.
For instance, here’s a closure that removes itself from a hook after being run once:
(letrec ((hookfun (lambda ()
(message "Run once")
(remove-hook 'post-command-hook hookfun))))
(add-hook 'post-command-hook hookfun))
Here is a complete list of the other facilities that create local bindings:
• Function calls (see Chapter 13 [Functions], page 221).
• Macro calls (see Chapter 14 [Macros], page 255).
• condition-case (see Section 11.7.3 [Errors], page 174).
Variables can also have buffer-local bindings (see Section 12.11 [Buffer-Local Variables],
page 201); a few variables have terminal-local bindings (see Section 30.2 [Multiple Termi-
Chapter 12: Variables 188
nals], page 738). These kinds of bindings work somewhat like ordinary local bindings, but
they are localized depending on where you are in Emacs.
If value is specified, and symbol is void (i.e., it has no dynamically bound value; see
Section 12.4 [Void Variables], page 188), 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 306.
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 201.
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 195.
When you evaluate a top-level defvar form with C-M-x (eval-defun) or with C-x
C-e (eval-last-sexp) in Emacs Lisp mode, a special feature of these two commands
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 25
[Documentation], page 551.
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 200.
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 195).
In addition, it marks the variable as risky (see Section 12.12 [File Local Variables],
page 208).
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 191
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 208.
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 193
(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 85) 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 195).
Each local binding has a certain scope and extent. Scope refers to where in the textual
source code the binding can be accessed. Extent refers to when, as the program is executing,
the binding exists.
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.
(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 197
(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 130. 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.
Note that when code using Dynamic Binding is native compiled the native compiler will
not perform any Lisp specific optimization.
(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 208). 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 148.
Chapter 12: Variables 200
Lexical binding is also enabled in Lisp Interaction and IELM mode, used in
the *scratch* and *ielm* buffers, and also when evaluating expressions via M-:
(eval-expression) and when processing the --eval command-line options of Emacs (see
Section “Action Arguments” in The GNU Emacs Manual) and emacsclient (see Section
“emacsclient Options” in The GNU Emacs Manual).
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 189). 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)
to a free variable. If a non-special variable is bound but not used within a let form, the
byte-compiler will warn about an unused lexical variable. The byte-compiler will also issue
a warning if you use a special variable as a function argument.
A warning about a reference or an assignment to a free variable is usually a clear sign that
that variable should be marked as dynamically scoped, so you need to add an appropriate
defvar before the first use of that variable.
A warning about an unused variable may be a good hint that the variable was intended
to be dynamically scoped (because it is actually used, but in another function), but it
may also be an indication that the variable is simply really not used and could simply be
removed. So you need to find out which case it is, and based on that, either add a defvar or
remove the variable altogether. If removal is not possible or not desirable (typically because
it is a formal argument and that we cannot or don’t want to change all the callers), you
can also add a leading underscore to the variable’s name to indicate to the compiler that
this is a variable known not to be used.)
Here is an example illustrating how this could be done, assuming that a Unix shell and
make are used for byte-compilation:
$ rm *.elc # force recompilation
$ EMACS_GENERATE_DYNVARS=1 make # generate .dynvars
$ cat *.dynvars > ~/my-dynvars # combine .dynvars
$ rm *.elc # force recompilation
$ EMACS_DYNVARS_FILE=~/my-dynvars make # perform checks
(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 30.2 [Multiple Termi-
nals], page 738).
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 24.1.2 [Setting Hooks], page 491).
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 24.1 [Hooks],
page 490.
A variable can be let-bound (see Section 12.3 [Local Variables], page 185) 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.
before-hack-local-variables-hook [Variable]
Emacs calls this hook immediately before applying file-local variables stored in
file-local-variables-alist.
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 267). 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 290) 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.
ignored-local-variable-values [User Option]
If there are some values of particular local variables that you always want to ignore
completely, you can use this variable. Its value has the same form as safe-local-
variable-values; a file-local variable setting to the value that appears in the list will
always be ignored when processing the local variables specified by the file. As with
that variable, when Emacs queries the user about whether to obey file-local variables,
the user can choose to ignore their particular values permanently, and that will alter
this variable and save it to the user’s custom file. Variable-value pairs that appear in
this variable take precedence over the same pairs in safe-local-variable-values.
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.
Chapter 12: Variables 211
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 267). 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.
risky-local-variable-p sym [Function]
This function returns non-nil if sym is a risky variable, based on the above criteria.
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.
enable-local-eval [User Option]
This variable controls processing of ‘Eval:’ in ‘-*-’ lines or local variables lists in files
being visited. A value of t means process them unconditionally; nil means ignore
them; anything else means ask the user what to do for each file. The default value is
maybe.
safe-local-eval-forms [User Option]
This variable holds a list of expressions that are safe to evaluate when found in the
‘Eval:’ “variable” in a file local variables list.
If the expression is a function call and the function has a safe-local-eval-function
property, the property value determines whether the expression is safe to evaluate. The
property value can be a predicate to call to test the expression, a list of such predicates (it’s
safe if any predicate succeeds), or t (always safe provided the arguments are constant).
Text properties are also potential loopholes, since their values could include functions to
call. So Emacs discards all text properties from string values specified for file-local variables.
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 in
addition to .dir-locals.el. This is useful when .dir-locals.el is under version
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.
3
The MS-DOS version of Emacs uses _dir-locals.el instead, due to limitations of the DOS filesystems.
Chapter 12: Variables 213
(connection-local-set-profile-variables
'remote-ksh
'((shell-file-name . "/bin/ksh")
(shell-command-switch . "-c")
(shell-interactive-switch . "-i")
(shell-login-switch . "-l")))
Chapter 12: Variables 214
(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.
connection-local-set-profiles criteria &rest profiles [Function]
This function assigns profiles, which are symbols, to all remote connections identified
by criteria. criteria is a plist identifying a connection and the application using
this connection. Property names might be :application, :protocol, :user and
: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.
hack-connection-local-variables criteria [Function]
This function collects applicable connection-local variables associated with criteria in
connection-local-variables-alist, without applying them. Example:
(hack-connection-local-variables
'(:application 'tramp :protocol "ssh" :machine "localhost"))
Chapter 12: Variables 215
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"))
(connection-local-set-profiles
'(:application 'tramp :protocol "ssh" :machine "remotehost")
'remote-perl)
enable-connection-local-variables [Variable]
If nil, connection-local variables are ignored. This variable shall be changed tem-
porarily only in special modes.
⇒ 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
as (setcar a b), but without you having to use two separate functions for setting and
accessing this type of place.
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
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 83) and pop (see Section 5.3
[List Elements], page 76) 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.
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 226.
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 22.2 [Defining Commands], page 402, 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 226
⇒ 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 250). interactive, if present, should be an interactive form specifying how the
function is to be called interactively (see Section 22.3 [Interactive Call], page 410).
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 298).
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 238.
Chapter 13: Functions 229
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 248.
To undefine a function name, use fmakunbound. See Section 13.9 [Function Cells],
page 238.
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:
1
This is related to, but different from currying, which transforms a function that takes multiple arguments
in such a way that it can be called as a chain of functions, each one with a single argument.
Chapter 13: Functions 231
the call. If func accepts n arguments, then a call to apply-partially with m <= n
arguments will produce a new function of n - m arguments2 .
Here’s how we could define the built-in function 1+, if it didn’t exist, using
apply-partially and +, another built-in function3 :
(defalias '1+ (apply-partially '+ 1)
"Increment argument by one.")
(1+ 10)
⇒ 11
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 22.3 [Interactive
Call], page 410.
2
If the number of arguments that func can accept is unlimited, then the new function will also accept
an unlimited number of arguments, so in that case apply-partially doesn’t reduce the number of
arguments that the new function could accept.
3
Note that unlike the built-in function, this version accepts any number of arguments.
Chapter 13: Functions 232
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)))
#'(lambda (x) (* x x))
In the following example, we define a change-property function that takes a func-
tion as its third argument, followed by a double-property function that makes use of
change-property by passing it an anonymous function:
(defun change-property (symbol prop function)
(let ((value (get symbol prop)))
(put symbol prop (funcall function value))))
(declare declarations)
A declare form, as described in Section 13.14 [Declare Form], page 250.
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
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.
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.
13.10 Closures
As explained in Section 12.10 [Variable Scoping], page 195, 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 233), 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
Chapter 13: Functions 240
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 198, 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.
the original function. When you’re done with it, you can revert to the untraced behavior
with:
(remove-function (process-filter proc) #'my-tracing-function)
Similarly, if you want to trace the execution of the function named display-buffer,
you could use:
(defun his-tracing-function (orig-fun &rest args)
(message "display-buffer called with args %S" args)
(let ((res (apply orig-fun args)))
(message "display-buffer returned %S" res)
res))
−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 (i.e., a lambda expression or an fbound symbol rather than an
expression or a string), then the interactive spec of the combined function will be a
call to that function with the interactive spec of the original function as sole argument.
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.
developers about adding a suitable hook. Especially, Emacs’s own source files should not
put advice on functions in Emacs. (There are currently a few exceptions to this convention,
but we aim to correct them.) It is generally cleaner to create a new hook in foo, and make
bar use the hook, than to have bar put advice in foo.
Special forms (see Section 10.1.7 [Special Forms], page 145) cannot be advised, however
macros can be advised, in much the same way as functions. Of course, this will not affect
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 221), 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.
define-advice symbol (where lambda-list &optional name depth) [Macro]
&rest body
This macro defines a piece of advice and adds it to the function named symbol. The
advice is an anonymous function if name is nil or a function named symbol@name.
See advice-add for explanation of other arguments.
advice-add symbol where function &optional props [Function]
Add the advice function to the named function symbol. where and props have the
same meaning as for add-function (see Section 13.11.1 [Core Advising Primitives],
page 241).
advice-remove symbol function [Function]
Remove the advice function from the named function symbol. function can also be
the name of a piece of advice.
advice-member-p function symbol [Function]
Return non-nil if the advice function is already in the named function symbol. func-
tion can also be the name of a piece of advice.
advice-mapc function symbol [Function]
Call function for every piece of advice that was added to the named function symbol.
function is called with two arguments: the advice function and its properties.
:after Call function after the old function. Both functions receive the same arguments,
and the return value of the composition is the return value of the old function.
More specifically, the composition of the two functions behaves like:
(lambda (&rest r) (prog1 (apply oldfun r) (apply function r)))
(add-function :after funvar function) is comparable for single-function
hooks to (add-hook 'hookvar function 'append) for normal hooks.
:override
This completely replaces the old function with the new one. The old function
can of course be recovered if you later call remove-function.
:around Call function instead of the old function, but provide the old function as an extra
argument to function. This is the most flexible composition. For example, it
lets you call the old function with different arguments, or many times, or within
a let-binding, or you can sometimes delegate the work to the old function and
sometimes override it completely. More specifically, the composition of the two
functions behaves like:
(lambda (&rest r) (apply function oldfun r))
:before-while
Call function before the old function and don’t call the old function if function
returns nil. Both functions receive the same arguments, and the return value
of the composition is the return value of the old function. More specifically, the
composition of the two functions behaves like:
(lambda (&rest r) (and (apply function r) (apply oldfun r)))
(add-function :before-while funvar function) is comparable for single-
function hooks to (add-hook 'hookvar function) when hookvar is run via
run-hook-with-args-until-failure.
:before-until
Call function before the old function and only call the old function if function
returns nil. More specifically, the composition of the two functions behaves
like:
(lambda (&rest r) (or (apply function r) (apply oldfun r)))
(add-function :before-until funvar function) is comparable for single-
function hooks to (add-hook 'hookvar function) when hookvar is run via
run-hook-with-args-until-success.
:after-while
Call function after the old function and only if the old function returned non-
nil. Both functions receive the same arguments, and the return value of the
composition is the return value of function. More specifically, the composition
of the two functions behaves like:
(lambda (&rest r) (and (apply oldfun r) (apply function r)))
(add-function :after-while funvar function) is comparable for
single-function hooks to (add-hook 'hookvar function 'append) when
hookvar is run via run-hook-with-args-until-failure.
Chapter 13: Functions 246
:after-until
Call function after the old function and only if the old function returned nil.
More specifically, the composition of the two functions behaves like:
(lambda (&rest r) (or (apply oldfun r) (apply function r)))
(add-function :after-until funvar function) is comparable for
single-function hooks to (add-hook 'hookvar function 'append) when
hookvar is run via run-hook-with-args-until-success.
:filter-args
Call function first and use the result (which should be a list) as the new argu-
ments to pass to the old function. More specifically, the composition of the two
functions behaves like:
(lambda (&rest r) (apply oldfun (funcall function r)))
:filter-return
Call the old function first and pass the result to function. More specifically, the
composition of the two functions behaves like:
(lambda (&rest r) (funcall function (apply oldfun r)))
end with a period. It can also be nil, in which case the warning message provides no
additional details.
The argument when should be a string indicating when the function was first made
obsolete—for example, a date or a release number.
In addition, you can mark a particular calling convention for a function as obsolete:
Making a function inline often makes its function calls run faster. But it also has
disadvantages. For one thing, it reduces flexibility; if you change the definition of the
function, calls already inlined still use the old definition until you recompile them.
Another disadvantage is that making a large function inline can increase the size of
compiled code both in files and in memory. Since the speed advantage of inline functions
is greatest for small functions, you generally should not make large functions inline.
Chapter 13: Functions 249
Also, inline functions do not behave well with respect to debugging, tracing, and ad-
vising (see Section 13.11 [Advising Functions], page 240). Since ease of debugging and the
flexibility of redefining functions are important features of Emacs, you should not make a
function inline, even if it’s small, unless its speed is really crucial, and you’ve timed the
code to verify that using defun actually has performance problems.
After an inline function is defined, its inline expansion can be performed later on in the
same file, just like macros.
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 255). 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.
Alternatively, you can define a function by providing the code which will inline it as a
compiler macro. The following macros make this possible.
define-inline name args [doc] [declare] body. . . [Macro]
Define a function name by providing code that does its inlining, as a compiler macro.
The function will accept the argument list args and will have the specified body.
If present, doc should be the function’s documentation string (see Section 13.2.4
[Function Documentation], page 226); declare, if present, should be a declare form
(see Section 13.14 [Declare Form], page 250) specifying the function’s metadata.
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 231).
− They are more efficient.
− They can be used as place forms to store values (see Section 12.17 [Generalized Vari-
ables], page 217).
− 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 195.
The following macros should be used in the body of a function defined by define-inline.
inline-quote expression [Macro]
Quote expression for define-inline. This is similar to the backquote (see
Section 10.3 [Backquote], page 147), but quotes code and accepts only ,, not ,@.
inline-letevals (bindings. . . ) body. . . [Macro]
This provides a convenient way to ensure that the arguments to an inlined function
are evaluated exactly once, as well as to create local variables.
It’s similar to let (see Section 12.3 [Local Variables], page 185): It sets up local
variables as specified by bindings, and then evaluates body with those bindings in
effect.
Chapter 13: Functions 250
Each element of bindings should be either a symbol or a list of the form (var expr);
the result is to evaluate expr and bind var to the result. However, when an element
of bindings is just a symbol var, the result of evaluating var is re-bound to var (which
is quite different from the way let works).
The tail of bindings can be either nil or a symbol which should hold a list of ar-
guments, in which case each argument is evaluated, and the symbol is bound to the
resulting list.
(debug edebug-form-spec)
This is valid for macros only. When stepping through the macro with Ede-
bug, use edebug-form-spec. See Section 19.2.15.1 [Instrumenting Macro
Calls], page 340.
(doc-string n)
This is used when defining a function or macro which itself will be used
to define entities like functions, macros, or variables. It indicates that the
nth argument, if any, should be considered as a documentation string.
(indent indent-spec)
Indent calls to this function or macro according to indent-spec. This
is typically used for macros, though it works for functions too. See
Section 14.6 [Indenting Macros], page 262.
(interactive-only value)
Set the function’s interactive-only property to value. See [The
interactive-only property], page 402.
(obsolete current-name when)
Mark the function or macro as obsolete, similar to a call to
make-obsolete (see Section 13.12 [Obsolete Functions], page 247).
current-name should be a symbol (in which case the warning message
says to use that instead), a string (specifying the warning message), or
nil (in which case the warning message gives no extra details). when
should be a string indicating when the function or macro was first made
obsolete.
(compiler-macro expander)
This can only be used for functions, and tells the compiler to use expander
as an optimization function. When encountering a call to the function,
of the form (function args...), the macro expander will call expander
with that form as well as with args . . . , and expander can either return
a new expression to use instead of the function call, or it can return
just the form unchanged, to indicate that the function call should be left
alone. expander can be a symbol, or it can be a form (lambda (arg)
body) in which case arg will hold the original function call expression,
and the (unevaluated) arguments to the function can be accessed using
the function’s formal arguments.
(gv-expander expander)
Declare expander to be the function to handle calls to the macro (or
function) as a generalized variable, similarly to gv-define-expander.
expander can be a symbol or it can be of the form (lambda (arg) body)
in which case that function will additionally have access to the macro (or
function)’s arguments.
(gv-setter setter)
Declare setter to be the function to handle calls to the macro (or function)
as a generalized variable. setter can be a symbol in which case it will be
passed to gv-define-simple-setter, or it can be of the form (lambda
Chapter 13: Functions 252
(arg) body) in which case that function will additionally have access to
the macro (or function)’s arguments and it will be passed to gv-define-
setter.
(completion completion-predicate)
Declare completion-predicate as a function to determine whether to in-
clude the symbol in the list of functions when asking for completions
in M-x. completion-predicate is called with two parameters: The first
parameter is the symbol, and the second is the current buffer.
(modes modes)
Specify that this command is meant to be applicable for modes only.
(pure val)
If val is non-nil, this function is pure (see Section 13.1 [What Is a Func-
tion], page 221). This is the same as the pure property of the function’s
symbol (see Section 9.4.2 [Standard Properties], page 136).
(side-effect-free val)
If val is non-nil, this function is free of side effects, so the byte com-
piler can ignore calls whose value is ignored. This is the same as the
side-effect-free property of the function’s symbol, see Section 9.4.2
[Standard Properties], page 136.
(speed n) Specify the value of native-comp-speed in effect for native compilation of
this function (see Section 18.2 [Native-Compilation Variables], page 314).
This allows function-level control of the optimization level used for native
code emitted for the function. In particular, if n is −1, native compilation
of the function will emit bytecode instead of native code for the function.
no-font-lock-keyword
This is valid for macros only. Macros with this declaration are highlighted
by font-lock (see Section 24.6 [Font Lock Mode], page 527) as normal
functions, not specially as macros.
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.
declare-function function file &optional arglist fileonly [Macro]
Tell the byte compiler to assume that function is defined in the file file. The optional
third argument arglist is either t, meaning the argument list is unspecified, or a list
of formal parameters in the same style as defun. An omitted arglist defaults to t, not
nil; this is atypical behavior for omitted arguments, and it means that to supply a
fourth but not third argument one must specify t for the third-argument placeholder
instead of the usual nil. The optional fourth argument fileonly non-nil means check
only that file exists, not that it actually defines function.
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.
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 248.
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 284.
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 147). 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)))
binding is the most local binding of such variable, so any references inside the form being
evaluated do refer to it. Here is an example:
(defmacro foo (a)
(list 'setq (eval a) t))
(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.
lines at the same nesting level should be indented just like this one; a list says
that following lines might call for different indentations. This makes a difference
when the indentation is being computed by C-M-q; if the value is a number,
C-M-q need not recalculate indentation for the following lines until the end of
the list.
264
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 40.12.2 [Defining Faces], page 1073); 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 1238.
(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.
(face-link face)
Link to the documentation of a face; face is a string which specifies
the name of the face to describe with describe-face 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 284). 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.
Chapter 15: Customization Settings 266
The most common reason to use :require is when a variable enables a feature
such as a minor mode, and just setting the variable won’t have any effect unless
the code which implements the mode is loaded.
:version version
This keyword specifies that the item was first introduced in Emacs version
version, or that its default value was changed in that version. The value version
must be a string.
:package-version '(package . version)
This keyword specifies that the item was first introduced in package version
version, or that its meaning or default value was changed in that version. 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.
the user has already saved a customization for option, the user’s customized value is
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 195.
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 189.) 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 1242), 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 264, 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 271).
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.
Re-evaluating a defcustom form with a different :options value does not clear
the values added by previous evaluations, or added by calls to custom-add-
frequent-value (see below).
: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
Chapter 15: Customization Settings 269
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.
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 function 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)
Chapter 15: Customization Settings 270
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 135. In
Chapter 15: Customization Settings 271
addition, there’s themed-value, which is used to record the value set by a theme (see
Section 15.6 [Custom Themes], page 281). These properties are lists, the car of which is an
expression that evaluates to the value.
sexp The value may be any Lisp object that can be printed and read back. You can
use sexp as a fall-back for any option, if you don’t want to take the time to
work out a more specific type to use.
integer The value must be an integer.
natnum The value must be a nonnegative integer.
number The value must be a number (floating point or integer).
float The value must be floating point.
string The value must be a string. The customization buffer shows the string without
delimiting ‘"’ characters or ‘\’ quotes.
regexp Like string except that the string must be a valid regular expression.
character
The value must be a character code. A character code is actually an integer,
but this type shows the value by inserting the character in the buffer, rather
than by showing the number.
file The value must be a file name. 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 267.
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 23.1 [Key Sequences],
page 451.
Chapter 15: Customization Settings 273
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.
Section 15.3 [Variable Definitions], page 267). 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:
:options '("foo" ("bar" integer) "baz")
Finally, you may want to change how the key is presented. By default, the
key is simply shown as a const, since the user cannot change the special keys
specified with the :options keyword. However, you may want to use a more
specialized type for presenting the key, like function-item if you know it is a
symbol with a function binding. This is done by using a customization type
specification instead of a symbol for the key.
:options '("foo"
((function-item some-function) integer)
"baz")
Many alists use lists with two elements, instead of cons cells. For example,
(defcustom list-alist
'(("foo" 1) ("bar" 2) ("baz" 3))
"Each element is a list of the form (KEY VALUE).")
instead of
(defcustom cons-alist
'(("foo" . 1) ("bar" . 2) ("baz" . 3))
"Each element is a cons-cell (KEY . VALUE).")
Because of the way lists are implemented on top of cons cells, you can treat
list-alist in the example above as a cons cell alist, where the value type is a
list with a single element containing the real value.
(defcustom list-alist '(("foo" 1) ("bar" 2) ("baz" 3))
"Each element is a list of the form (KEY VALUE)."
:type '(alist :value-type (group integer)))
The group widget is used here instead of list only because the formatting is
better suited for the purpose.
Similarly, you can have alists with more values associated with each key, using
variations of this trick:
(defcustom person-data '(("brian" 50 t)
Chapter 15: Customization Settings 275
("dorith" 55 nil)
("ken" 52 t))
"Alist of basic info about people.
Each element has the form (NAME AGE MALE-FLAG)."
:type '(alist :value-type (group integer boolean)))
(plist :key-type key-type :value-type value-type)
This customization type is similar to alist (see above), except that (i) the in-
formation is stored as a property list, (see Section 5.9 [Property Lists], page 97),
and (ii) key-type, if omitted, defaults to symbol rather than sexp.
(choice alternative-types...)
The value must fit one of alternative-types. For example, (choice integer
string) allows either an integer or a string.
In the customization buffer, the user selects an alternative using a menu, and
can then edit the value in the usual way for that alternative.
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 278.
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.
Chapter 15: Customization Settings 276
with a file name, followed either by the symbol t or two strings, use this customization
type:
(list file
(choice (const t)
(list :inline t string string)))
If the user chooses the first alternative in the choice, then the overall list has two elements
and the second element is t. If the user chooses the second alternative, then the overall list
has three elements and the second and third must be strings.
The widgets can specify predicates to say whether an inline value matches the widget
with the :match-inline element.
:type-error string
string should be a string that describes why a value doesn’t match the type,
as determined by the :match function. When the :match function returns nil,
the widget’s :error property will be set to string.
The defcustom shows how the new widget can be used as an ordinary customization
type.
The reason for the name lazy is that the other composite widgets convert their inferior
widgets to internal form when the widget is instantiated in a buffer. This conversion is
recursive, so the inferior widgets will convert their inferior widgets. If the data structure
is itself recursive, this conversion is an infinite recursion. The lazy widget prevents the
recursion: it convert its :type argument only when needed.
an Emacs Lisp source file, which should follow the conventions described in this section.
(Instead of writing a Custom theme by hand, you can also create one using a Customize-like
interface; see Section “Creating Custom Themes” in The GNU Emacs Manual.)
A Custom theme file should be named foo-theme.el, where foo is the theme name.
The first Lisp form in the file should be a call to deftheme, and the last form should be a
call to provide-theme.
deftheme theme &optional doc [Macro]
This macro declares theme (a symbol) as the name of a Custom theme. The optional
argument doc should be a string describing the theme; this is the description shown
when the user invokes the describe-theme command or types ? in the ‘*Custom
Themes*’ buffer.
Two special theme names are disallowed (using them causes an error): user is a
dummy theme that stores the user’s direct customization settings, and changed is a
dummy theme that stores changes made outside of the Customize system.
provide-theme theme [Macro]
This macro declares that the theme named theme has been fully specified.
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.
custom-theme-set-variables theme &rest args [Function]
This function specifies the Custom theme theme’s variable settings. theme should be
a symbol. Each argument in args should be a list of the form
(var expression [now [request [comment]]])
where the list entries have the same meanings as in custom-set-variables. See
Section 15.5 [Applying Customizations], page 281.
custom-theme-set-faces theme &rest args [Function]
This function specifies the Custom theme theme’s face settings. theme should be a
symbol. Each argument in args should be a list of the form
(face spec [now [comment]])
where the list entries have the same meanings as in custom-set-faces. See
Section 15.5 [Applying Customizations], page 281.
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 usually take precedence when Emacs is looking for a theme
to load.
The following functions are useful for programmatically enabling and disabling themes:
custom-theme-p theme [Function]
This function return a non-nil value if theme (a symbol) is the name of a Custom
theme (i.e., a Custom theme which has been loaded into Emacs, whether or not the
theme is enabled). Otherwise, it returns nil.
Chapter 15: Customization Settings 283
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 41.21 [Dynamic Libraries], page 1196.
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.
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 20.3 [Input Functions], page 355.
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 149.
For information about how load is used in building Emacs, see Section E.1 [Building
Emacs], page 1242.
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.
Chapter 16: Loading 287
load-file-rep-suffixes [Variable]
This is a list of suffixes that indicate representations of the same file. This list should
normally start with the empty string. When load searches for a file it appends the
suffixes in this list, in order, to the file name, before searching for another file.
Enabling Auto Compression mode appends the suffixes in jka-compr-load-suffixes
to this list and disabling Auto Compression mode removes them again. The standard
value of load-file-rep-suffixes if Auto Compression mode is disabled is ("").
Given that the standard value of jka-compr-load-suffixes is (".gz"), the stan-
dard value of load-file-rep-suffixes if Auto Compression mode is enabled is (""
".gz").
get-load-suffixes [Function]
This function returns the list of all suffixes that load should try, in order, when its
must-suffix argument is non-nil. This takes both load-suffixes and load-file-
rep-suffixes into account. If load-suffixes, jka-compr-load-suffixes and
load-file-rep-suffixes all have their standard values, this function returns
(".elc" ".elc.gz" ".el" ".el.gz") if Auto Compression mode is enabled and
(".elc" ".el") if Auto Compression mode is disabled.
To summarize, load normally first tries the suffixes in the value of (get-load-suffixes)
and then those in load-file-rep-suffixes. If nosuffix is non-nil, it skips the former
group, and if must-suffix is non-nil, it skips the latter group.
load-path [Variable]
The value of this variable is a list of directories to search when loading files with load.
Each element is a string (which must be a directory) or nil (which stands for the
current working directory).
When Emacs starts up, it sets up the value of load-path in several steps. First, it
initializes load-path using default locations set when Emacs was compiled. Normally, this
is a directory something like
"/usr/local/share/emacs/version/lisp"
(In this and the following examples, replace /usr/local with the installation prefix
appropriate for your Emacs.) These directories contain the standard Lisp files that come
with Emacs. If Emacs cannot find them, it will not start correctly.
If you run Emacs from the directory where it was built—that is, an executable that has
not been formally installed—Emacs instead initializes load-path using the lisp directory
in the directory containing the sources from which it was built. If you built Emacs in a
Chapter 16: Loading 288
separate directory from the sources, it also adds the lisp directories from the build directory.
(In all cases, elements are represented as absolute file names.)
Unless you start Emacs with the --no-site-lisp option, it then adds two more
site-lisp directories to the front of load-path. These are intended for locally installed
Lisp files, and are normally of the form:
"/usr/local/share/emacs/version/site-lisp"
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 42.1 [Packaging
Basics], page 1199).
It is common to add code to one’s init file (see Section 41.1.2 [Init File], page 1156) 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 1242), any changes to load-path that these files make will be lost after dumping.
Chapter 16: Loading 289
If Emacs was compiled with support for native compilation (see Chapter 18 [Native Com-
pilation], page 312), then when a ‘.elc’ byte-compiled file is found by searching load-path,
Emacs will try to look for a corresponding ‘.eln’ file holding the corresponding natively-
compiled code. The natively-compiled files are looked up in the directories listed by the
native-comp-eln-load-path.
native-comp-eln-load-path [Variable]
This variable holds a list of directories where Emacs looks for natively-compiled ‘.eln’
files. File names in the list that are not absolute are interpreted as relative to
invocation-directory (see Section 41.3 [System Environment], page 1163). The
last directory in the list is the system directory, i.e. the directory with ‘.eln’ files
installed by the Emacs build and installation procedure. In each of the directories
in the list, Emacs looks for ‘.eln’ files in a subdirectory whose name is constructed
from the Emacs version and an 8-character hash that depends on the current native-
compilation ABI; the name of this subdirectory is stored in the variable comp-native-
version-dir.
text of the program will be unibyte text, and its string constants will be unibyte strings.
See Section 34.10 [Coding Systems], page 913.
In most Emacs Lisp programs, the fact that non-ASCII strings are multibyte strings
should not be noticeable, since inserting them in unibyte buffers converts them to unibyte
automatically. However, if this does make a difference, you can force a particular Lisp file to
be interpreted as unibyte by writing ‘coding: raw-text’ in a local variables section. With
that designator, the file will unconditionally be interpreted as unibyte. This can matter
when making keybindings to non-ASCII characters written as ?vliteral.
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 25.1 [Documentation Basics],
page 551), and completion of variable and function names (see Section 16.5.1 [Autoload by
Prefix], page 293, 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.
You can autoload macros and keymaps as well as ordinary functions. Specify type
as macro if function is really a macro. Specify type as keymap if function is really a
keymap. Various parts of Emacs need to know this information without loading the
real definition.
An autoloaded keymap loads automatically during key lookup when a prefix key’s
binding is the symbol function. Autoloading does not occur for other kinds of access
to the keymap. In particular, it does not happen when a Lisp program gets the
keymap from the value of a variable and calls define-key; not even if the variable
name is the same symbol function.
If function already has a non-void function definition that is not an autoload object,
this function does nothing and returns nil. Otherwise, it constructs an autoload
object (see Section 2.4.19 [Autoload Type], page 24), and stores it as the function
definition for function. The autoload object has this form:
(autoload filename docstring interactive type)
For example,
(symbol-function 'run-prolog)
⇒ (autoload "prolog" 169681 t nil)
In this case, "prolog" is the name of the file to load, 169681 refers to the docu-
mentation string in the emacs/etc/DOC file (see Section 25.1 [Documentation Basics],
page 551), t means the function is interactive, and nil that it is not a macro or a
keymap.
autoloadp object [Function]
This function returns non-nil if object is an autoload object. For example, to check
if run-prolog is defined as an autoloaded function, evaluate
(autoloadp (symbol-function 'run-prolog))
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 make-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
Chapter 16: Loading 292
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)
(switch-to-buffer "*doctor*")
(doctor-mode))
Here’s what that produces in loaddefs.el:
(autoload '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 1242. 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 25.6 [Help Functions], page 558) 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")
Chapter 16: Loading 293
(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 208). 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.
Chapter 16: Loading 295
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)
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 301) as well as when you load it. This is in
case the required package contains macros that the byte compiler must know about. It also
avoids byte compiler warnings for functions and variables defined in the file loaded with
require.
Although top-level calls to require are evaluated during byte compilation, provide
calls are not. Therefore, you can ensure that a file of definitions is loaded before it is byte-
compiled by including a provide followed by a require for the same feature, as in the
following example.
(provide 'my-feature) ; Ignored by byte compiler,
; evaluated by load.
(require 'my-feature) ; Evaluated by byte compiler.
The compiler ignores the provide, then processes the require by loading the file in ques-
tion. Loading the file does execute the provide call, so the subsequent require call does
nothing when the file is loaded.
Chapter 16: Loading 296
(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 290.
features [Variable]
The value of this variable is a list of symbols that are the features loaded in the
current Emacs session. Each symbol was put in this list with a call to provide. The
order of the elements in the features list is not significant.
load-history [Variable]
The value of this variable is an alist that associates the names of loaded library files
with the names of the functions and variables they defined, as well as the features
they provided or required.
Each element in this alist describes one loaded library (including libraries that are
preloaded at startup). It is a list whose car is the absolute file name of the library
(a string). The rest of the list elements have these forms:
var The symbol var was defined as a variable.
(defun . fun)
The function fun was defined.
(t . fun) The function fun was previously an autoload before this library redefined
it as a function. The following element is always (defun . fun), which
represents defining fun as a function.
(autoload . fun)
The function fun was defined as an autoload.
(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.
Chapter 16: Loading 298
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 148.
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:
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.
Chapter 16: Loading 299
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:
module-file-suffix [Variable]
This variable holds the system-dependent value of the file-name extension of the
module files. Its value is .so on POSIX hosts, .dylib on macOS, and .dll on
MS-Windows.
Chapter 16: Loading 300
On macOS, dynamic modules can also have the suffix .so in addition to .dylib.
Every dynamic module should export a C-callable function named emacs_module_init,
which Emacs will call as part of the call to load or require which loads the module. It
should also export a symbol named plugin_is_GPL_compatible to indicate that its code
is released under the GPL or compatible license; Emacs will signal an error if your program
tries to load modules that don’t export such a symbol.
If a module needs to call Emacs functions, it should do so through the API (Application
Programming Interface) defined and documented in the header file emacs-module.h that
is part of the Emacs distribution. See Section E.8 [Writing Dynamic Modules], page 1256,
for details of using that API when writing your own modules.
Modules can create user-ptr Lisp objects that embed pointers to C struct’s defined by
the module. This is useful for keeping around complex data structures created by a module,
to be passed back to the module’s functions. User-ptr objects can also have associated
finalizers – functions to be run when the object is GC’ed; this is useful for freeing any
resources allocated for the underlying data structure, such as memory, open file descriptors,
etc. See Section E.8.3 [Module Values], page 1262.
Loadable modules in Emacs are enabled by using the --with-modules option at config-
ure time.
301
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 174).
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 294). 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 305). For more details, See Section 14.3 [Compiling Macros], page 257.
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
byte-recompile-directory directory &optional flag force [Command]
follow-symlinks
This command recompiles every ‘.el’ file in directory (or its subdirectories) that
needs recompilation. A file needs recompilation if a ‘.elc’ file exists but is older than
the ‘.el’ file.
When a ‘.el’ file has no corresponding ‘.elc’ file, flag says what to do. If it is nil,
this command ignores these files. If flag is 0, it compiles them. If it is neither nil nor
0, it asks the user whether to compile each such file, and asks about each subdirectory
as well.
Interactively, byte-recompile-directory prompts for directory and flag is the prefix
argument.
If force is non-nil, this command recompiles every ‘.el’ file that has a ‘.elc’ file.
This command will normally not compile ‘.el’ files that are symlinked. If the optional
follow-symlink parameter is non-nil, symlinked ‘.el’ will also be compiled.
The returned value is unpredictable.
batch-byte-compile &optional noforce [Function]
This function runs byte-compile-file on files specified on the command line. This
function must be used only in a batch execution of Emacs, as it kills Emacs on
completion. An error in one file does not prevent processing of subsequent files, but
no output file will be generated for it, and the Emacs process will terminate with a
nonzero status code.
If noforce is non-nil, this function does not recompile files that have an up-to-date
‘.elc’ file.
$ emacs -batch -f batch-byte-compile *.el
Chapter 17: Byte Compilation 304
• 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.
Experience shows that using dynamic function loading provides benefits that are hardly
measurable, so this feature is deprecated since Emacs 27.1.
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.
• You can suppress the warning for a specific call to a function func by conditionalizing
it on an fboundp test, like this:
(if (fboundp 'func) ...(func ...)...)
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 252.
• 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 189.
You can also suppress compiler warnings within a certain expression using the
with-suppressed-warnings macro:
For more coarse-grained suppression of compiler warnings, you can use the with-no-
warnings construct:
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.
Chapter 17: Byte Compilation 308
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).
(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.)
Chapter 17: Byte Compilation 311
will load each file that it succeeded to compile. The optional argument selector allows
control of which of files will be compiled; it can have one of the following values:
nil or omitted
Select all the files and directories in files.
a regular expression string
Select the files and directories whose names match the regexp.
a function A predicate function, which will be called with each file and directory
in files, and should return non-nil if the file or the directory should be
selected for compilation.
On systems with multiple CPU execution units, when files names more than one file,
this function will normally start several compilation subprocesses in parallel, under the
control of native-comp-async-jobs-number (see Section 18.2 [Native-Compilation
Variables], page 314).
The following function allows Lisp programs to test whether native-compilation is avail-
able at runtime.
native-comp-available-p [Function]
This function returns non-nil if the running Emacs process has the native-compilation
support compiled into it. On systems that load libgccjit dynamically, it also makes
sure that library is available and can be loaded. Lisp programs that need to know up
front whether native-compilation is available should use this predicate.
The value can also be a list of error conditions (see Section 11.7.3.1 [Signaling Errors],
page 175). 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 39 [Processes], page 987.
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)
19.1.7 Backtraces
Debugger mode is derived from Backtrace mode, which is also used to show backtraces by
Edebug and ERT. (see Section 19.2 [Edebug], page 326, and ERT: Emacs Lisp Regression
Testing.)
Chapter 19: Debugging Lisp Programs 321
The backtrace buffer shows you the functions that are executing and their argument
values. When a backtrace buffer is created, it shows each stack frame on one, possibly very
long, line. (A stack frame is the place where the Lisp interpreter records information about
a particular invocation of a function.) The most recently called function will be at the top.
In a backtrace you can specify a stack frame by moving point to a line describing that
frame. The frame whose line point is on is considered the current frame.
If a function name is underlined, that means Emacs 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. You can also type RET while point is on any name of a function or
variable which is not underlined, to see help information for that symbol in a help buffer, if
any exists. The xref-find-definitions command, bound to M-., can also be used on any
identifier in a backtrace (see Section “Looking Up Identifiers” in The GNU Emacs Manual).
In backtraces, the tails of long lists and the ends of long strings, vectors or structures,
as well as objects which are deeply nested, will be printed as underlined “...”. You can click
with the mouse on a “...”, or type RET while point is on it, to show the part of the object
that was hidden. To control how much abbreviation is done, customize backtrace-line-
length.
Here is a list of commands for navigating and viewing backtraces:
v Toggle the display of local variables of the current stack frame.
p Move to the beginning of the frame, or to the beginning of the previous frame.
n Move to the beginning of the next frame.
+ Add line breaks and indentation to the top-level Lisp form at point to make it
more readable.
- Collapse the top-level Lisp form at point back to a single line.
# Toggle print-circle for the frame at point.
: Toggle print-gensym for the frame at point.
. Expand all the forms abbreviated with “...” in the frame at point.
that you caused by changing variable values or data structures while inside the
debugger).
d Continue execution, but enter the debugger the next time any Lisp function is
called. This allows you to step through the subexpressions of an expression,
seeing what values the subexpressions compute, and what else they do.
The stack frame made for the function call which enters the debugger in this
way will be flagged automatically so that the debugger will be called again when
the frame is exited. You can use the u command to cancel this flag.
b Flag the current frame so that the debugger will be entered when the frame
is exited. Frames flagged in this way are marked with stars in the backtrace
buffer.
u Don’t enter the debugger when the current frame is exited. This cancels a b
command on that frame. The visible effect is to remove the star from the line
in the backtrace buffer.
j Flag the current frame like b. Then continue execution like c, but temporarily
disable break-on-entry for all functions that are set up to do so by debug-on-
entry.
e Read a Lisp expression in the minibuffer, evaluate it (with the relevant lexical
environment, if applicable), and print the value in the echo area. The debugger
alters certain important variables, and the current buffer, as part of its opera-
tion; e temporarily restores their values from outside the debugger, so you can
examine and change them. This makes the debugger more transparent. By
contrast, M-: does nothing special in the debugger; it shows you the variable
values within the debugger.
R Like e, but also save the result of evaluation in the buffer *Debugger-record*.
q Terminate the program being debugged; return to top-level Emacs command
execution.
If the debugger was entered due to a C-g but you really want to quit, and not
debug, use the q command.
r Return a value from the debugger. The value is computed by reading an ex-
pression with the minibuffer and evaluating it.
The r command is useful when the debugger was invoked due to exit from a
Lisp call frame (as requested with b or by entering the frame with d); then the
value specified in the r command is used as the value of that frame. It is also
useful if you call debug and use its return value. Otherwise, r has the same
effect as c, and the specified return value does not matter.
You can’t use r when the debugger was entered due to an error.
l Display a list of functions that will invoke the debugger when called. This is a
list of functions that are set to break on entry by means of debug-on-entry.
debugger [Variable]
The value of this variable is the function to call to invoke the debugger. Its value
must be a function of any number of arguments, or, more typically, the name of a
function. This function should invoke some kind of debugger. The default value of
the variable is debug.
The first argument that Lisp hands to the function indicates why it was called. The
convention for arguments is detailed in the description of debug (see Section 19.1.9
[Invoking the Debugger], page 322).
backtrace [Function]
This function prints a trace of Lisp function calls currently active. The trace is
identical to the one that debug would show in the *Backtrace* buffer. The return
value is always nil.
In the following example, a Lisp expression calls backtrace explicitly. This prints
the backtrace to the stream standard-output, which, in this case, is the buffer
‘backtrace-output’.
Each line of the backtrace represents one function call. The line shows the function
followed by a list of the values of the function’s arguments if they are all known; if
they are still being computed, the line consists of a list containing the function and
its unevaluated arguments. Long lists or deeply nested structures may be elided.
(with-output-to-temp-buffer "backtrace-output"
(let ((var 1))
(save-excursion
(setq var (eval '(progn
(1+ var)
(list 'testing (backtrace))))))))
⇒ (testing nil)
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
----------- Buffer: backtrace-output ------------
debug-on-next-call [Variable]
If this variable is non-nil, it says to call the debugger before the next eval, apply
or funcall. Entering the debugger sets debug-on-next-call to nil.
The d command in the debugger works by setting this variable.
backtrace-debug level flag [Function]
This function sets the debug-on-exit flag of the stack frame level levels down the stack,
giving it the value flag. If flag is non-nil, this will cause the debugger to be entered
when that frame later exits. Even a nonlocal exit through that frame will enter the
debugger.
This function is used only by the debugger.
command-debug-status [Variable]
This variable records the debugging status of the current interactive command. Each
time a command is called interactively, this variable is bound to nil. The debugger
can set this variable to leave information for future debugger invocations during the
same command invocation.
The advantage of using this variable rather than an ordinary global variable is that
the data will never carry over to a subsequent command invocation.
This variable is obsolete and will be removed in future versions.
backtrace-frame frame-number &optional base [Function]
The function backtrace-frame is intended for use in Lisp debuggers. It returns
information about what computation is happening in the stack frame frame-number
levels down.
Chapter 19: Debugging Lisp Programs 326
If that frame has not evaluated the arguments yet, or is a special form, the value is
(nil function arg-forms...).
If that frame has evaluated its arguments and called its function already, the return
value is (t function arg-values...).
In the return value, function is whatever was supplied as the car of the evaluated
list, or a lambda expression in the case of a macro call. If the function has a &rest
argument, that is represented as the tail of the list arg-values.
If base is specified, frame-number counts relative to the topmost frame whose function
is base.
If frame-number is out of range, backtrace-frame returns nil.
19.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.
Chapter 19: Debugging Lisp Programs 327
See Section 19.2.9 [Edebug Eval], page 334, for other evaluation functions available inside
of Edebug.
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.
Chapter 19: Debugging Lisp Programs 330
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 19.2.16 [Edebug Options], page 346.
edebug-sit-for-seconds [User Option]
This option specifies how many seconds to wait between execution steps in trace mode
or continue mode. The default is 1 second.
19.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 19.2.6.1 [Breakpoints], page 332, 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).
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.
Chapter 19: Debugging Lisp Programs 331
19.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.
are no following breakpoints. This command does not continue execution—it just moves
point in the buffer.
19.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 19.2.14 [The Outside Context], page 338, 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 19: Debugging Lisp Programs 335
If an error occurs during an evaluation from the evaluation list, the error message is
displayed in a string as if it were the result. Therefore, expressions using variables that are
not currently valid do not interrupt your debugging.
Here is an example of what the evaluation list window looks like after several expressions
have been added to it:
(current-buffer)
#<buffer *scratch*>
;---------------------------------------------------------------
(selected-window)
#<window 16 on *scratch*>
;---------------------------------------------------------------
(point)
196
;---------------------------------------------------------------
bad-var
"Symbol's value as variable is void: bad-var"
;---------------------------------------------------------------
(recursion-depth)
0
;---------------------------------------------------------------
this-command
eval-last-sexp
;---------------------------------------------------------------
To delete a group, move point into it and type C-c C-d, or simply delete the text for
the group and update the evaluation list with C-c C-u. To add a new expression to the
evaluation list, insert the expression at a suitable place, insert a new comment line, then
type C-c C-u. You need not insert dashes in the comment line—its contents don’t matter.
After selecting *edebug*, you can return to the source code buffer with C-c C-w. The
*edebug* buffer is killed when you continue execution, and recreated next time it is needed.
You can also print circular structures and structures that share elements more informa-
tively by binding print-circle to a non-nil value.
Here is an example of code that creates a circular structure:
(setq a (list 'x 'y))
Chapter 19: Debugging Lisp Programs 337
(setcar a a)
If print-circle is non-nil, printing functions (e.g., prin1) will print a as ‘#1=(#1# y)’.
The ‘#1=’ notation labels the structure that follows it with the label ‘1’, and the ‘#1#’
notation references the previously labeled structure. This notation is used for any shared
elements of lists or vectors.
For further details about how printing can be customized, see see Section 20.5 [Output
Functions], page 358.
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.
since you began testing coverage in the current Emacs session. Thus, to do coverage testing
on your program, execute it under various conditions and note whether it behaves correctly;
Edebug will tell you when you have tried enough different conditions that each form has
returned two different values.
Coverage testing makes execution slower, so it is only done if edebug-test-coverage is
non-nil. Frequency counting is performed for all executions of an instrumented function,
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.
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.
def-edebug-spec macro specification [Macro]
Specify which expressions of a call to macro macro are forms to be evaluated. speci-
fication should be the Edebug specification. Neither argument is evaluated.
The macro argument can actually be any symbol, not just a macro name.
Here is a table of the possibilities for specification and how each directs processing of
arguments.
t All arguments are instrumented for evaluation. This is short for (body).
a symbol The symbol must have an Edebug specification, which is used instead. This
indirection is repeated until another kind of specification is found. This allows
you to inherit the specification from another macro.
a list The elements of the list describe the types of the arguments of a calling form.
The possible elements of a specification list are described in the following sec-
tions.
If a macro has no Edebug specification, neither through a debug declaration nor through
a def-edebug-spec call, the variable edebug-eval-macro-args comes into play.
edebug-eval-macro-args [User Option]
This controls the way Edebug treats macro arguments with no explicit Edebug specifi-
cation. If it is nil (the default), none of the arguments is instrumented for evaluation.
Otherwise, all arguments are instrumented.
&interpose
Lets a function control the parsing of the remaining code. It takes the form
&interpose spec fun args... and means that Edebug will first match spec
against the code and then call fun with the code that matched spec, a parsing
function pf, and finally args.... The parsing function expects a single argument
indicating the specification list to use to parse the remaining code. It should be
called exactly once and returns the instrumented code that fun is expected to re-
turn. For example (&interpose symbolp pcase--match-pat-args) matches
sexps whose first element is a symbol and then lets pcase--match-pat-args
lookup the specs associated with that head symbol according to pcase--match-
pat-args and pass them to the pf it received as argument.
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-elem-spec:
def-edebug-elem-spec element specification [Function]
Define the specification to use in place of the symbol element. specifica-
tion has to be a list.
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
Chapter 19: Debugging Lisp Programs 344
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 Extracts the name of the current defining form from the code. It takes the form
&name [prestring] spec [poststring] fun args... and means that Edebug
will match spec against the code and then call fun with the concatenation of the
current name, args..., prestring, the code that matched spec, and poststring.
If fun is absent, it defaults to a function that concatenates the arguments (with
an @ between the previous name and the new).
name The argument, a symbol, is the name of the defining form. Shorthand for
[&name symbolp].
A defining form is not required to have a name field; and it may have multiple
name fields.
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.
Backtracking is disabled while matching any of the form specifications (that is, form,
body, def-form, and def-body). These specifications will match any form so any error
must be in the form itself rather than at a higher level.
Backtracking is also disabled after successfully matching a quoted symbol, string specifi-
cation, or &define keyword, since this usually indicates a recognized construct. But if you
have a set of alternative constructs that all begin with the same symbol, you can usually
work around this constraint by factoring the symbol out of the alternatives, e.g., ["foo"
&or [first case] [second case] ...].
Most needs are satisfied by these two ways that backtracking is automatically disabled,
but occasionally it is useful to explicitly disable backtracking by using the gate specification.
This is useful when you know that no higher alternatives could apply. See the example of
the let specification.
(def-edebug-elem-spec 'lambda-list
'(([&rest arg]
[&optional ["&optional" arg &rest arg]]
&optional ["&rest" arg]
)))
(def-edebug-elem-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
Chapter 19: Debugging Lisp Programs 346
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-elem-spec 'backquote-form
'(&or ([&or "," ",@"] &or ("quote" backquote-form) form)
(backquote-form . [&or nil backquote-form])
(vector &rest backquote-form)
sexp))
Saving and restoring point in other buffers is necessary if you are debugging code that
changes the point of a buffer that is displayed in a non-selected window. If Edebug
or the user then selects the window, point in that buffer will move to the window’s
value of point.
Saving and restoring point in all buffers is expensive, since it requires selecting each
window twice, so enable this only if you need it. See Section 19.2.14.2 [Edebug Display
Update], page 339.
edebug-initial-mode [User Option]
If this variable is non-nil, it specifies the initial execution mode for Edebug when it is
first activated. Possible values are step, next, go, Go-nonstop, trace, Trace-fast,
continue, and Continue-fast.
The default value is step. This variable can be set interactively with C-x C-a
C-m (edebug-set-initial-mode). See Section 19.2.3 [Edebug Execution Modes],
page 329.
edebug-trace [User Option]
If this is non-nil, trace each function entry and exit. Tracing output is displayed in
a buffer named *edebug-trace*, one function entry or exit per line, indented by the
recursion level.
Also see edebug-tracing, in Section 19.2.12 [Trace Buffer], page 337.
edebug-test-coverage [User Option]
If non-nil, Edebug tests coverage of all expressions debugged. See Section 19.2.13
[Coverage Testing], page 337.
edebug-continue-kbd-macro [User Option]
If non-nil, continue defining or executing any keyboard macro that is executing
outside of Edebug. Use this with caution since it is not debugged. See Section 19.2.3
[Edebug Execution Modes], page 329.
edebug-print-length [User Option]
If non-nil, the default value of print-length for printing results in Edebug. See
Section 20.6 [Output Variables], page 360.
edebug-print-level [User Option]
If non-nil, the default value of print-level for printing results in Edebug. See
Section 20.6 [Output Variables], page 360.
edebug-print-circle [User Option]
If non-nil, the default value of print-circle for printing results in Edebug. See
Section 20.6 [Output Variables], page 360.
edebug-unwrap-results [User Option]
If non-nil, Edebug tries to remove any of its own instrumentation when showing the
results of expressions. This is relevant when debugging macros where the results of
expressions are themselves instrumented expressions. As a very artificial example,
suppose that the example function fac has been instrumented, and consider a macro
of the form:
(defmacro test () "Edebug example."
Chapter 19: Debugging Lisp Programs 348
either the same or a replacement form, which Edebug will then use as the final result
of instrumentation.
Edebug also has a coverage testing feature (see Section 19.2.13 [Coverage Testing],
page 337). These features partly duplicate each other, and it would be cleaner to com-
bine them.
Chapter 19: Debugging Lisp Programs 351
19.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 sample CPU usage periodically (cpu), when memory is allocated (memory),
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 CPU usage sampled by each type (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, preceded by
how much CPU resources it used in absolute and percentage terms since profiling started.
If a given line has a ‘+’ symbol to the left of the function name, 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 function benchmark-call as well as the macros benchmark-run,
benchmark-run-compiled, benchmark-progn and benchmark-call in benchmark.el. You
can also use the benchmark command for timing forms interactively.
352
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
(see Section 41.17 [Batch Mode], page 1187), standard input is used instead of
the minibuffer. For example,
(message "%s" (read t))
will in batch mode 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.
Chapter 20: Reading and Printing Lisp Objects 355
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.6 [Circular Objects], page 29. 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.
Chapter 20: Reading and Printing Lisp Objects 356
The following function allows you to control the I/O mode of any standard stream of the
Emacs process.
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 79). At the end, the list contains all the characters
output, but in reverse order.
(setq last-output nil)
⇒ nil
Chapter 20: Reading and Printing Lisp Objects 358
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.
line. Note in this case stream can not be a function and an error is signaled if it is.
This function returns t if a newline is printed.
If you need to use binary I/O in batch mode, e.g., use the functions described in this
section to write out arbitrary binary data or avoid conversion of newlines on non-POSIX
hosts, see Section 20.3 [Input Functions], page 355.
print-quoted [Variable]
If this is non-nil, that means to print quoted forms using abbreviated reader syntax,
e.g., (quote foo) prints as 'foo, and (function foo) as #'foo. The default is t.
print-escape-newlines [Variable]
If this variable is non-nil, then newline characters in strings are printed as ‘\n’ and
formfeeds are printed as ‘\f’. Normally these characters are printed as actual newlines
and formfeeds.
This variable affects the print functions prin1 and print that print with quoting. It
does not affect princ. Here is an example using prin1:
(prin1 "a\nb")
a "a
a b"
⇒ "a
b"
print-escape-control-characters [Variable]
If this variable is non-nil, control characters in strings are printed as backslash se-
quences by the print functions prin1 and print that print with quoting. If this
variable and print-escape-newlines are both non-nil, the latter takes precedences
for newlines and formfeeds.
print-escape-nonascii [Variable]
If this variable is non-nil, then unibyte non-ASCII characters in strings are uncondi-
tionally printed as backslash sequences by the print functions prin1 and print that
print with quoting.
Those functions also use backslash sequences for unibyte non-ASCII characters, re-
gardless of the value of this variable, when the output stream is a multibyte buffer or
a marker pointing into one.
print-escape-multibyte [Variable]
If this variable is non-nil, then multibyte non-ASCII characters in strings are un-
conditionally printed as backslash sequences by the print functions prin1 and print
that print with quoting.
Those functions also use backslash sequences for multibyte non-ASCII characters,
regardless of the value of this variable, when the output stream is a unibyte buffer or
a marker pointing into one.
Chapter 20: Reading and Printing Lisp Objects 362
print-charset-text-property [Variable]
This variable controls printing of ‘charset’ text property on printing a string. The
value should be nil, t, or default.
If the value is nil, charset text properties are never printed. If t, they are always
printed.
If the value is default, only print charset text properties if there is an “unexpected”
charset property. For ascii characters, all charsets are considered “expected”. Oth-
erwise, the expected charset property of a character is given by char-charset.
print-length [Variable]
The value of this variable is the maximum number of elements to print in any list,
vector or bool-vector. If an object being printed has more than this many elements,
it is abbreviated with an ellipsis.
If the value is nil (the default), then there is no limit.
(setq print-length 2)
⇒ 2
(print '(1 2 3 4 5))
a (1 2 ...)
⇒ (1 2 ...)
print-level [Variable]
The value of this variable is the maximum depth of nesting of parentheses and brackets
when printed. Any list or vector at a depth exceeding this limit is abbreviated with
an ellipsis. A value of nil (which is the default) means no limit.
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.6 [Circular Objects], page 29.
print-gensym [Variable]
If non-nil, this variable enables detection of uninterned symbols (see Section 9.3
[Creating Symbols], page 132) 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.
Chapter 20: Reading and Printing Lisp Objects 363
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.
print-integers-as-characters [Variable]
When this variable is non-nil, integers that represent graphic base characters will be
printed using Lisp character syntax (see Section 2.4.3.1 [Basic Char Syntax], page 11).
Other numbers are printed the usual way. For example, the list (4 65 -1 10) would
be printed as ‘(4 ?A -1 ?\n)’.
More precisely, values printed in character syntax are those representing characters
belonging to the Unicode general categories Letter, Number, Punctuation, Symbol
and Private-use (see Section 34.6 [Character Properties], page 905), as well as the
control characters having their own escape syntax such as newline.
364
21 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 40.4 [The Echo Area], page 1039),
but only while it is in use for reading an argument.
Like other buffers, a minibuffer uses a local keymap (see Chapter 23 [Keymaps], page 451)
to specify special key bindings. The function that invokes the minibuffer also sets up its
local map according to the job to be done. See Section 21.2 [Text from Minibuffer], page 365,
for the non-completion minibuffer local maps. See Section 21.6.3 [Completion Commands],
page 378, for the minibuffer local maps for completion.
An active minibuffer usually has major mode minibuffer-mode. This is an Emacs
internal mode without any special features. To customize the setup of minibuffers, we
suggest you use minibuffer-setup-hook (see Section 21.15 [Minibuffer Misc], page 399)
rather than minibuffer-mode-hook, since the former is run later, after the minibuffer has
been fully initialized.
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 30.9 [Minibuffers and Frames], page 774.
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.
If read is non-nil, then default is also used as the input to read, if the user enters
empty input. If default is a list of strings, the first string is used as the input. If
default is nil, empty input results in an end-of-file error. However, in the usual
case (where read is nil), read-from-minibuffer ignores default when the user enters
empty input and returns an empty string, "". In this respect, it differs from all the
other minibuffer input functions in this chapter.
If keymap is non-nil, that keymap is the local keymap to use in the minibuffer.
If keymap is omitted or nil, the value of minibuffer-local-map is used as the
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. If
history is the symbol t, history is not recorded. You can optionally specify a starting
position in the history list as well. See Section 21.4 [Minibuffer History], page 371.
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 34.11 [Input Methods], page 927) and the setting of
enable-multibyte-characters (see Section 34.1 [Text Representations], page 900)
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 21.5 [Initial Input],
page 373.
See read-regexp above for details of how these values are used.
minibuffer-allow-text-properties [Variable]
If this variable is nil, then read-from-minibuffer and read-string strip all text
properties from the minibuffer input before returning it. However, read-no-blanks-
input (see below), as well as read-minibuffer and related functions (see Section 21.3
[Reading Lisp Objects With the Minibuffer], page 370), and all functions that do mini-
buffer input with completion, remove the face property unconditionally, regardless
of the value of this variable.
If this variable is non-nil, most text properties on strings from the completion table
are preserved—but only on the part of the strings that were completed.
(let ((minibuffer-allow-text-properties t))
(completing-read "String: " (list (propertize "foobar" 'data 'zot))))
=> #("foobar" 3 6 (data zot))
In this example, the user typed ‘foo’ and then hit the TAB key, so the text properties
are only preserved on the last three characters.
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
M-< minibuffer-beginning-of-buffer
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
read-minibuffer-restore-windows [Variable]
If this option is non-nil (the default), getting input from the minibuffer will restore,
on exit, the window configurations of the frame where the minibuffer was entered
from and, if it is different, the frame that owns the minibuffer window. This means
that if, for example, a user splits a window while getting input from the minibuffer
on the same frame, that split will be undone when exiting the minibuffer.
If this option is nil, no such restorations are done. Hence, the window split mentioned
above will persist after exiting the minibuffer.
Chapter 21: Minibuffers 370
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.
history-length [User Option]
The value of this variable specifies the maximum length for all history lists that
don’t specify their own maximum lengths. If the value is t, that means there is no
maximum (don’t delete old elements). If a history list variable’s symbol has a non-nil
history-length property, it overrides this variable for that particular history list.
history-delete-duplicates [User Option]
If the value of this variable is t, that means when adding a new history element, all
previous identical elements are deleted.
Here are some of the standard minibuffer history list variables:
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.
custom-variable-history [Variable]
A history list for variable-name arguments read by read-variable.
read-number-history [Variable]
A history list for numbers read by read-number.
goto-line-history [Variable]
A history list for arguments to goto-line. This variable can be made local in every
buffer by customizing the user option goto-line-history-local.
Chapter 21: Minibuffers 373
21.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". try-completion is not affected by nontrivial boundaries; e.g.,
try-completion on "/usr/sh" might still return "/usr/share/", not "share/".
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 208.
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 21.6.5 [Reading File Names], page 382);
within read-buffer, it is overridden by read-buffer-completion-ignore-case
(see Section 21.6.4 [High-Level Completion], page 380).
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 35.2 [Searching and Case], page 932) 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 21.6.1 [Basic Com-
pletion], page 373) used for completion in the minibuffer. This is the buffer-local
variable that contains what completing-read passes to try-completion. It is used
by minibuffer completion commands such as minibuffer-complete.
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 exiting the mini-
buffer; completing-read sets 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
Chapter 21: Minibuffers 379
confirm-after-completion, the user may exit with an input that is not a valid
completion alternative, but Emacs asks for confirmation 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 36 [Syntax Tables], page 958.
minibuffer-complete [Command]
This function completes the minibuffer contents as far as possible.
minibuffer-complete-and-exit [Command]
This function completes the minibuffer contents, and exits if confirmation is not
required, i.e., if minibuffer-completion-confirm is nil. If confirmation is required,
it is given by repeating this command immediately—the command is programmed to
work without confirmation when run twice in succession.
minibuffer-completion-help [Command]
This function creates a list of the possible completions of the current minibuffer
contents. It works by calling all-completions using the value of the variable
minibuffer-completion-table as the collection argument, and the value of
minibuffer-completion-predicate as the predicate argument. The list of
completions is displayed as text in a buffer named *Completions*.
minibuffer-local-completion-map [Variable]
completing-read uses this value as the local keymap when an exact match of one
of the completions is not required. By default, this keymap makes the following
bindings:
? minibuffer-completion-help
SPC minibuffer-complete-word
TAB minibuffer-complete
and uses minibuffer-local-map as its parent keymap (see [Definition of minibuffer-
local-map], page 368).
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.
minibuffer-beginning-of-buffer-movement [Variable]
If non-nil, the M-< command will move to the end of the prompt if point is after the
end of the prompt. If point is at or before the end of the prompt, move to the start of
the buffer. If this variable is nil, the command behaves like beginning-of-buffer.
strings, or a buffer. If it is a list, the default value is the first element of this list. It
is mentioned in the prompt, but is not inserted in the minibuffer as initial input.
The argument prompt should be a string ending with a colon and a space. If default
is non-nil, the function inserts it in prompt before the colon to follow the convention
for reading from the minibuffer with a default value (see Section D.3 [Programming
Tips], page 1230).
The optional argument require-match has the same meaning as in completing-read.
See Section 21.6.2 [Minibuffer Completion], page 376.
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 21.6.2 [Minibuffer Completion], page 376.
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.
Chapter 21: Minibuffers 384
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:
(read-file-name "The file is ")
case, the default directory is still used for completion of relative file names, but is not
displayed.
If this variable is nil and the initial minibuffer contents are empty, the user may have
to explicitly fetch the next history element to access a default value. If the variable
is non-nil, the initial minibuffer contents are always non-empty and the user can
always request a default value by immediately typing RET in an unedited minibuffer.
(See above.)
For example:
;; Here the minibuffer starts out with the default directory.
(let ((insert-default-directory t))
(read-file-name "The file is "))
minibuffer-local-shell-command-map [Variable]
This keymap is used by read-shell-command for completing command and file names
that are part of a shell command. It uses minibuffer-local-map as its parent
keymap, and binds TAB to completion-at-point.
completion-styles-alist [Variable]
This variable stores a list of available completion styles. Each element in the list has
the form
(style try-completion all-completions doc)
Here, style is the name of the completion style (a symbol), which may be used in the
completion-styles variable to refer to this style; try-completion is the function that
does the completion; all-completions is the function that lists the completions; and
doc is a string describing the completion style.
The try-completion and all-completions functions should each accept four arguments:
string, collection, predicate, and point. The string, collection, and predicate ar-
guments have the same meanings as in try-completion (see Section 21.6.1 [Basic
Completion], page 373), and the point argument is the position of point within string.
Each function should return a non-nil value if it performed its job, and nil if it did
not (e.g., if there is no way to complete string according to the completion style).
When the user calls a completion command like minibuffer-complete (see
Section 21.6.3 [Completion Commands], page 378), Emacs looks for the first
style listed in completion-styles and calls its try-completion function. If this
function returns nil, Emacs moves to the next listed completion style and calls
its try-completion function, and so on until one of the try-completion functions
successfully performs completion and returns a non-nil value. A similar procedure
is used for listing completions, via the all-completions functions.
See Section “Completion Styles” in The GNU Emacs Manual, for a description of the
available completion styles.
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.
Unless this function puts own face on the annotation suffix string, the
completions-annotations face is added by default to that string.
:affixation-function
The value should be a function to add prefixes and suffixes to completions.
This function must accept one argument, a list of completions, and should
return a list of annotated completions. Each element of the returned list
must be a three-element list, the completion, a prefix string, and a suffix
string. This function takes priority over :annotation-function.
: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.
unique and exact match; and it should return the longest common prefix
substring of all matches otherwise.
t This specifies an all-completions operation. The function should return
a list of all possible completions of the specified string.
lambda This specifies a test-completion operation. The function should return
t if the specified string is an exact match for some completion alternative;
nil otherwise.
(boundaries . suffix)
This specifies a completion-boundaries operation. The function should
return (boundaries start . end), where start is the position of the be-
ginning boundary in the specified string, and end is the position of the end
boundary in suffix.
If a Lisp program returns nontrivial boundaries, it should make sure that
the all-completions operation is consistent with them. The completions
returned by all-completions should only pertain to the piece of the prefix
and suffix covered by the completion boundaries. See Section 21.6.1 [Basic
Completion], page 373, for the precise expected semantics of completion
boundaries.
metadata This specifies a request for information about the state of the current com-
pletion. The return value should have the form (metadata . alist), where
alist is an alist whose elements are described below.
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 21.6.6 [Completion Variables], page 385.
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. Unless this function puts own face on the annotation suffix string, the
completions-annotations face is added by default to that string.
affixation-function
The value should be a function for adding prefixes and suffixes to completions.
The function should take one argument, completions, which is a list of possible
completions. It should return such a list of completions where each element
contains a list of three elements: a completion, a prefix which is displayed before
the completion string in the *Completions* buffer, and a suffix displayed after
the completion string. This function takes priority over annotation-function.
Chapter 21: Minibuffers 389
group-function
The value should be a function for grouping the completion candidates. The
function must take two arguments, completion, which is a completion candidate
and transform, which is a boolean flag. If transform is nil, the function must
return the group title of the group to which the candidate belongs. The returned
title can also be nil. Otherwise the function must return the transformed
candidate. The transformation can for example remove a redundant prefix,
which is displayed in the group title.
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.
“Symbol Completion” in The GNU Emacs Manual. This command uses the abnormal hook
variable completion-at-point-functions:
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 21.6.1 [Basic Completion], page 373) for
completing the text at point. It can be used by major modes to provide mode-specific
completion tables (see Section 24.2.1 [Major Mode Conventions], page 494).
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 21.6.1 [Basic Completion], page 373);
completion alternatives will be generated from this completion table in the usual way,
via the completion styles defined in completion-styles (see Section 21.6.6 [Comple-
tion Variables], page 385). props is a property list for additional information; any of
the properties in completion-extra-properties are recognized (see Section 21.6.6
[Completion Variables], page 385), 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))
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.
something that quits), the function responds ‘Please answer y or n.’, and repeats
the request.
This function actually uses the minibuffer, but does not allow editing of the answer.
The cursor moves to the minibuffer 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 35.7 [Search and Replace],
page 953). 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.
If you bind help-form (see Section 25.6 [Help Functions], page 558) to a non-nil value
while calling y-or-n-p, then pressing help-char causes it to evaluate help-form and
display the result. help-char is automatically added to prompt.
If the user first types y RET, which is invalid because this function demands the entire
word ‘yes’, it responds by displaying these prompts, with a brief pause between them:
---------- Buffer: minibuffer ----------
Please answer yes or no.
Do you really want to remove everything? (yes or no)
---------- Buffer: minibuffer ----------
Chapter 21: Minibuffers 393
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. The command throws an error if the current buffer is a minibuffer,
but not the active minibuffer.
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 22.5 [Command Loop Info],
page 413).
Chapter 21: Minibuffers 396
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. The position in the history can go beyond the current position and
invoke “future history” (see Section 21.2 [Text from Minibuffer], page 365).
previous-matching-history-element pattern n [Command]
This command replaces the minibuffer contents with the value of the nth previous
(older) history element that matches pattern (a regular expression).
next-matching-history-element pattern n [Command]
This command replaces the minibuffer contents with the value of the nth next (newer)
history element that matches pattern (a regular expression).
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.
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.
goto-history-element nabs [Command]
This function puts element of the minibuffer history in the minibuffer. The argument
nabs specifies the absolute history position in descending order, where 0 means the
current element and a positive number n means the nth previous element. NABS
being a negative number -n means the nth entry of “future history.”
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.
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 40.4.4 [Echo Area Customization], page 1045).
The option resize-mini-windows does not affect the behavior of minibuffer-only frames
(see Section 30.3.1 [Frame Layout], page 742). The following option allows to automatically
resize such frames as well.
window of that frame is the buffer whose contents will be shown the next time that
window is redisplayed. The function is expected to fit the frame to the buffer in some
appropriate way.
Any other non-nil value means to resize minibuffer-only frames by calling
fit-mini-frame-to-buffer, a function that behaves like fit-frame-to-buffer
(see Section 29.5 [Resizing Windows], page 657) but does not strip leading or trailing
empty lines from the buffer text.
minibuffer-prompt [Function]
This function returns the prompt string of the currently active minibuffer. If no
minibuffer is active, it returns nil.
minibuffer-prompt-end [Function]
This function returns the current position of the end of the minibuffer prompt, if a
minibuffer is current. Otherwise, it returns the minimum valid buffer position.
minibuffer-prompt-width [Function]
This function returns the current display-width of the minibuffer prompt, if a mini-
buffer is current. Otherwise, it returns zero.
minibuffer-contents [Function]
This function returns the editable contents of the minibuffer (that is, everything
except the prompt) as a string, if a minibuffer is current. Otherwise, it returns the
entire contents of the current buffer.
minibuffer-contents-no-properties [Function]
This is like minibuffer-contents, except that it does not copy text properties, just
the characters themselves. See Section 33.19 [Text Properties], page 858.
delete-minibuffer-contents [Command]
This command erases the editable contents of the minibuffer (that is, everything
except the prompt), if a minibuffer is current. Otherwise, it erases the entire current
buffer.
minibuffer-depth [Function]
This function returns the current depth of activations of the minibuffer, a nonnegative
integer. If no minibuffers are active, it returns zero.
editing level for a new minibuffer. By default, the outer-level minibuffer is invisible
while you are editing the inner one. If you have minibuffer-follows-selected-
frame set to nil, you can have minibuffers visible on several frames at the same
time. See Section “Basic Minibuffer” in emacs.
If this variable is nil, you cannot invoke minibuffer commands when the minibuffer
is active, not even if you switch to another window to do it.
minibuffer-setup-hook [Variable]
This is a normal hook that is run whenever a minibuffer is entered. See Section 24.1
[Hooks], page 490.
Chapter 21: Minibuffers 400
minibuffer-exit-hook [Variable]
This is a normal hook that is run whenever a minibuffer is exited. See Section 24.1
[Hooks], page 490.
minibuffer-help-form [Variable]
The current value of this variable is used to rebind help-form locally inside the
minibuffer (see Section 25.6 [Help Functions], page 558).
minibuffer-scroll-window [Variable]
If the value of this variable is non-nil, it should be a window object. When the
function scroll-other-window is called in the minibuffer, it scrolls this window (see
Section 29.21 [Textual Scrolling], page 714).
minibuffer-selected-window [Function]
This function returns the window that was selected just before the minibuffer window
was selected. If the selected window is not a minibuffer window, it returns nil.
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 30.9 [Minibuffers and Frames], page 774.
401
22 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.
The modes list allows specifying which modes the command is meant to be used in.
See Section 22.2.4 [Command Modes], page 408, for more details about the effect of
specifying modes, and when to use it.
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.
• It may be a Lisp expression that is not a string; then it should be a form that is
evaluated to get a list of arguments to pass to the command. Usually this form will
call various functions to read input from the user, most often through the minibuffer
(see Chapter 21 [Minibuffers], page 364) or directly from the keyboard (see Section 22.8
[Reading Input], page 432).
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).
Default A default value of some sort is used if the user enters no text in the minibuffer.
The default depends on the code character.
No I/O This code letter computes an argument without reading any input. Therefore,
it does not use a prompt string, and any prompt string you supply is ignored.
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 28 [Buffers], page 626). 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 31.1 [Point], page 797). No
I/O.
‘D’ A directory. The default is the current default directory of the current buffer,
default-directory (see Section 26.9.4 [File Name Expansion], page 594). 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 22.7 [Input Events], page 416. No I/O.
You use ‘e’ for mouse events and for special system events (see Section 22.7.10
[Misc Events], page 424). The event list that the command receives depends on
the event. See Section 22.7 [Input Events], page 416, which describes the forms
of the list for each event in the corresponding subsections.
Chapter 22: Command Loop 406
You can use ‘e’ more than once in a single command’s interactive specification.
If the key sequence that invoked the command has n events that are lists, the
nth ‘e’ provides the nth such event. Events that are not lists, such as function
keys and ASCII characters, do not count where ‘e’ is concerned.
‘f’ A file name of an existing file (see Section 26.9 [File Names], page 590). 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 23.1 [Key Sequences], page 451). 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 on a form that can be used as input to functions like
define-key. 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 (see Section 22.8.1
[Key Sequence Input], page 432), so this form is usually used when prompting
for a new key sequence that is to be bound to a command.
‘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 22.12 [Prefix Command
Arguments], page 444. 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
Chapter 22: Command Loop 407
(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 30.2 [Multiple Terminals], page 738.
real-last-command [Variable]
This variable is set up by Emacs just like last-command, but never altered by Lisp
programs.
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
Chapter 22: Command Loop 414
kill-region so that any kill commands immediately following will know to append
the killed text to the previous kill.
this-original-command [Variable]
This has the same value as this-command except when command remapping occurs
(see Section 23.13 [Remapping Commands], page 469). 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.
current-minibuffer-command [Variable]
This has the same value as this-command, but is bound recursively when entering a
minibuffer. This variable can be used from minibuffer hooks and the like to determine
what command opened the current minibuffer session.
this-command-keys [Function]
This function returns a string or vector containing the key sequence that invoked the
present 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 22.8.1 [Key Sequence Input], page 432. The value is a string if
all events in the sequence were characters that fit in a string. See Section 22.7 [Input
Events], page 416.
(this-command-keys)
;; Now use C-u C-x C-e to evaluate that.
⇒ "^X^E"
this-command-keys-vector [Function]
Like this-command-keys, except that it always returns the events in a vector, so
you don’t need to deal with the complexities of storing input events in a string (see
Section 22.7.15 [Strings of Events], page 431).
(see Section 41.13.2 [Recording Input], page 1184) 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 21.7 [Yes-or-No Queries], page 391).
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 30.10 [Input Focus], page 774.
If the last event came from a keyboard macro, the value is macro.
disable-point-adjustment [Variable]
If this variable is non-nil when a command returns to the command loop, then the
command loop does not check for those text properties, and does not move point out
of sequences that have them.
The command loop sets this variable to nil before each command, so if a command
sets it, the effect applies only to that command.
global-disable-point-adjustment [Variable]
If you set this variable to a non-nil value, the feature of moving point out of these
sequences is completely turned off.
Chapter 22: Command Loop 416
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 22.7.12 [Classifying
Events], page 426). 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 23.12
[Changing Key Bindings], page 466). The function event-convert-list converts such a
list into an event type (see Section 22.7.12 [Classifying Events], page 426).
You can use the modifier keys ALT, CTRL, HYPER, META, SHIFT, and SUPER with function
keys. The way to represent them is with prefixes in the symbol name:
‘A-’ The alt modifier.
‘C-’ The control modifier.
‘H-’ The hyper modifier.
‘M-’ The meta modifier.
‘S-’ The shift modifier.
‘s-’ The super modifier.
Thus, the symbol for the key F3 with META held down is M-f3. When you use more than
one prefix, we recommend you write them in alphabetical order; but the order does not
matter in arguments to the key-binding lookup and modification functions.
click-count
This is the number of rapid repeated presses so far of the same mouse button or
the number of repeated turns of the wheel. See Section 22.7.7 [Repeat Events],
page 422.
To access the contents of a mouse position list in the position slot of a mouse event,
you should typically use the functions documented in Section 22.7.13 [Accessing Mouse],
page 428.
The explicit format of the list depends on where the event occurred. For clicks in the
text area, mode line, header line, tab 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 mouse event occurred.
pos-or-area
The buffer position of the character clicked on in the text area; or, if the event
was outside the text area, the window area where it occurred. It is one of the
symbols mode-line, header-line, tab-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 22.8.1 [Key Sequence
Input], page 432.
x, y The relative pixel coordinates of the event. For events 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 29.4 [Window Sizes], page 652. For events in a mode
line, header line or tab 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 event 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 event position.
string The string which was clicked on, including any properties.
string-pos The position in the string where the click occurred.
text-pos For clicks on a marginal area or on a fringe, this is the buffer position of the
first visible character in the corresponding line in the window. For clicks on the
Chapter 22: Command Loop 420
mode line, the header line or the tab line, this is nil. For other events, it is
the buffer position closest to the click.
col, row These are the actual column and row coordinate numbers of the glyph under
the x, y position. If x lies beyond the last column of actual text on its line, col
is reported by adding fictional extra columns that have the default character
width. Row 0 is taken to be the header line if the window has one, or Row 1 if
the window also has the tab line, or the topmost row of the text area otherwise.
Column 0 is taken to be the leftmost column of the text area for clicks on a
window text area, or the leftmost mode line or header line column for clicks
there. For clicks on fringes or vertical borders, these have no meaningful data.
For clicks on margins, col is measured from the left edge of the margin area and
row is measured from the top of the margin area.
image If there is an image at the click location, this is the image object as returned by
find-image (see Section 40.17.8 [Defining Images], page 1123); otherwise this
is nil.
dx, dy These are the pixel coordinates of the click, relative to the top left corner
of object, which is (0 . 0). If object is nil, which stands for a buffer, the
coordinates are relative to the top left corner of the character glyph clicked on.
width, height
If the click is on a character, either from buffer text or from overlay or display
string, these are the pixel width and height of that character’s glyph; otherwise
they are dimensions of object clicked on.
For clicks on a scroll bar, position has this form:
(window area (portion . whole) timestamp part)
window The window whose scroll bar was clicked on.
area This is the symbol vertical-scroll-bar.
portion The number of pixels from the top of the scroll bar to the click position. On
some toolkits, including GTK+, Emacs cannot extract this data, so the value
is always 0.
whole The total length, in pixels, of the scroll bar. On some toolkits, including GTK+,
Emacs cannot extract this data, so the value is always 0.
timestamp
The time at which the event occurred, in milliseconds. On some toolkits, in-
cluding GTK+, Emacs cannot extract this data, so the value is always 0.
part The part of the scroll bar on which the click occurred. It is one of the symbols
handle (the scroll bar handle), above-handle (the area above the handle),
below-handle (the area below the handle), up (the up arrow at one end of the
scroll bar), or down (the down arrow at one end of the scroll bar).
For clicks on the frame’s internal border (see Section 30.3.1 [Frame Layout], page 742),
the frame’s tool bar (see Section 23.17.6 [Tool Bar], page 483) or tab bar, position has this
form:
Chapter 22: Command Loop 421
2
Button-down is the conservative antithesis of drag.
Chapter 22: Command Loop 423
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.
event-click-count event [Function]
This function returns the number of consecutive button presses that led up to event.
If event is a double-down, double-click or double-drag event, the value is 2. If event
is a triple event, the value is 3 or greater. If event is an ordinary mouse event (not a
repeat event), the value is 1.
double-click-fuzz [User Option]
To generate repeat events, successive mouse button presses must be at approximately
the same screen position. The value of double-click-fuzz specifies the maximum
number of pixels the mouse may be moved (horizontally or vertically) between two
successive clicks to make a double-click.
This variable is also the threshold for motion of the mouse to count as a drag.
double-click-time [User Option]
To generate repeat events, the number of milliseconds between successive button
presses must be less than the value of double-click-time. Setting double-click-
time to nil disables multi-click detection entirely. Setting it to t removes the time
limit; Emacs then detects multi-clicks by position only.
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 34.10
[Coding Systems], page 913) 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
Chapter 22: Command Loop 426
(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.
Some of these special events, such as delete-frame, invoke Emacs commands by default;
others are not bound. If you want to arrange for a special event to invoke a command, you
can do that via special-event-map. The command you bind to a function key in that map
can then examine the full event which invoked it in last-input-event. See Section 22.9
[Special Events], page 441.
events that are lists, the event type is the symbol in the car of the list. Thus, the event
type is always a symbol or a character.
Two events of the same type are equivalent where key bindings are concerned; thus, they
always run the same command. That does not necessarily mean they do the same things,
however, as some commands look at the whole event to decide what to do. For example,
some commands use the location of a mouse event to decide where in the buffer to act.
Sometimes broader classifications of events are useful. For example, you might want to
ask whether an event involved the META key, regardless of which other key or mouse button
was used.
The functions event-modifiers and event-basic-type are provided to get such infor-
mation conveniently.
event-modifiers event [Function]
This function returns a list of the modifiers that event has. The modifiers are symbols;
they include shift, control, meta, alt, hyper and super. In addition, the modifiers
list of a mouse event symbol always contains one of click, drag, and down. For double
or triple events, it also contains double or triple.
The argument event may be an entire event object, or just an event type. If event
is a symbol that has never been used in an event that has been read as input in
the current Emacs session, then event-modifiers can return nil, even when event
actually has modifiers.
Here are some examples:
(event-modifiers ?a)
⇒ nil
(event-modifiers ?A)
⇒ (shift)
(event-modifiers ?\C-a)
⇒ (control)
(event-modifiers ?\C-%)
⇒ (control)
(event-modifiers ?\C-\S-a)
⇒ (control shift)
(event-modifiers 'f5)
⇒ nil
(event-modifiers 's-f5)
⇒ (super)
(event-modifiers 'M-S-f5)
⇒ (meta shift)
(event-modifiers 'mouse-1)
⇒ (click)
(event-modifiers 'down-mouse-1)
⇒ (down)
The modifiers list for a click event explicitly contains click, but the event symbol
name itself does not contain ‘click’. 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.
Chapter 22: Command Loop 428
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.
window. The coordinates x and y are relative to the text area of the selected window.
If whole is non-nil, the x coordinate is relative to the entire window area including
scroll bars, margins and fringes.
The earliest GNU Emacs versions represented meta characters as codes in the range of
128 to 255. At that time, the basic character codes ranged from 0 to 127, so all keyboard
character codes did fit in a string. Many Lisp programs used ‘\M-’ in string constants to
stand for meta characters, especially in arguments to define-key and similar functions,
and key sequences and sequences of events were always represented as strings.
When we added support for larger basic character codes beyond 127, and additional
modifier bits, we had to change the representation of meta characters. Now the flag that
represents the Meta modifier in a character is 227 and such numbers cannot be included in
a string.
To support programs with ‘\M-’ in string constants, there are special rules for including
certain meta characters in a string. Here are the rules for interpreting a string as a sequence
of input characters:
• If the keyboard character value is in the range of 0 to 127, it can go in the string
unchanged.
• The meta variants of those characters, with codes in the range of 227 to 227 + 127, can
also go in the string, but you must change their numeric values. You must set the 27
bit instead of the 227 bit, resulting in a value between 128 and 255. Only a unibyte
string can include these codes.
• Non-ASCII characters above 256 can be included in a multibyte string.
• Other keyboard character events cannot fit in a string. This includes keyboard events
in the range of 128 to 255.
Functions such as read-key-sequence that construct strings of keyboard input charac-
ters follow these rules: they construct vectors instead of strings, when the events won’t fit
in a string.
When you use the read syntax ‘\M-’ in a string, it produces a code in the range of 128
to 255—the same code that you get if you modify the corresponding keyboard event to put
it in the string. Thus, meta events in strings work consistently regardless of how they get
into the strings.
However, most programs would do well to avoid these issues by following the recommen-
dations at the beginning of this section.
⇒ "^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 22.11 [Quitting], page 443.
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 32.7 [The Mark], page 815).
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 or frame, such as a mode
line or a scroll bar, the event type shows nothing special—it is the same symbol that
would normally represent that combination of mouse button and modifier keys. The
information about the window part is kept elsewhere in the event—in the coordinates. But
read-key-sequence translates this information into imaginary prefix keys, all of which
are symbols: tab-line, header-line, horizontal-scroll-bar, menu-bar, tab-bar,
mode-line, vertical-line, vertical-scroll-bar, left-margin, right-margin,
left-fringe, right-fringe, right-divider, and bottom-divider. You can define
meanings for mouse clicks in special window parts by defining key sequences using these
imaginary prefix keys.
For example, if you call read-key-sequence and then click the mouse on the window’s
mode line, you get two events, like this:
(read-key-sequence "Click on the mode line: ")
⇒ [mode-line
(mouse-1
(#<window 6 on NEWS> mode-line
(40 . 63) 5959987))]
num-input-keys [Variable]
This variable’s value is the number of key sequences processed so far in this Emacs
session. This includes key sequences read from the terminal and key sequences read
from keyboard macros being executed.
If the optional argument prompt is non-nil, it should be a string to display in the echo
area as a prompt. If prompt is nil or the string ‘""’, read-event does not display
any message to indicate it is waiting for input; instead, it prompts by echoing: it
displays descriptions of the events that led to or were read by the current command.
See Section 40.4 [The Echo Area], page 1039.
If inherit-input-method is non-nil, then the current input method (if any) is employed
to make it possible to enter a non-ASCII character. Otherwise, input method handling
is disabled for reading this event.
If cursor-in-echo-area is non-nil, then read-event moves the cursor temporarily
to the echo area, to the end of any message displayed there. Otherwise read-event
does not move the cursor.
If seconds is non-nil, it should be a number specifying the maximum time to wait
for input, in seconds. If no input arrives within that time, read-event stops waiting
and returns nil. A floating point seconds means to wait for a fractional number of
seconds. Some systems support only a whole number of seconds; on these systems,
seconds is rounded down. If seconds is nil, read-event waits as long as necessary
for input to arrive.
If seconds is nil, Emacs is considered idle while waiting for user input to arrive. Idle
timers—those created with run-with-idle-timer (see Section 41.12 [Idle Timers],
page 1181)—can run during this period. However, if seconds is non-nil, the state
of idleness remains unchanged. If Emacs is non-idle when read-event is called, it
remains non-idle throughout the operation of read-event; if Emacs is idle (which
can happen if the call happens inside an idle timer), it remains idle.
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 25.6 [Help
Functions], page 558. Certain other events, called special events, are also processed
directly within read-event (see Section 22.9 [Special Events], page 441).
Here is what happens if you call read-event and then press the right-arrow function
key:
(read-event)
⇒ right
read-char &optional prompt inherit-input-method seconds [Function]
This function reads and returns a character input event. If the user generates an
event which is not a character (i.e., a mouse click or function key event), read-char
signals an error. The arguments work as in read-event.
If the event has modifiers, Emacs attempts to resolve them and return the code of
the corresponding character. For example, if the user types C-a, the function returns
1, which is the ASCII code of the ‘C-a’ character. If some of the modifiers cannot
be reflected in the character code, read-char leaves the unresolved modifier bits
set in the returned event. For example, if the user types C-M-a, the function returns
134217729, 8000001 in hex, i.e. ‘C-a’ with the Meta modifier bit set. This value is not a
valid character code: it fails the characterp test (see Section 34.5 [Character Codes],
page 904). Use event-basic-type (see Section 22.7.12 [Classifying Events], page 426)
to recover the character code with the modifier bits removed; use event-modifiers
to test for modifiers in the character event returned by read-char.
Chapter 22: Command Loop 436
In the first example below, the user types the character 1 (ASCII code 49). The second
example shows a keyboard macro definition that calls read-char from the minibuffer
using eval-expression. read-char reads the keyboard macro’s very next character,
which is 1. Then eval-expression displays its return value in the echo area.
(read-char)
⇒ 49
num-nonmacro-input-events [Variable]
This variable holds the total number of input events received so far from the
terminal—not counting those generated by keyboard macros.
extra-keyboard-modifiers [Variable]
This variable lets Lisp programs “press” the modifier keys on the keyboard. The
value is a character. Only the modifiers of the character matter. Each time the user
types a keyboard key, it is altered as if those modifier keys were held down. For
instance, if you bind extra-keyboard-modifiers to ?\C-\M-a, then all keyboard
input characters typed during the scope of the binding will have the control and meta
modifiers applied to them. The character ?\C-@, equivalent to the integer 0, does not
count as a control character for this purpose, but as a character with no modifiers.
Thus, setting extra-keyboard-modifiers to zero cancels any modification.
When using a window system, the program can press any of the modifier keys in this
way. Otherwise, only the CTL and META keys can be virtually pressed.
Note that this variable applies only to events that really come from the keyboard,
and has no effect on mouse events or any other events.
Chapter 22: Command Loop 438
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 115), 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 34.11 [Input Methods], page 927). Use translation-table-
for-input (see Section 34.9 [Translation of Characters], page 912), if you want to
translate characters after input methods operate.
Here’s an example of using the keyboard-translate-table to make C-x, C-c and C-v
perform the cut, copy and paste operations:
(keyboard-translate ?\C-x 'control-x)
(keyboard-translate ?\C-c 'control-c)
(keyboard-translate ?\C-v 'control-v)
(global-set-key [control-x] 'kill-region)
(global-set-key [control-c] 'kill-ring-save)
(global-set-key [control-v] 'yank)
On a graphical terminal that supports extended ASCII input, you can still get the standard
Emacs meanings of one of those characters by typing it with the shift key. That makes it
a different character as far as keyboard translation is concerned, but it has the same usual
meaning.
See Section 23.14 [Translation Keymaps], page 470, 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
Chapter 22: Command Loop 439
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 22.8.6
[Event Input Misc], page 440). 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.
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.
Quitting is suppressed when the first character is read, so that the user can enter a
C-g. See Section 22.11 [Quitting], page 443.
If prompt is supplied, it specifies a string for prompting the user. The prompt string
is always displayed in the echo area, followed by a single ‘-’.
In the following example, the user types in the octal number 177 (which is 127 in
decimal).
⇒ 127
Chapter 22: Command Loop 440
unread-command-events [Variable]
This variable holds a list of events waiting to be read as command input. The events
are used in the order they appear in the list, and removed one by one as they are
used.
The variable is needed because in some cases a function reads an event and then
decides not to use it. Storing the event in this variable causes it to be processed
normally, by the command loop or by the functions to read command input.
For example, the function that implements numeric prefix arguments reads any num-
ber of digits. When it finds a non-digit event, it must unread the event so that it
can be read normally by the command loop. Likewise, incremental search uses this
feature to unread events with no special meaning in a search, because these events
should exit the search and then execute normally.
The reliable and easy way to extract events from a key sequence so as to put them in
unread-command-events is to use listify-key-sequence (see below).
Normally you add events to the front of this list, so that the events most recently
unread will be reread first.
Events read from this list are not normally added to the current command’s key se-
quence (as returned by, e.g., this-command-keys), as the events will already have
been added once as they were read for the first time. An element of the form
(t . event) forces event to be added to the current command’s key sequence.
Elements read from this list are normally recorded by the record-keeping features (see
Section 41.13.2 [Recording Input], page 1184) and while defining a keyboard macro
(see Section 22.16 [Keyboard Macros], page 449). However, an element of the form
(no-record . event) causes event to be processed normally without recording it.
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.
Chapter 22: Command Loop 441
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 event symbols (see Section 22.7.11 [Event Examples], page 426).
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
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 23.9 [Controlling Active Maps], page 460).
See Section 41.5 [Time of Day], page 1168, for functions to get the current time.
Chapter 22: Command Loop 443
22.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)
(while (not done)
(let ((inhibit-quit first)
...)
Chapter 22: Command Loop 444
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 172). 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). Similarly, you can throw a string value to make
recursive-edit signal an error, printing this string as the message. If you throw a function,
recursive-edit will call it without arguments before returning. Throwing any other value,
will make recursive-edit return normally to the function that called it. The command
C-M-c (exit-recursive-edit) does this.
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")
Chapter 22: Command Loop 448
(recursive-edit)
(forward-word 1))
⇒ simple-rec
(simple-rec)
⇒ nil
exit-recursive-edit [Command]
This function exits from the innermost recursive edit (including minibuffer input).
Its definition is effectively (throw 'exit nil).
abort-recursive-edit [Command]
This function aborts the command that requested the innermost recursive edit (includ-
ing minibuffer input), by signaling quit after exiting the recursive edit. Its definition
is effectively (throw 'exit t). See Section 22.11 [Quitting], page 443.
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.
command-history [Variable]
This variable’s value is a list of recent complex commands, each represented as a form
to evaluate. It continues to accumulate all complex commands for the duration of the
editing session, but when it reaches the maximum size (see Section 21.4 [Minibuffer
History], page 371), the oldest elements are deleted as new ones are added.
command-history
⇒ ((switch-to-buffer "chistory.texi")
(describe-key "^X^[")
(visit-tags-table "~/emacs/src/")
(find-tag "repeat-complex-command"))
This history list is actually a special case of minibuffer history (see Section 21.4 [Mini-
buffer History], page 371), with one special twist: the elements are expressions rather than
strings.
There are a number of commands devoted to the editing and recall of previous com-
mands. The commands repeat-complex-command, and list-command-history are de-
scribed in the user manual (see Section “Repetition” in The GNU Emacs Manual). Within
the minibuffer, the usual minibuffer history commands are available.
executing-kbd-macro [Variable]
This variable contains the string or vector that defines the keyboard macro that is
currently executing. It is nil if no macro is currently executing. A command can
test this variable so as to behave differently when run from an executing macro. Do
not set this variable yourself.
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 30.2 [Multiple Terminals], page 738.
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 30.2 [Multiple Terminals], page 738.
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).
451
23 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 22.7.12 [Classifying Events], page 426. In this kind of
binding, binding is a command.
Chapter 23: Keymaps 453
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 115) 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 23: Keymaps 457
(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 23.9 [Controlling Active Maps], page 460, 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 23.14
[Translation Keymaps], page 470.
See Appendix G [Standard Keymaps], page 1291, 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 23.9 [Controlling Active Maps], page 460).
In the above pseudo-code, if a key sequence starts with a mouse event (see Section 22.7.3
[Mouse Events], page 418), 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 33.19.4 [Special Proper-
ties], page 866), 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 23.10 [Key Lookup],
page 463.
The command which is finally found might also be remapped. See Section 23.13 [Remap-
ping Commands], page 469.
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 23: Keymaps 461
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 24.3.2
[Keymaps and Minor Modes], page 512.
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 24.3.2 [Keymaps and Minor Modes], page 512, for more information about
minor modes. See also minor-mode-key-binding (see Section 23.11 [Functions for
Key Lookup], page 464).
Chapter 23: Keymaps 462
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 30.2 [Multiple Terminals], page 738. 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 22.9 [Special Events], page 441.
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 23: Keymaps 463
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 23.8 [Searching Keymaps], page 459).
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 23.3 [Format of
Keymaps], page 452.)
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
The keymap argument can also be a list of keymaps.
Unlike read-key-sequence, this function does not modify the specified events in
ways that discard information (see Section 22.8.1 [Key Sequence Input], page 432).
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.
local-key-binding key &optional accept-defaults [Function]
This function returns the binding for key in the current local keymap, or nil if it is
undefined there.
The argument accept-defaults controls checking for default bindings, as in lookup-key
(above).
global-key-binding key &optional accept-defaults [Function]
This function returns the binding for command key in the current global keymap, or
nil if it is undefined there.
The argument accept-defaults controls checking for default bindings, as in lookup-key
(above).
minor-mode-key-binding key &optional accept-defaults [Function]
This function returns a list of all the active minor mode bindings of key. More
precisely, it returns an alist of pairs (modename . binding), where modename is the
variable that enables the minor mode, and binding is key’s binding in that mode. If
key has no minor-mode bindings, the value is nil.
If the first binding found is not a prefix definition (a keymap or a symbol defined as
a keymap), all subsequent bindings from other minor modes are omitted, since they
would be completely shadowed. Similarly, the list omits non-prefix bindings that
follow prefix bindings.
Chapter 23: Keymaps 466
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 23.1 [Key Sequences], page 451) 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 23.10 [Key Lookup], page 463.) 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 23.17 [Menu
Keymaps], page 475).
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 23.13
[Remapping Commands], page 469).
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 41.1.3 [Terminal-Specific],
page 1158.
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 23: Keymaps 471
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 289), 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 23: Keymaps 473
In the example below, the returned alist indicates that the key ESC, which is dis-
played as ‘^[’, is a prefix key whose definition is the sparse keymap (keymap (83 .
center-paragraph) (115 . foo)).
(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.
Usually it’s best to use overriding-local-map as the expression for keymap. Then
where-is-internal searches precisely the keymaps that are active. To search only
the global map, pass the value (keymap) (an empty keymap) as keymap.
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 23.13 [Remapping Commands], page 469). 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.
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 23.17.7 [Modifying Menus], page 486).
For example:
(menu-item "--" nil :visible (boundp 'foo))
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.
can do that by giving a nested keymap an item string which starts with ‘@’. This causes
Emacs to display the nested keymap using a separate menu pane; the rest of the item string
after the ‘@’ is the pane label. If Emacs is compiled without X toolkit support, or if a menu
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.
event, then the menu items should be bound to characters or real function keys, that can
be typed with the keyboard.
The binding whose definition is ("--") is a separator line. Like a real menu item, the
separator has a key symbol, in this case separator-replace-tags. If one menu has two
separators, they must have two different key symbols.
Here is how we make this menu appear as an item in the parent menu:
(define-key menu-bar-edit-menu [replace]
(list 'menu-item "Replace" menu-bar-replace-menu))
Note that this incorporates the submenu keymap, which is the value of the 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)
A local keymap can cancel a menu bar item made by the global keymap by rebinding
the same fake function key with undefined as the binding. For example, this is how Dired
suppresses the ‘Edit’ menu bar item:
(define-key dired-mode-map [menu-bar edit] 'undefined)
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 25.3 [Keys in Documentation], page 554.
item must be a command, not a keymap; in other words, it does not work to define a tool
bar icon as a prefix key.
The :help property specifies a help-echo string to display while the mouse is on that
item. This is displayed in the same way as help-echo text properties (see [Help display],
page 872).
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 40.17 [Images],
page 1109) 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 23.17.1.3 [Menu
Separators], page 478). 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 24.2.1
[Major Mode Conventions], page 494). 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.
Chapter 23: Keymaps 485
There are two convenience functions for defining tool bar items, as follows.
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.
Chapter 23: Keymaps 486
auto-raise-tool-bar-buttons [Variable]
If this variable is non-nil, tool bar items display in raised form when the mouse
moves over them.
tool-bar-button-margin [Variable]
This variable specifies an extra margin to add around tool bar items. The value is an
integer, a number of pixels. The default is 4.
tool-bar-button-relief [Variable]
This variable specifies the shadow width for tool bar items. The value is an integer,
a number of pixels. The default is 1.
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 22.7.2 [Function Keys], page 417, for more information about how to add
modifiers to function keys.
If you have functions that change whether a tool bar item is enabled or not, this status
is not necessarily updated visually immediately. To force recalculation of the tool bar, call
force-mode-line-update (see Section 24.4 [Mode Line Format], page 515).
Here is an example:
(define-key-after my-menu [drink]
'("Drink" . drink-command) 'eat)
makes a binding for the fake function key DRINK and puts it right after the binding
for EAT.
Here is how to insert an item called ‘Work’ in the ‘Signals’ menu of Shell mode, after
the item break:
(define-key-after shell-mode-map [menu-bar signals work]
'("Work" . work-command) 'break)
where name and callback have the same meanings as above, and each optional key-
word and arg pair should be one of the following:
:keys keys
keys is a string to display as keyboard equivalent to the menu item.
This is normally not needed, as keyboard equivalents are computed au-
tomatically. keys is expanded with substitute-command-keys before it
is displayed (see Section 25.3 [Keys in Documentation], page 554).
:key-sequence keys
keys is a hint indicating which key sequence to display as keyboard equiv-
alent, in case the command is bound to several key sequences. It has no
effect if keys is not bound to same command as this menu item.
:active enable
enable is an expression; if it evaluates to nil, the item is made 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 23.17.1.3 [Menu Separators], page 478).
Alternatively, a menu item can be a list with the same format as menu. This is a
submenu.
'("Words"
["Forward word" forward-word]
["Backward word" backward-word]))
490
24.1 Hooks
A hook is a variable where you can store a function or functions (see Section 13.1 [What
Is a Function], page 221) 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 41.1.2 [Init File], page 1156), but Lisp programs can set them also. See
Appendix H [Standard Hooks], page 1294, 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 41.2.2 [Suspending Emacs], page 1161).
If the hook variable’s name does not end with ‘-hook’, that indicates it is probably
an abnormal hook. These differ from normal hooks in two ways: they can be called with
one or more arguments, and their return values can be used in some way. The hook’s
documentation says how the functions are called and how their return values are used.
Any functions added to an abnormal hook must follow the hook’s calling convention. By
convention, abnormal hook names end in ‘-functions’.
If the name of the variable ends in ‘-predicate’ or ‘-function’ (singular) then its
value must be a function, not a list of functions. As with abnormal hooks, the expected
arguments and meaning of the return value vary across such single function hooks. The
details are explained in each variable’s docstring.
Since hooks (both multi and single function) are variables, their values can be modified
with setq or temporarily with let. However, it is often useful to add or remove a particular
function from a hook while preserving any other functions it might have. For multi func-
tion hooks, the recommended way of doing this is with add-hook and remove-hook (see
Section 24.1.2 [Setting Hooks], page 491). 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. For hooks which hold only a single function, add-hook is not appropriate,
Chapter 24: Major and Minor Modes 491
but you can use add-function (see Section 13.11 [Advising Functions], page 240) to com-
bine new functions with the hook. Note that some single function hooks may be nil which
add-function cannot deal with, so you must check for that before calling add-function.
but write it slightly differently, you will get two equivalent but distinct functions on the
hook. If you then remove one of them, the other will still be on it.
to that mode in the current buffer, by setting various buffer-local variables such as a local
keymap. See Section 24.2.1 [Major Mode Conventions], page 494. Note that unlike minor
modes there is no way to “turn off” a major mode, instead the buffer must be switched to
a different one. However, you can temporarily suspend a major mode and later restore the
suspended mode, see below.
The least specialized major mode is called Fundamental mode, which has no mode-
specific definitions or variable settings.
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 24.2.1 [Major Mode Conventions],
page 494), since you are not supposed to customize this mode.
major-mode-suspend [Function]
This function works like fundamental-mode, in that it kills all buffer-local variables,
but it also records the major mode in effect, so that it could subsequently be restored.
This function and major-mode-restore (described next) are useful when you need
to put a buffer under some specialized mode other than the one Emacs chooses for it
automatically (see Section 24.2.2 [Auto Major Mode], page 497), but would also like
to be able to switch back to the original mode later.
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 24.2.4 [Derived
Modes], page 500. 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 24.2.5 [Basic Major Modes], page 502, 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.
• 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 23.7 [Active Keymaps], page 458, 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 191, 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 31.2.6 [List Motion], page 805) 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 36 [Syntax Tables], page 958.
• 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 37.2 [Defining Abbrevs],
page 976.
Chapter 24: Major and Minor Modes 496
• 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 24.6 [Font Lock
Mode], page 527).
• Each face that the mode defines should, if possible, inherit from an existing Emacs
face. See Section 40.12.8 [Basic Faces], page 1083, and Section 24.6.7 [Faces for Font
Lock], page 536.
• Consider adding a mode-specific menu to the menu bar. This should preferably in-
clude the most important menu-specific settings and commands that will allow users
discovering the main features quickly and efficiently.
• Consider adding mode-specific context menus for the mode, to be used if and when
users activate the context-menu-mode (see Section “Menu Mouse Clicks” in The Emacs
Manual). To this end, define a mode-specific function which builds one or more menus
depending on the location of the mouse-3 click in the buffer, and then add that function
to the buffer-local value of context-menu-functions.
• 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 24.5
[Imenu], page 525).
• The mode can tell ElDoc mode how to retrieve different types of documentation for
whatever is at point, by adding one or more buffer-local entries to the special hook
eldoc-documentation-functions.
• 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 21.6.8
[Completion in Buffers], page 389.
• 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 201.
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 24.2.6 [Mode Hooks],
page 503.
• 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-
Chapter 24: Major and Minor Modes 497
mode does this automatically.) See Section 24.2.4 [Derived Modes], page 500, and
Section 24.2.6 [Mode Hooks], page 503.
• 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 203).
• 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 24.2.2 [Auto Major Mode], page 497), 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 24.2.5 [Basic Major Modes], page 502.
• 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 24.2.2 [Auto Major Mode], page 497). 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 291). 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 189).
‘-*-’ line or at the end of the file. The variable enable-local-variables controls
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.
set-auto-mode &optional keep-mode-if-same [Function]
This function selects and sets the major mode that is appropriate for the current
buffer. It bases its decision (in order of precedence) on the ‘-*-’ line, on any ‘mode:’
local variable near the end of a file, on the ‘#!’ line (using interpreter-mode-alist),
on the text at the beginning of the buffer (using magic-mode-alist), and finally on
the visited file name (using auto-mode-alist). See Section “How Major Modes are
Chosen” in The GNU Emacs Manual. If enable-local-variables is nil, set-auto-
mode does not check the ‘-*-’ line, or near the end of the file, for any mode tag.
There are some file types where it is not appropriate to scan the file contents for
a mode specifier. For example, a tar archive may happen to contain, near the end
of the file, a member file that has a local variables section specifying a mode for
that particular file. This should not be applied to the containing tar file. Similarly,
a tiff image file might just happen to contain a first line that seems to match the
‘-*-’ pattern. For these reasons, both these file extensions are members of the list
inhibit-local-variables-regexps. Add patterns to this list to prevent Emacs
searching them for local variables of any kind (not just mode specifiers).
If keep-mode-if-same is non-nil, this function does not call the mode command if the
buffer is already in the proper major mode. For instance, set-visited-file-name
sets this to t to avoid killing buffer local variables that the user may have set.
set-buffer-major-mode buffer [Function]
This function sets the major mode of buffer to the default value of major-mode; if that
is nil, it uses the current buffer’s major mode (if that is suitable). As an exception,
if buffer’s name is *scratch*, it sets the mode to initial-major-mode.
The low-level primitives for creating buffers do not use this function, but medium-
level commands such as switch-to-buffer and find-file-noselect use it whenever
they create buffers.
initial-major-mode [User Option]
The value of this variable determines the major mode of the initial *scratch* buffer.
The value should be a symbol that is a major mode command. The default value is
lisp-interaction-mode.
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 24: Major and Minor Modes 499
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 26.9.4 [File Name Expan-
sion], page 594), with version numbers and backup suffixes removed using file-name-
sans-versions (see Section 26.9.1 [File Name Components], page 590), 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’.
If auto-mode-alist has more than one element whose regexp matches the file name,
Emacs will use the first match.
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.)
Chapter 24: Major and Minor Modes 500
(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))
• The new mode has its own mode hook, variant-hook. It runs this hook, af-
ter running the hooks of its ancestor modes, with run-mode-hooks, as the last
thing it does, apart from running any :after-hook form it may have. See
Section 24.2.6 [Mode Hooks], page 503.
In addition, you can specify how to override other aspects of parent with body. The
command variant evaluates the forms in body after setting up all its usual overrides,
just before running the mode hooks.
If parent has a non-nil mode-class symbol property, then define-derived-mode
sets the mode-class property of variant to the same value. This ensures, for example,
that if parent is a special mode, then variant is also a special mode (see Section 24.2.1
[Major Mode Conventions], page 494).
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.)
:interactive
Modes are interactive commands by default. If you specify a nil value,
the mode defined here won’t be interactive. This is useful for modes that
are never meant to be activated by users manually, but are only supposed
to be used in some specially-formatted buffer.
: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
Chapter 24: Major and Minor Modes 502
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))
Do not write an interactive spec in the definition; define-derived-mode does that
automatically.
derived-mode-p &rest modes [Function]
This function returns non-nil if the current major mode is derived from any of the
major modes given by the symbols modes.
special-mode [Command]
Special mode is a basic major mode for buffers containing text that is produced
specially by Emacs, rather than directly from a file. Major modes derived from
Special mode are given a mode-class property of special (see Section 24.2.1 [Major
Mode Conventions], page 494).
Special mode sets the buffer to read-only. Its keymap defines several common bind-
ings, including q for quit-window and g for revert-buffer (see Section 27.3 [Re-
verting], page 622).
An example of a major mode derived from Special mode is Buffer Menu mode, which
is used by the *Buffer List* buffer. See Section “Listing Existing Buffers” in The
GNU Emacs Manual.
In addition, modes for buffers of tabulated data can inherit from Tabulated List mode,
which is in turn derived from Special mode. See Section 24.2.7 [Tabulated List Mode],
page 504.
change-major-mode-after-body-hook [Variable]
This is a normal hook run by run-mode-hooks. It is run before the mode hooks.
after-change-major-mode-hook [Variable]
This is a normal hook run by run-mode-hooks. It is run at the very end of every
properly-written major mode command.
tabulated-list-init-header [Function]
This function computes and sets header-line-format for the Tabulated List buffer
(see Section 24.4.7 [Header Lines], page 524), 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.
tabulated-list-clear-all-tags [Function]
This function clears all tags from the padding area in the current buffer.
The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp Interaction mode) have
more features than Text mode and the code is correspondingly more complicated. Here are
excerpts from lisp-mode.el that illustrate how these modes are written.
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, Lisp mode and Emacs
Lisp mode inherit from Lisp Data mode and Lisp Interaction Mode inherits from Emacs
Lisp mode.
Chapter 24: Major and Minor Modes 509
Amongst other things, Lisp Data mode 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 lisp-data-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."
(setq-local find-tag-default-function 'lisp-find-tag-default)
(setq-local comment-start-skip
"\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
(setq imenu-case-fold-search t))
local-minor-modes [Variable]
This buffer-local variable lists the currently enabled minor modes in the current buffer,
and is a list of symbols.
global-minor-modes [Variable]
This variable lists the currently enabled global minor modes, and is a list of symbols.
minor-mode-list [Variable]
The value of this variable is a list of all minor mode commands.
The reason for this somewhat complex behavior is that it lets users easily toggle the
minor mode interactively, and also lets the minor mode be easily enabled in a mode
hook, like this:
This behaves correctly whether or not foo-mode was already enabled, since the
foo-mode mode command unconditionally enables the minor mode when it is called
from Lisp with no argument. Disabling a minor mode in a mode hook is a little uglier:
Enabling or disabling a minor mode twice in direct succession should not fail and should
do the same thing as enabling or disabling it only once. In other words, the minor mode
command should be idempotent.
• Add an element to minor-mode-alist for each minor mode (see [Definition of minor-
mode-alist], page 521), if you want to indicate the minor mode in the mode line. This
element should be a list of the following form:
(mode-variable string)
Here mode-variable is the variable that controls enabling of the minor mode, and string
is a short string, starting with a space, to represent the mode in the mode line. These
strings must be short so that there is room for several of them at once.
When you add an element to minor-mode-alist, use assq to check for an existing
element, to avoid duplication. For example:
(unless (assq 'leif-mode minor-mode-alist)
(push '(leif-mode " Leif") minor-mode-alist))
or like this, using add-to-list (see Section 5.5 [List Variables], page 83):
(add-to-list 'minor-mode-alist '(leif-mode " Leif"))
In addition, several major mode conventions (see Section 24.2.1 [Major Mode Conven-
tions], page 494) 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 264). 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
cookie (see [autoload cookie], page 291), and specify a :require so that customizing the
variable will load the library that defines the mode. For example:
Chapter 24: Major and Minor Modes 512
;;;###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)
: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 variable
becomes a customization variable. Toggling it through the Customize
interface turns the mode on and off, and its value can be saved for future
Emacs sessions (see Section “Saving Customizations” in The GNU Emacs
Manual. For the saved variable to work, you should ensure that the minor
mode function is available each time Emacs starts; usually this is done
by marking the define-minor-mode form as autoloaded.
:init-value init-value
This is the value to which the mode variable is initialized. Except in
unusual circumstances (see below), this value must be nil.
:lighter lighter
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.
:keymap keymap
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 23.12 [Changing Key Bindings], page 466). If
keymap is a keymap or an alist, this also defines the variable mode-map.
: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 217). 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) which should
be assigned to place.
:after-hook after-hook
This defines a single Lisp form which is evaluated after the mode hooks
have run. It should not be quoted.
:interactive value
Minor modes are interactive commands by default. If value is nil, this
is inhibited. If value is a list of symbols, it’s used to say which major
modes this minor mode is useful in.
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
Chapter 24: Major and Minor Modes 514
mode hook variable mode-hook and finishes by evaluating any form in :after-hook.
(Note that all of this, including running the hook, is done both when the mode is
enabled and disabled.)
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.
the body forms. To turn on the minor mode in a buffer, it uses the function turn-on;
to turn off the minor mode, it calls mode with −1 as argument.
Globally enabling the mode also affects buffers subsequently created by visiting files,
and buffers that use a major mode other than Fundamental mode; but it does not
detect the creation of a new buffer in Fundamental mode.
This defines the customization option global-mode (see Chapter 15 [Customization],
page 264), which can be toggled in the Customize interface to turn the minor
mode on and off. As with define-minor-mode, you should ensure that the
define-globalized-minor-mode form is evaluated each time Emacs starts, for
example by providing a :require keyword.
Use :group group in keyword-args to specify the custom group for the mode variable
of the global minor mode.
By default, the buffer-local minor mode variable that says whether the mode is
switched on or off is the same as the name of the mode itself. Use :variable variable
if that’s not the case–some minor modes use a different variable to store this state
information.
Generally speaking, when you define a globalized minor mode, you should also define
a non-globalized version, so that people can use (or disable) it in individual buffers.
This also allows them to disable a globally enabled minor mode in a specific major
mode, by using that mode’s hook.
If given a :predicate keyword, a user option called the same as the global mode
variable, but with -modes instead of -mode at the end will be created. The variable
is used as a predicate that specifies which major modes the minor mode should be
activated in. Valid values include t (use in all major modes, nil (use in no major
modes), or a list of mode names (or (not mode-name ...)) elements (as well as t and
nil).
(c-mode (not mail-mode message-mode) text-mode)
This means “use in modes derived from c-mode, and not in modes derived from
message-mode or mail-mode, but do use in modes derived from text-mode, and
otherwise no other modes”.
((not c-mode) t)
This means “don’t use modes derived from c-mode, but use everywhere else”.
(text-mode)
This means “use in modes derived from text-mode, but nowhere else”. (There’s an
implicit nil element at the end.)
This section describes how to control the contents of the mode line and header line. We
include it in this chapter because much of the information displayed in the mode line relates
to the enabled major and minor modes.
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 40.12 [Faces], page 1069.
Some modes put a lot of data in the mode line, pushing elements at the end of the
mode line off to the right. Emacs can “compress” the mode line if the mode-line-compact
variable is non-nil by turning stretches of spaces into a single space. If this variable is long,
this is only done when the mode line is wider than the currently selected window. (This
computation is approximate, based on the number of characters, and not their displayed
width.) This variable can be buffer-local to only compress mode-lines in certain buffers.
Here are the meanings of various data types as mode line constructs:
string A string as a mode line construct appears verbatim except for %-constructs in it.
These stand for substitution of other data; see Section 24.4.5 [%-Constructs],
page 522.
If parts of the string have face properties, they control display of the text just
as they would text in the buffer. Any characters which have no face properties
are displayed, by default, in the face mode-line or mode-line-inactive (see
Section “Standard Faces” in The GNU Emacs Manual). The help-echo and
keymap properties in string have special meanings. See Section 24.4.6 [Proper-
ties in Mode], page 523.
symbol A symbol as a mode line construct stands for its value. The value of symbol is
used as a mode line construct, in place of symbol. However, the symbols t and
nil are ignored, as is any symbol whose value is void.
There is one exception: if the value of symbol is a string, it is displayed verba-
tim: the %-constructs are not recognized.
Unless symbol is marked as risky (i.e., it has a non-nil risky-local-variable
property), all text properties specified in symbol’s value are ignored. This
includes the text properties of strings in symbol’s value, as well as all :eval and
:propertize forms in it. (The reason for this is security: non-risky variables
could be set automatically from file variables without prompting the user.)
(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. (Note that text properties are handled specially (for reasons of
efficiency) when displaying strings in the mode line: Only the text property on
the first character of the string are considered, and they are then used over the
entire string. If you need a string with different text properties, you have to
use the special :propertize 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
Chapter 24: Major and Minor Modes 518
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
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 24.4.4 [Mode Line Variables], page 519), 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
Chapter 24: Major and Minor Modes 519
" "
'global-mode-string
" %[("
'(:eval (format-time-string "%F"))
'mode-line-process
'minor-mode-alist
"%n"
")%]--"
'(which-function-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-function-mode en-
able particular minor modes; as usual, these variable names are also the minor mode com-
mand names.)
mode-line-position-line-format [Variable]
The format used to display line numbers when line-number-mode (see Section “Op-
tional Mode Line” in The GNU Emacs Manual) is switched on. ‘%l’ in the format
will be replaced with the line number.
mode-line-position-column-format [Variable]
The format used to display column numbers when column-number-mode (see Section
“Optional Mode Line” in The GNU Emacs Manual) is switched on. ‘%c’ in the format
will be replaced with a zero-based column number, and ‘%C’ will be replaced with a
one-based column number.
mode-line-position-column-line-format [Variable]
The format used to display column numbers when both line-number-mode and
column-number-mode are switched on. See the previous two variables for the meaning
of the ‘%l’, ‘%c’ and ‘%C’ format specs.
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-function-mode minor mode if set, else after mode-line-
modes. Elements that are added to this construct should normally end in a space
(to ensure that consecutive global-mode-string elements display properly). For in-
stance, 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 informa-
tion.
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.
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
Chapter 24: Major and Minor Modes 522
" "
mode-line-position
(vc-mode vc-mode)
" "
mode-line-modes
(which-function-mode ("" which-func-format "--"))
(global-mode-string ("--" global-mode-string))
"-%-")
%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 39.6 [Process Information], page 1001.
%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 28.5 [Buffer Modification], page 632.
%+ ‘*’ 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 28.5 [Buffer Modification], page 632.
%& ‘*’ if the buffer is modified, and ‘-’ otherwise.
%@ ‘@’ if the buffer’s default-directory (see Section 26.9.4 [File Name Expan-
sion], page 594) is on a remote machine, and ‘-’ otherwise.
%[ An indication of the depth of recursive editing levels (not counting minibuffer
levels): one ‘[’ for each editing level. See Section 22.13 [Recursive Editing],
page 446.
%] 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 %-construct is still supported, but it is obsolete, since you can get the same
result using the variable mode-name.
%m The value of mode-name.
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 24.4.2 [Mode Line Data], page 516). 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.
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.
24.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 35.3 [Reg-
ular Expressions], page 933); 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...)
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.
Chapter 24: Major and Minor Modes 526
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 36.3 [Syntax Table Functions],
page 963).
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
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.
Chapter 24: Major and Minor Modes 527
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.
font-lock-fontify-buffer
This function should fontify the current buffer’s accessible portion, by calling
the function specified by font-lock-fontify-buffer-function.
font-lock-unfontify-buffer
Used when turning Font Lock off to remove the fontification. Calls the function
specified by font-lock-unfontify-buffer-function.
font-lock-debug-fontify
This is a convenience command meant to be used when developing font lock-
ing for a mode, and should not be called from Lisp code. It recomputes all
the relevant variables and then calls font-lock-fontify-region on the entire
buffer.
There are several variables that control how Font Lock mode highlights text. But major
modes should not set any of these variables directly. Instead, they should set font-lock-
defaults as a buffer-local variable. The value assigned to this variable is used, if and when
Font Lock mode is enabled, to set all the other variables.
Chapter 24: Major and Minor Modes 529
font-lock-defaults [Variable]
This variable is set by modes to specify how to fontify text in that mode. It auto-
matically becomes buffer-local when set. If its value is nil, Font Lock mode does
no highlighting, and you can use the ‘Faces’ menu (under ‘Edit’ and then ‘Text
Properties’ in the menu bar) to assign faces explicitly to text in the buffer.
If non-nil, the value should look like this:
(keywords [keywords-only [case-fold
[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 24.6.5
[Levels of Font Lock], page 535.
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 24.6.8 [Syntactic Font Lock], page 537.
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 36.3 [Syntax Table Functions],
page 963.
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 24.6.4 [Other Font Lock Variables], page 534.
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.
mode, using the keywords element in font-lock-defaults. The value can also
be altered using the functions font-lock-add-keywords and font-lock-remove-
keywords (see Section 24.6.3 [Customizing Keywords], page 533).
Each element of font-lock-keywords specifies how to find certain cases of text, and how
to highlight those cases. Font Lock mode processes the elements of font-lock-keywords
one by one, and for each element, it finds and handles all matches. Ordinarily, once part
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 35.3.3 [Regexp Functions], page 942) 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)
(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:
(subexp
Chapter 24: Major and Minor Modes 531
(matcher . anchored-highlighter)
In this kind of element, anchored-highlighter specifies how to highlight text
that follows a match found by matcher. So a match found by matcher acts
as the anchor for further searches specified by anchored-highlighter. anchored-
highlighter is a list of the following form:
(anchored-matcher pre-form post-form
subexp-highlighters...)
Chapter 24: Major and Minor Modes 532
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)))))
Chapter 24: Major and Minor Modes 534
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 embedded in program code inside specially-formed comments
or strings. This face inherits, by default, from font-lock-string-face.
font-lock-doc-markup-face
for mark-up elements in text using font-lock-doc-face. It is typically used
for the mark-up constructs in documentation embedded in program code, fol-
lowing conventions such as Haddock, Javadoc or Doxygen. This face inherits,
by default, from font-lock-constant-face.
font-lock-negation-char-face
for easily-overlooked negation characters.
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 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 24.6.7 [Faces for Font Lock], page 536).
This variable is normally set through the “other” elements in font-lock-defaults:
(setq-local font-lock-defaults
`(,python-font-lock-keywords
nil nil nil nil
(font-lock-syntactic-face-function
. python-font-lock-syntactic-face-function)))
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.
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.
other than just the paired parentheses already handled by syntax tables. For example, if
the provided grammar is precise enough, transpose-sexps can correctly transpose the
two arguments of a + operator, taking into account the precedence rules of the language.
Calling smie-setup is also sufficient to make TAB indentation work in the expected way,
extends blink-matching-paren to apply to elements like begin...end, and provides some
commands that you can bind in the major mode keymap.
smie-close-block [Command]
This command closes the most recently opened (and not yet closed) block.
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.
• 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.
To describe the lexing rules of your language to SMIE, you need 2 functions, one to
fetch the next token, and another to fetch the previous token. Those functions will usually
first skip whitespace and comments and then look at the next chunk of text to see if it is a
special token. If so it should skip the token and return a description of this token. Usually
this is simply the string extracted from the buffer, but it can be anything you want. For
example:
(defvar sample-keywords-regexp
(regexp-opt '("+" "*" "," ";" ">" ">=" "<" "<=" ":=" "=")))
(defun sample-smie-forward-token ()
(forward-comment (point-max))
(cond
((looking-at sample-keywords-regexp)
(goto-char (match-end 0))
(match-string-no-properties 0))
(t (buffer-substring-no-properties
(point)
(progn (skip-syntax-forward "w_")
(point))))))
Chapter 24: Major and Minor Modes 545
(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 24: Major and Minor Modes 550
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.
551
25 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 1233, 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 560.
\[command]
stands for a key sequence that will invoke command, or ‘M-x command’ if com-
mand has no key bindings.
Chapter 25: Documentation 555
\{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 25.4 [Text Quoting Style], page 556.
' (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.
text-quoting-style [User Option]
The value of this variable is a symbol that specifies the style Emacs should use for
single quotes in the wording of help and messages. If the variable’s value is curve,
the style is ‘like this’ with curved single quotes. If the value is straight, the
style is ’like this’ with straight apostrophes. If the value is grave, quotes are
not translated and the style is ‘like this’ with grave accent and apostrophe, the
standard style before Emacs version 25. The default value nil acts like curve if
curved single quotes seem to be displayable, and like grave otherwise.
This option is useful on platforms that have problems with curved quotes. You can
customize it freely according to your personal preference.
substitute-command-keys string &optional no-face [Function]
This function scans string for the above special sequences and replaces them by what
they stand for, returning the result as a string. This permits display of documentation
that refers accurately to the user’s own customized key bindings. By default, the key
bindings are given a special face help-key-binding, but if the optional argument
no-face is non-nil, the function doesn’t add this face to the produced string.
If a command has multiple bindings, this function normally uses the first one it finds.
You can specify one particular key binding by assigning an :advertised-binding
symbol property to the command, like this:
(put 'undo :advertised-binding [?\C-/])
The :advertised-binding property also affects the binding shown in menu items
(see Section 23.17.5 [Menu Bar], page 482). The property is ignored if it specifies a
key binding that the command does not actually have.
Here are examples of the special sequences:
(substitute-command-keys
"To abort recursive edit, type `\\[abort-recursive-edit]'.")
⇒ "To abort recursive edit, type ‘C-]’."
Chapter 25: Documentation 556
(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 1233, 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, read-char, read-char-
from-minibuffer, or y-or-n-p probably should bind help-form to a non-nil ex-
pression 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 400).
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 25: Documentation 560
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.
:no-eval*
Like :no-eval, but always inserts ‘[it depends]’ as the result. For in-
stance:
:no-eval* (buffer-string)
will result in:
(buffer-string)
→ [it depends]
:no-value
Like :no-eval, but is used when the function in question has no well-
defined return value, and is used for side effect only.
:result Used to output the result from non-evaluating example forms.
:no-eval (setcar list 'c)
:result c
:eg-result
Used to output an example result from non-evaluating example forms.
For instance:
:no-eval (looking-at "f[0-9]")
:eg-result t
will result in:
(looking-at "f[0-9]")
eg. → t
:result-string
:eg-result-string
These two are the same as :result and :eg-result, respectively, but
are inserted as is. This is useful when the result is unreadable or should
be of a particular form:
:no-eval (find-file "/tmp/foo")
:eg-result-string "#<buffer foo>"
:no-eval (default-file-modes)
:eg-result-string "#o755"
:no-manual
Indicates that this function is not documented in the manual.
:args By default, the function’s actual argument list is shown. If :args is
present, they are used instead.
:args (regexp string)
Here’s a very short example:
(define-short-documentation-group string
"Creating Strings"
(substring
:eval (substring "foobar" 0 3)
:eval (substring "foobar" 3))
(concat
Chapter 25: Documentation 563
26 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 28 [Buffers], page 626, and those related to backups and auto-saving are described
in Chapter 27 [Backups and Auto-Saving], page 614.
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 26.9.4 [File Name Expansion], page 594.
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 26.12 [Magic File Names],
page 604, 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 177). 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 34.12 [Locales], page 928).
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 26: Files 567
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 28.4 [Buffer File Name],
page 630) 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 26.9.3 [Directory Names], page 593),
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 26.13
[Format Conversion], page 609). 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 27.2 [Auto-Saving], page 619) 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 27.1.1 [Making Backup Files], page 614.
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 34.10.3 [Lisp and Coding Systems], page 916), perform the encoding (see
Section 34.10.7 [Explicit Encoding], page 925), and set last-coding-system-used to
the coding system that was used (see Section 34.10.2 [Encoding and I/O], page 915).
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 24.1 [Hooks], page 490.
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 26: Files 570
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.
before-save-hook [User Option]
This normal hook runs before a buffer is saved in its visited file, regardless of whether
that is done normally or by one of the hooks described above. For instance, the
copyright.el program uses this hook to make sure the file you are saving has the
current year in its copyright notice.
after-save-hook [User Option]
This normal hook runs after a buffer has been saved in its visited file.
file-precious-flag [User Option]
If this variable is non-nil, then save-buffer protects against I/O errors while saving
by writing the new file to a temporary name instead of the name it is supposed to
have, and then renaming it to the intended name after it is clear there are no errors.
This procedure prevents problems such as a lack of disk space from resulting in an
invalid file.
As a side effect, backups are necessarily made by copying. See Section 27.1.2 [Rename
or Copy], page 616. Yet, at the same time, saving a precious file always breaks all
hard links between the file you save and other file names.
Some modes give this variable a non-nil buffer-local value in particular buffers.
require-final-newline [User Option]
This variable determines whether files may be written out that do not end with a
newline. If the value of the variable is t, then save-buffer silently adds a newline at
the end of the buffer whenever it does not already end in one. If the value is visit,
Emacs adds a missing newline just after it visits the file. If the value is visit-save,
Emacs adds a missing newline both on visiting and on saving. For any other non-nil
value, save-buffer asks the user whether to add a newline each time the case arises.
If the value of the variable is nil, then save-buffer doesn’t add newlines at all. nil
is the default value, but a few major modes set it to t in particular buffers.
See also the function set-visited-file-name (see Section 28.4 [Buffer File Name],
page 630).
This function checks the file contents against the defined file formats, and converts
the file contents if appropriate and also calls the functions in the list after-insert-
file-functions. See Section 26.13 [Format Conversion], page 609. Normally, one
of the functions in the after-insert-file-functions list determines the coding
system (see Section 34.10 [Coding Systems], page 913) used for decoding the file’s
contents, including end-of-line conversion. However, if the file contains null bytes,
it is by default visited without any code conversions. See Section 34.10.3 [Lisp and
Coding Systems], page 916.
If visit is non-nil, this function additionally marks the buffer as unmodified and sets
up various fields in the buffer so that it is visiting the file filename: these include
the buffer’s visited file name and its last save file modtime. This feature is used by
find-file-noselect and you probably should not use it yourself.
If beg and end are non-nil, they should be numbers that are byte offsets specifying
the portion of the file to insert. In this case, visit must be nil. For example,
(insert-file-contents filename nil 0 500)
inserts the characters coded by the first 500 bytes of a file.
If beg or end happens to be in the middle of a character’s multibyte sequence, Emacs’s
character code conversion will insert one or more eight-bit characters (a.k.a. “raw
bytes”) (see Section 34.7 [Character Sets], page 910) into the buffer. If you want to
read part of a file this way, we recommend to bind coding-system-for-read to a
suitable value around the call to this function (see Section 34.10.6 [Specifying Coding
Systems], page 923), and to write Lisp code which will check for raw bytes at the
boundaries, read the entire sequence of these bytes, and convert them back to valid
characters.
If the argument replace is non-nil, it means to replace the contents of the buffer
(actually, just the accessible portion) with the contents of the file. This is better
than simply deleting the buffer contents and inserting the whole file, because (1) it
preserves some marker positions and (2) it puts less data in the undo list.
It is possible to read a special file (such as a FIFO or an I/O device) with
insert-file-contents, as long as replace and visit are nil.
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 26.12 [Magic File Names], page 604.
operating in batch mode (see Section 41.17 [Batch Mode], page 1187). This feature
is useful for programs that use files for internal purposes, files that the user does not
need to know about.
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 26.8 [Files
and Storage], page 589.
(file-locked-p "foo")
⇒ nil
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. This function handles file system errors by calling display-warning
and otherwise ignores the error.
lock-file-mode [Command]
This command, called interactively, toggles the local value of create-lockfiles in
the current buffer.
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
See Section 26.7 [Changing Files], page 584, for the set-file-modes function, which
can be used to set these permissions.
(file-modes "~/junk/diffs" 'nofollow)
⇒ 492 ; Decimal integer.
(format "%o" 492)
⇒ "754" ; Convert to octal.
$ 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 26.6.4
[File Attributes], page 580).
Note that in the third example, the function returned sym-link, but did not proceed
to resolve it, although that file is itself a symbolic link. That is because this function
does not follow symbolic links—the process of following the symbolic links does not
apply to the last component of the file name.
The string that this function returns is what is recorded in the symbolic link; it may
or may not include any leading directories. This function does not expand the link
target to produce a fully-qualified file name, and in particular does not use the leading
directories, if any, of the filename argument if the link target is not an absolute file
name. Here’s an example:
(file-symlink-p "/foo/bar/baz")
⇒ "some-file"
Here, although /foo/bar/baz was given as a fully-qualified file name, the result is
not, and in fact does not have any leading directories at all. And since some-file
might itself be a symbolic link, you cannot simply prepend leading directories to it,
nor even naively use expand-file-name (see Section 26.9.4 [File Name Expansion],
page 594) to produce its absolute file name.
For this reason, this function is seldom useful if you need to determine more than just
the fact that a file is or isn’t a symbolic link. If you actually need the file name of the
link target, use file-chase-links or file-truename, described in Section 26.6.3
[Truenames], page 578.
26.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
Chapter 26: Files 579
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.
file-truename filename [Function]
This function returns the truename of the file filename. If the argument is not an
absolute file name, this function first expands it against default-directory.
This function does not expand environment variables. Only substitute-in-file-
name does that. See [Definition of substitute-in-file-name], page 596.
If you may need to follow symbolic links preceding ‘..’ appearing as a name com-
ponent, call file-truename without prior direct or indirect calls to expand-file-
name. Otherwise, the file name component immediately preceding ‘..’ will be sim-
plified away before file-truename is called. To eliminate the need for a call to
expand-file-name, file-truename handles ‘~’ in the same way that expand-file-
name does.
If the target of a symbolic links has remote file name syntax, file-truename returns
it quoted. See Section 26.9.4 [Functions that Expand Filenames], page 594.
file-chase-links filename &optional limit [Function]
This function follows symbolic links, starting with filename, until it finds a file name
which is not the name of a symbolic link. Then it returns that file name. This function
does not follow symbolic links at the level of parent directories.
If you specify a number for limit, then after chasing through that many links, the
function just returns what it has even if that is still a symbolic link.
To illustrate the difference between file-chase-links and file-truename, suppose
that /usr/foo is a symbolic link to the directory /home/foo, and /home/foo/hello is an
ordinary file (or at least, not a symbolic link) or nonexistent. Then we would have:
(file-chase-links "/usr/foo/hello")
;; This does not follow the links in the parent directories.
⇒ "/usr/foo/hello"
(file-truename "/usr/foo/hello")
;; Assuming that /home is not a symbolic link.
⇒ "/home/foo/hello"
file-equal-p file1 file2 [Function]
This function returns t if the files file1 and file2 name the same file. This is similar
to comparing their truenames, except that remote file names are also handled in an
appropriate manner. If file1 or file2 does not exist, the return value is unspecified.
file-name-case-insensitive-p filename [Function]
Sometimes file names or their parts need to be compared as strings, in which case
it’s important to know whether the underlying filesystem is case-insensitive. This
function returns t if file filename is on a case-insensitive filesystem. It always returns
t on MS-DOS and MS-Windows. On Cygwin and macOS, filesystems may or may not
be case-insensitive, and the function tries to determine case-sensitivity by a runtime
test. If the test is inconclusive, the function returns t on Cygwin and nil on macOS.
Chapter 26: Files 580
Currently this function always returns nil on platforms other than MS-DOS, MS-
Windows, Cygwin, and macOS. It does not detect case-insensitivity of mounted
filesystems, such as Samba shares or NFS-mounted Windows volumes. On remote
hosts, it assumes t for the ‘smb’ method. For all other connection methods, runtime
tests are performed.
On GNU platforms when operating on a local file, this function is atomic: if the
filesystem is simultaneously being changed by some other process, this function re-
turns the file’s attributes either before or after the change. Otherwise this function is
not atomic, and might return nil if it detects the race condition, or might return a
hodgepodge of the previous and current file attributes.
Accessor functions are provided to access the elements in this list. The accessors are
mentioned along with the descriptions of the elements below.
0. t for a directory, a string for a symbolic link (the name linked to), or nil for a
text file (file-attribute-type).
1. The number of names the file has (file-attribute-link-number). Alternate
names, also known as hard links, can be created by using the add-name-to-file
function (see Section 26.7 [Changing Files], page 584).
2. The file’s UID, normally as a string (file-attribute-user-id). However, if it
does not correspond to a named user, the value is an integer.
3. The file’s GID, likewise (file-attribute-group-id).
4. The time of last access as a Lisp timestamp (file-attribute-access-time).
The timestamp is in the style of current-time (see Section 41.5 [Time of Day],
page 1168) and is truncated to that of the filesystem’s timestamp resolution; for
example, on some FAT-based filesystems, only the date of last access is recorded,
so this time will always hold the midnight of the day of the last access.
5. The time of last modification as a Lisp timestamp (file-attribute-
modification-time). This is the last time when the file’s contents were
modified.
6. The time of last status change as a Lisp timestamp (file-attribute-status-
change-time). This is the time of the last change to the file’s access mode bits,
its owner and group, and other information recorded in the filesystem for the file,
beyond the file’s contents.
7. The size of the file in bytes (file-attribute-size).
8. The file’s modes, as a string of ten letters or dashes, as in ‘ls -l’
(file-attribute-modes).
9. An unspecified value, present for backward compatibility.
10. The file’s inode number (file-attribute-inode-number), a nonnegative inte-
ger.
11. The filesystem number of the device that the file is on file-attribute-device-
number), an integer. 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.
(file-nlinks "foo")
⇒ 2
(file-nlinks "doesnt-exist")
⇒ nil
reporting the system-dependent error message that describes the reason for the failure. If
they fail because a file is missing, they signal a file-missing error instead.
For performance, the operating system may cache or alias changes made by these func-
tions instead of writing them immediately to secondary storage. See Section 26.8 [Files and
Storage], page 589.
In the functions that have an argument newname, if this argument is a directory name
it is treated as if the nondirectory part of the source name were appended. Typically, a
directory name is one that ends in ‘/’ (see Section 26.9.3 [Directory Names], page 593). For
example, if the old name is a/b/c, the newname d/e/f/ is treated as if it were d/e/f/c.
This special treatment does not apply if newname is not a directory name but names a file
that is a directory; for example, the newname d/e/f is left as-is even if d/e/f happens to
be a directory.
In the functions that have an argument newname, if a file by the name of newname
already exists, the actions taken depend on the value of the argument ok-if-already-exists:
• Signal a file-already-exists error if ok-if-already-exists is nil.
• Request confirmation if ok-if-already-exists is a number.
• Replace the old file without confirmation if ok-if-already-exists is any other value.
add-name-to-file oldname newname &optional ok-if-already-exists [Command]
This function gives the file named oldname the additional name newname. This
means that newname becomes a new hard link to oldname.
If newname is a symbolic link, its directory entry is replaced, not the directory entry
it points to. If oldname is a symbolic link, this function might or might not follow
the link; it does not follow the link on GNU platforms. If oldname is a directory, this
function typically fails, although for the superuser on a few old-fashioned non-GNU
platforms it can succeed and create a filesystem that is not tree-structured.
In the first part of the following example, we list two files, foo and foo3.
$ ls -li fo*
81908 -rw-rw-rw- 1 rms rms 29 Aug 18 20:32 foo
84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
Now we create a hard link, by calling add-name-to-file, then list the files again.
This shows two names for one file, foo and foo2.
(add-name-to-file "foo" "foo2")
⇒ nil
$ ls -li fo*
81908 -rw-rw-rw- 2 rms 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
Chapter 26: Files 586
$ 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 26.6.4 [File Attributes], page 580.
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.
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 26.6.1 [Testing Accessibility], page 575, 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.
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.
failure you can use the write-region function with the write-region-inhibit-fsync
variable set to nil. See Section 26.4 [Writing to Files], page 571.
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 26.9.4 [File Name Expansion],
page 594). This function converts absolute file names to relative names:
default-directory [Variable]
The value of this buffer-local variable is the default directory for the current buffer.
It should be an absolute directory name; it may start with ‘~’. This variable is
buffer-local in every buffer.
expand-file-name uses the default directory when its second argument is nil.
Chapter 26: Files 596
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 ‘/:’.
The default directory for temporary files is controlled by the variable temporary-file-
directory. This variable gives the user a uniform way to specify the directory for all
temporary files. Some programs use small-temporary-file-directory instead, if that is
non-nil. To use it, you should expand the prefix against the proper directory before calling
make-temp-file.
for Lisp programs to cope if the value is a directory’s file name instead. Using the
value as the second argument to expand-file-name is a good way to achieve that.
The default value is determined in a reasonable way for your operating system; it
is based on the TMPDIR, TMP and TEMP environment variables, with a fall-back to a
system-dependent name if none of these variables is defined.
Even if you do not use make-temp-file to create the temporary file, you should still
use this variable to decide which directory to put the file in. However, if you expect
the file to be small, you should use small-temporary-file-directory first if that
is non-nil.
small-temporary-file-directory [User Option]
This variable specifies the directory name for creating certain temporary files, which
are likely to be small.
If you want to write a temporary file which is likely to be small, you should compute
the directory like this:
(make-temp-file
(expand-file-name prefix
(or small-temporary-file-directory
temporary-file-directory)))
make-temp-name base-name [Function]
This function generates a string that might be a unique file name. The name starts
with base-name, and has several random characters appended to it, which are different
in each Emacs job. It is like make-temp-file except that (i) it just constructs a name
and does not create a file, (ii) base-name should be an absolute file name that is not
magic, and (iii) if the returned file name is magic, it might name an existing file. See
Section 26.12 [Magic File Names], page 604.
Warning: In most cases, you should not use this function; use make-temp-file in-
stead! This function is susceptible to a race condition, between the make-temp-name
call and the creation of the file, which in some cases may cause a security hole.
Sometimes, it is necessary to create a temporary file on a remote host or a mounted
directory. The following two functions support this.
make-nearby-temp-file prefix &optional dir-flag suffix [Function]
This function is similar to make-temp-file, but it creates a temporary file
as close as possible to default-directory. If prefix is a relative file name,
and default-directory is a remote file name or located on a mounted file
systems, the temporary file is created in the directory returned by the function
temporary-file-directory. Otherwise, the function make-temp-file is used.
prefix, dir-flag and suffix have the same meaning as in make-temp-file.
(let ((default-directory "/ssh:remotehost:"))
(make-nearby-temp-file "foo"))
⇒ "/ssh:remotehost:/tmp/foo232J6v"
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
Chapter 26: Files 599
On GNU and other POSIX-like systems, this simply returns filename. On other
operating systems, it may enforce system-specific file name conventions; for exam-
ple, on MS-DOS this function performs a variety of changes to enforce MS-DOS file
name limitations, including converting any leading ‘.’ to ‘_’ and truncating to three
characters after the ‘.’.
The recommended way to use this function is to specify a name which fits the con-
ventions of GNU and Unix systems, and pass it to convert-standard-filename.
insert-directory-program [Variable]
This variable’s value is the program to run to generate a directory listing for the
function insert-directory. It is ignored on systems which generate the listing with
Lisp code.
The first argument given to handler is the name of the primitive, as a symbol; the
remaining arguments are the arguments that were passed to that primitive. (The first of
these arguments is most often the file name itself.) For example, if you do this:
(file-exists-p filename)
and filename has handler handler, then handler is called like this:
(funcall handler 'file-exists-p filename)
When a function takes two or more arguments that must be file names, it checks each
of those names for a handler. For example, if you do this:
(expand-file-name filename dirname)
then it checks for a handler for filename and then for a handler for dirname. In either case,
the handler is called like this:
(funcall handler 'expand-file-name filename dirname)
The handler then needs to figure out whether to handle filename or dirname.
If the specified file name matches more than one handler, the one whose match starts
last in the file name gets precedence. This rule is chosen so that handlers for jobs such as
uncompression are handled first, before handlers for jobs such as remote file access.
Here are the operations that a magic file name handler gets to handle:
access-file, add-name-to-file,
byte-compiler-base-file-name,
copy-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,
exec-path, 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-locked-p,
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,
Chapter 26: Files 606
file-ownership-preserved-p,
file-readable-p, file-regular-p,
file-remote-p, file-selinux-context,
file-symlink-p, file-system-info,
file-truename, file-writable-p,
find-backup-file-name,
get-file-buffer,
insert-directory,
insert-file-contents,
load, lock-file,
make-auto-save-file-name,
make-directory,
make-directory-internal,
make-lock-file-name,
make-nearby-temp-file,
make-process,
make-symbolic-link,
process-file,
rename-file, set-file-acl, set-file-modes,
set-file-selinux-context, set-file-times,
set-visited-file-modtime, shell-command,
start-file-process,
substitute-in-file-name,
temporary-file-directory,
unhandled-file-name-directory,
unlock-file,
vc-registered,
verify-visited-file-modtime,
write-region.
Handlers for insert-file-contents typically need to clear the buffer’s modified flag,
with (set-buffer-modified-p nil), if the visit argument is non-nil. This also has the
effect of unlocking the buffer if it is locked.
The handler function must handle all of the above operations, and possibly others to
be added in the future. It need not implement all these operations itself—when it has
nothing special to do for a certain operation, it can reinvoke the primitive, to handle the
operation in the usual way. It should always reinvoke the primitive for an operation it does
not recognize. Here’s one way to do this:
(defun my-file-handler (operation &rest args)
;; First check for the specific operations
;; that we have special handling for.
(cond ((eq operation 'insert-file-contents) ...)
((eq operation 'write-region) ...)
...
;; Handle any operation we don’t know about.
(t (let ((inhibit-file-name-handlers
(cons 'my-file-handler
(and (eq inhibit-file-name-operation operation)
inhibit-file-name-handlers)))
(inhibit-file-name-operation operation))
Chapter 26: Files 607
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.
When this variable is set to nil, cached values are never expired. Use this setting
with caution, only if you are sure nothing other than Emacs ever changes the remote
files. If it is set to t, cached values are never used. This is the safest value, but could
result in performance degradation.
A compromise is to set it to a positive number. This means that cached values are
used for that amount of seconds since they were cached. If a remote file is checked
regularly, it might be a good idea to let-bind this variable to a value less than the
time period between consecutive checks. For example:
(defun display-time-file-nonempty-p (file)
(let ((remote-file-name-inhibit-cache
(- display-time-interval 5)))
(and (file-exists-p file)
(< 0 (file-attribute-size
(file-attributes
(file-chase-links file)))))))
26.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 34.10 [Coding
Systems], page 913, for details on character encoding and decoding.
we call this “round-trip” specification (see Section 26.13.3 [Format Conversion Piecemeal],
page 612, for non-paired specification).
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)
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.
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.
format-write-file file format &optional confirm [Command]
This command writes the current buffer contents into the file file in a format based on
format, which is a list of format names. It constructs the actual format starting from
format, then appending any elements from the value of buffer-file-format with a
non-nil preserve flag (see above), if they are not already present in format. It then
updates buffer-file-format with this format, making it the default for future saves.
Except for the format argument, this command is similar to write-file. In partic-
ular, confirm has the same meaning and interactive treatment as the corresponding
argument to write-file. See [Definition of write-file], page 568.
format-find-file file format [Command]
This command finds the file file, converting it according to format format. It also
makes format the default if the buffer is saved later.
The argument format is a list of format names. If format is nil, no conversion takes
place. Interactively, typing just RET for format specifies nil.
format-insert-file file format &optional beg end [Command]
This command inserts the contents of file file, converting it according to format
format. If beg and end are non-nil, they specify which part of the file to read,
as in insert-file-contents (see Section 26.3 [Reading from Files], page 570).
The return value is like what insert-file-contents returns: a list of the absolute
file name and the length of the data inserted (after conversion).
Chapter 26: Files 612
The argument format is a list of format names. If format is nil, no conversion takes
place. Interactively, typing just RET for format specifies nil.
buffer-auto-save-file-format [Variable]
This variable specifies the format to use for auto-saving. Its value is a list of format
names, just like the value of buffer-file-format; however, it is used instead of
buffer-file-format for writing auto-save files. If the value is t, the default, auto-
saving uses the same format as a regular save in the same buffer. This variable is
always buffer-local in all buffers.
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.
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.
614
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 26.6.1 [Testing Accessibility], page 575),
extra-alist is an alist describing the original file’s extended attributes, as returned
by file-extended-attributes (see Section 26.6.5 [Extended Attributes], page 583),
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 27: Backups and Auto-Saving 615
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 27.1.4 [Backup Names], page 618) 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 27.1.3 [Numbered Backups], page 617.
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~")
27.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 24.3.1 [Minor Mode
Conventions], page 510).
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-transforms [Variable]
This variable lists transforms to apply to buffer’s file name before making the auto-
save file name.
Chapter 27: Backups and Auto-Saving 620
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#"
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 26.2
[Saving Buffers], page 568, 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.
27.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 problematic.
When reverting from non-file sources, markers are usually not preserved, but this is
up to the specific revert-buffer-function implementation.
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
Chapter 27: Backups and Auto-Saving 624
confirmation, clearing the undo list, deciding the proper major mode, and running
the hooks listed below.
before-revert-hook [Variable]
This normal hook is run by 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.
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
this, calling the revert-buffer-function on a buffer that is marked unmodified should
always keep the buffer marked unmodified.
It is important to assure that point does not continuously jump around as a consequence
of auto-reverting. Of course, moving point might be inevitable if the buffer radically changes.
You should make sure that the revert-buffer-function does not print messages that
unnecessarily duplicate Auto Revert’s own messages, displayed if auto-revert-verbose is
t, and effectively override a nil value for auto-revert-verbose. Hence, adapting a mode
for auto-reverting often involves getting rid of such messages. This is especially important
for buffers that automatically revert every auto-revert-interval seconds.
If the new auto-reverting is part of Emacs, you should mention it in the documentation
string of global-auto-revert-non-file-buffers.
Similarly, you should document the additions in the Emacs manual.
626
28 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.
current-buffer [Function]
This function returns the current buffer.
Chapter 28: Buffers 627
(current-buffer)
⇒ #<buffer buffers.texi>
When an editing command returns to the editor command loop, Emacs automatically
calls set-buffer on the buffer shown in the selected window (see Section 29.3 [Selecting
Windows], page 650). 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 22 [Command Loop], page 401). Thus, you should not use set-buffer to
switch visibly to a different buffer; for that, use the functions described in Section 29.12
[Switching Buffers], page 675.
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,
Chapter 28: Buffers 628
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
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.
The current buffer is restored even in case of an abnormal exit via throw or error (see
Section 11.7 [Nonlocal Exits], page 172).
See also with-temp-file in [Writing to Files], page 573.
(get-buffer b)
⇒ #<buffer lewis>
(get-buffer "Frazzle-nots")
⇒ nil
See also the function get-buffer-create in Section 28.9 [Creating Buffers], page 638.
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
if 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 28.9 [Creating Buffers],
page 638.
buffer-file-truename [Variable]
This buffer-local variable holds the abbreviated truename of the file visited in the cur-
rent buffer, or nil if no file is visited. It is a permanent local, unaffected by kill-all-
local-variables. See Section 26.6.3 [Truenames], page 578, and [abbreviate-file-
name], page 594.
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 26.6.4 [File Attributes], page 580, for more information
about them.
If buffer-file-name is the name of a symbolic link, then both numbers refer to the
recursive target.
If filename is nil or the empty string, that stands for “no visited file”. In this case,
set-visited-file-name marks the buffer as having no visited file, without changing
the buffer’s modified flag.
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 28.6 [Modification Time], page 633). 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.
The function returns t if the last actual modification time and Emacs’s recorded
modification time are the same, nil otherwise. It also returns t if the buffer has no
recorded last modification time, that is if visited-file-modtime would return zero.
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
Lisp timestamp (see Section 41.5 [Time of Day], page 1168).
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 timestamp 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 be a Lisp time value (see Section 41.5 [Time of Day], page 1168).
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 28: Buffers 635
See also the file locking mechanism in Section 26.5 [File Locks], page 573.
(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 30.4.1 [Parameter
Access], page 753).
or another buffer is shown in it. More precisely, if the selected window is dedicated
(see Section 29.15 [Dedicated Windows], page 700) 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 29.16 [Quitting Windows], page 701).
Otherwise, it calls switch-to-prev-buffer (see Section 29.14 [Window History],
page 698) 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 29.11 [Buffers and Windows], page 673.
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 29.12 [Switching
Buffers], page 675), 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 28.9 [Creating Buffers],
page 638), rename-buffer (see Section 28.3 [Buffer Names], page 629), kill-buffer
(see Section 28.10 [Killing Buffers], page 639), bury-buffer (see above), and
select-window (see Section 29.3 [Selecting Windows], page 650). This hook
is not run for internal or temporary buffers created by get-buffer-create or
generate-new-buffer with a non-nil argument inhibit-buffer-hooks.
Functions run by this hook should avoid calling select-window with a nil norecord
argument since this may lead to infinite recursion.
⇒ 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.
This hook is not run for internal or temporary buffers created by get-buffer-create
or generate-new-buffer with a non-nil argument inhibit-buffer-hooks.
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 24.1 [Hooks], page 490. This variable is a permanent
local, so its local binding is not cleared by changing major modes.
This hook is not run for internal or temporary buffers created by get-buffer-create
or generate-new-buffer with a non-nil argument inhibit-buffer-hooks.
the buffer. Lastly, if this variable is set to the symbol always, both save-buffers-
kill-emacs and save-some-buffers will always offer to save. See [Definition of
save-some-buffers], page 568. The variable buffer-offer-save automatically be-
comes buffer-local when set for any reason. See Section 12.11 [Buffer-Local Variables],
page 201.
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.
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.
Chapter 28: Buffers 643
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.
644
29 Windows
This chapter describes the functions and variables related to Emacs windows. See
Chapter 30 [Frames], page 736, for how windows are assigned an area of screen available
for Emacs to use. See Chapter 40 [Display], page 1037, for information on how text is
displayed in windows.
At the center of that window is the body, where the buffer text is displayed. The body
can be surrounded by a series of optional areas which we will call window decorations. On
the left and right, from innermost to outermost, these are the left and right fringes, denoted
by LF and RF (see Section 40.13 [Fringes], page 1093); the left and right margins, denoted
by LM and RM in the schematic (see Section 40.16.5 [Display Margins], page 1107); the
left or right vertical scroll bar, only one of which is present at any time, denoted by LS
and RS (see Section 40.14 [Scroll Bars], page 1099); and the right divider, denoted by RD
(see Section 40.15 [Window Dividers], page 1102). Together these are the window’s left and
right decorations.
At the top of the window are the tab line and the header line (see Section 24.4.7 [Header
Lines], page 524). The text area of the window includes the header line and the tab line,
if they are present in the window. At the bottom of the window are the horizontal scroll
bar (see Section 40.14 [Scroll Bars], page 1099); the mode line (see Section 24.4 [Mode
Line Format], page 515); and the bottom divider (see Section 40.15 [Window Dividers],
page 1102). Together these form the window’s top and bottom decorations.
There are two special areas omitted in the schematic:
• When any of the fringes is missing, the display engine may use one character cell in its
place for showing a continuation or truncation glyph provided a text line doesn’t fit in
a window.
• When both, the vertical scroll bar and the right divider are missing, the display engine
usurps one pixel for drawing a vertical divider line between this window and the window
on its right, provided such a window exists. On a text terminal, this divider always
occupies an entire character cell.
In either case, the resulting artifact is considered part of the window’s body although
its screen space cannot be used for displaying buffer text.
Note also, that line numbers (and their surrounding whitespace) as displayed by
display-line-numbers-mode (see Section “Display Custom” in The GNU Emacs Manual)
do not count as decorations either; they are part of the window’s body too.
Chapter 29: Windows 646
Internal windows neither show any text nor do they have decorations. Hence, the concept
of “body” does not make sense for them. In fact, most functions operating on the body of
a window will yield an error when applied to an internal window.
By default, an Emacs frame exhibits one special live window that is used for displaying
messages and accepting user input—the minibuffer window (see Section 21.11 [Minibuffer
Windows], page 396). Since the minibuffer window is used for displaying text, it has a body
but it does not have a tab or header line or any margins. Finally, a tooltip window which
is used for displaying a tooltip in a tooltip frame (see Section 40.25 [Tooltips], page 1147)
has a body too but no decorations at all.
Windows on 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 is either a live window or an internal window. If it is a live
window, then the frame has just one window besides the minibuffer window, or the frame
is a minibuffer-only frame, see Section 30.3.1 [Frame Layout], page 742.
A minibuffer window (see Section 21.11 [Minibuffer Windows], page 396) 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 from the root window via window-next-sibling, see below. Also,
the function window-tree described at the end of this section lists the minibuffer window
alongside the actual window tree.
Chapter 29: Windows 647
When a live window is split (see Section 29.7 [Splitting Windows], page 662), 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. The set of windows that share the same parent are called
siblings.
A parent window always has at least two child windows. If this number were to fall to
one as a result of window deletion (see Section 29.8 [Deleting Windows], page 664), Emacs
automatically deletes the parent window too, and its sole remaining child window takes its
place in the window tree.
A 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:
______________________________________
| ______ ____________________________ |
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| ||| |||
|| |||____________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.
Chapter 29: Windows 648
The following functions can be used to retrieve a child window of an internal window,
and the siblings of a child window. Their window argument always defaults to the selected
window (see Section 29.3 [Selecting Windows], page 650).
argument side can be any of the symbols left, top, right or bottom. The default
value nil is handled like bottom.
Note that this function disregards the minibuffer window (see Section 21.11 [Mini-
buffer Windows], page 396). Hence, with side equal to bottom it may return t also
when the minibuffer window appears right below window.
The edges element is a list (left top right bottom), similar to the value returned
by window-edges (see Section 29.24 [Coordinates and Windows], page 721).
selected-window [Function]
This function returns the selected window (which is always a live window).
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 28.8 [Buffer
Chapter 29: Windows 651
List], page 636). Consequently, that hook provides one 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.
Emacs also runs the hook window-selection-change-functions whenever the redis-
play routine detects that another window has been selected since last redisplay. See
Section 29.28 [Window Hooks], page 731, for a detailed explanation. window-state-
change-functions (described in the same section) is another abnormal hook run after
a different window has been selected but is triggered by other window changes as well.
The sequence of calls to select-window with a non-nil norecord argument determines
an ordering of windows by their selection or use time, see below. The function get-lru-
window, for example, can then be used to retrieve the least recently selected window (see
Section 29.10 [Cyclic Window Ordering], page 671).
frame-selected-window &optional frame [Function]
This function returns the window on frame that is selected within that frame. frame
should be a live frame; if omitted or nil, it defaults to the selected frame.
set-frame-selected-window frame window &optional norecord [Function]
This function makes window the window selected within the frame frame. frame
should be a live frame; if nil, it defaults to the selected frame. window should be a
live window; if nil, it defaults to the selected window.
If frame is the selected frame, this makes window the selected window.
If the optional argument norecord is non-nil, this function does not alter the ordering
of the most recently selected windows, nor the buffer list.
The following macros are useful to temporarily select a window without affecting the
ordering of recently selected windows or the buffer list.
save-selected-window forms. . . [Macro]
This macro records the selected frame, as well as the selected window of each frame,
executes forms in sequence, then restores the earlier selected frame and windows. It
also saves and restores the current buffer. It returns the value of the last form in
forms.
This macro does not save or restore anything about the sizes, arrangement or contents
of windows; therefore, if forms change them, the change persists. If the previously
selected window of some frame is no longer live at the time of exit from forms, that
frame’s selected window is left alone. If the previously selected window is no longer
live, then whatever window is selected at the end of forms remains selected. The
current buffer is restored if and only if it is still live when exiting forms.
This macro changes neither the ordering of recently selected windows nor the buffer
list.
Chapter 29: Windows 652
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
frame-char-height and frame-char-width (see Section 30.3.2 [Frame Font], page 747).
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 its body and its top and
bottom decorations (see Section 29.1 [Basic Windows], page 644).
window-total-height &optional window round [Function]
This function returns the total height, in lines, of the window window. If window is
omitted or nil, it defaults to the selected window. If window is an internal window,
the return value is the total height occupied by its descendant windows.
If a window’s pixel height is not an integral multiple of its frame’s default character
height, the number of lines occupied by the window is rounded internally. This is
done in a way such that, if the window is a parent window, the sum of the total
heights of all its child windows internally equals the total height of their parent. This
means that although two windows have the same pixel height, their internal total
heights may differ by one line. This means also, that if window is vertically combined
and has a next sibling, the topmost row of that sibling can be calculated as the sum
of this window’s topmost row and total height (see Section 29.24 [Coordinates and
Windows], page 721)
If the optional argument round is ceiling, this function returns the smallest integer
larger than window’s pixel height divided by the character height of its frame; if it is
floor, it returns the largest integer smaller than said value; with any other round it
returns the internal value of windows’s total height.
The total width of a window is the number of columns comprising its body and its left
and right decorations (see Section 29.1 [Basic Windows], page 644).
window-total-width &optional window round [Function]
This function returns the total width, in columns, of the window window. If window
is omitted or nil, it defaults to the selected window. If window is internal, the return
value is the total width occupied by its descendant windows.
If a window’s pixel width is not an integral multiple of its frame’s character width,
the number of columns occupied by the window is rounded internally. This is done
in a way such that, if the window is a parent window, the sum of the total widths
of all its children internally equals the total width of their parent. This means that
although two windows have the same pixel width, their internal total widths may
differ by one column. This means also, that if this window is horizontally combined
and has a next sibling, the leftmost column of that sibling can be calculated as the
sum of this window’s leftmost column and total width (see Section 29.24 [Coordi-
nates and Windows], page 721). The optional argument round behaves as it does for
window-total-height.
window-total-size &optional window horizontal round [Function]
This function returns either the total height in lines or the total width in columns
of the window window. If horizontal is omitted or nil, this is equivalent to
Chapter 29: Windows 654
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 body, which does not include any of its
top or bottom decorations (see Section 29.1 [Basic Windows], page 644).
The body width of a window is the width of its body and of the text area, which does
not include any of its left or right decorations (see Section 29.1 [Basic Windows], page 644).
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 display-
ing 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.)
window-body-width &optional window pixelwise [Function]
This function returns the width, in columns, of the body of window window. If
window is omitted or nil, it defaults to the selected window; otherwise it must be a
live window.
If the optional argument pixelwise is non-nil, this function returns the body width
of window in units of pixels.
If pixelwise is nil, the return value is rounded down to the nearest integer, if nec-
essary. This means that if a column on the right of the text area is only partially
visible, that column is not counted. It also means that the width of a window’s body
can never exceed its total width as returned by window-total-width.
window-body-size &optional window horizontal pixelwise [Function]
This function returns the body height or body width of window. If horizontal is
omitted or nil, it is equivalent to calling window-body-height for window; otherwise
it is equivalent to calling window-body-width. In either case, the optional argument
pixelwise is passed to the function called.
The pixel heights of a window’s mode, tab and header line can be retrieved with the
functions given below. Their return value is usually accurate unless the window has not
been displayed before: In that case, the return value is based on an estimate of the font
used for the window’s frame.
window-mode-line-height &optional window [Function]
This function returns the height in pixels of window’s mode line. window must be a
live window and defaults to the selected one. If window has no mode line, the return
value is zero.
window-tab-line-height &optional window [Function]
This function returns the height in pixels of window’s tab line. window must be a
live window and defaults to the selected one. If window has no tab line, the return
value is zero.
window-header-line-height &optional window [Function]
This function returns the height in pixels of window’s header line. window must be
a live window and defaults to the selected one. If window has no header line, the
return value is zero.
Functions for retrieving the height and/or width of window dividers (see Section 40.15
[Window Dividers], page 1102), fringes (see Section 40.13 [Fringes], page 1093), scroll bars
(see Section 40.14 [Scroll Bars], page 1099), and display margins (see Section 40.16.5 [Display
Margins], page 1107) are described in the corresponding sections.
Chapter 29: Windows 656
If your Lisp program needs to make layout decisions, you will find the following function
useful:
Commands that change the size of windows (see Section 29.5 [Resizing Windows],
page 657), or split them (see Section 29.7 [Splitting Windows], page 662), obey the
variables window-min-height and window-min-width, which specify the smallest
allowable window height and width. They also obey the variable window-size-fixed,
with which a window can be fixed in size (see Section 29.6 [Preserving Window Sizes],
page 660).
The following function tells how small a specific window can get taking into account
the sizes of its areas and the values of window-min-height, window-min-width and
window-size-fixed (see Section 29.6 [Preserving Window Sizes], page 660).
The optional argument pixelwise non-nil means to return the minimum size of win-
dow counted in pixels.
The following commands resize windows in more specific ways. When called interactively,
they act on the selected window.
dow of any frame that shall be fit to its buffer. If any of these values is non-nil, it
overrides the corresponding argument of fit-frame-to-buffer.
shrink-window-if-larger-than-buffer &optional window [Command]
This command attempts to reduce window’s height as much as possible while still
showing its full buffer, but no less than window-min-height lines. The return value
is non-nil if the window was resized, and nil otherwise. If window is omitted or
nil, it defaults to the selected window. Otherwise, it should be a live window.
This command does nothing if the window is already too short to display all of its
buffer, or if any of the buffer is scrolled off-screen, or if the window is the only live
window in its frame.
This command calls fit-window-to-buffer (see above) to do its work.
balance-windows &optional window-or-frame [Command]
This function balances windows in a way that gives more space to full-width and/or
full-height windows. If window-or-frame specifies a frame, it balances all windows on
that frame. If window-or-frame specifies a window, it balances only that window and
its siblings (see Section 29.2 [Windows and Frames], page 646).
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.
maximize-window &optional window [Command]
This function attempts to make window as large as possible, in both dimensions,
without resizing its frame or deleting other windows. If window is omitted or nil, it
defaults to the selected window.
minimize-window &optional window [Command]
This function attempts to make window as small as possible, in both dimensions,
without deleting it or resizing its frame. If window is omitted or nil, it defaults to
the selected window.
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 29.5 [Resizing Windows], page 657.
Often window-size-fixed is overly aggressive because it inhibits any attempt to ex-
plicitly resize or split an affected window as well. This may even happen after the window
has been resized implicitly, for example, when deleting an adjacent window or resizing the
window’s frame. The following function tries hard to never disallow resizing such a window
explicitly:
window-preserve-size &optional window horizontal preserve [Function]
This function (un-)marks the height of window window as preserved for future resize
operations. window must be a live window and defaults to the selected one. If
the optional argument horizontal is non-nil, it (un-)marks the width of window as
preserved.
If the optional argument preserve is t, this means to preserve the current height/width
of window’s body. The height/width of window will change only if Emacs has no
better choice. Resizing a window whose height/width is preserved by this function
never throws an error.
If preserve is nil, this means to stop preserving the height/width of window, lift-
ing any respective restraint induced by a previous call of this function for window.
Calling enlarge-window, shrink-window or fit-window-to-buffer with window
as argument may also remove the respective restraint.
window-preserve-size is currently invoked by the following functions:
fit-window-to-buffer
If the optional argument preserve-size of that function (see Section 29.5 [Re-
sizing Windows], page 657) is non-nil, the size established by that function is
preserved.
display-buffer
If the alist argument of that function (see Section 29.13.1 [Choosing Window],
page 678) 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 29.27 [Window Param-
eters], page 728) 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:
window-preserved-size &optional window horizontal [Function]
This function returns the preserved height of window window in pixels. window must
be a live window and defaults to the selected one. If the optional argument horizontal
Chapter 29: Windows 662
is non-nil, it returns the preserved width of window. It returns nil if the size of
window is not preserved.
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
split-window window parameter is t, this function ignores all other window pa-
rameters. Otherwise, if the value of the split-window window parameter is a func-
tion, that function is called with the arguments window, size, and side, in lieu of
the usual action of split-window. Otherwise, this function obeys the window-atom
or window-side window parameter, if any. See Section 29.27 [Window Parameters],
page 728.
As an example, here is a sequence of split-window calls that yields the window config-
uration discussed in Section 29.2 [Windows and Frames], page 646. 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:
______________________________________
| ______ ____________________________ |
|| || __________________________ ||
|| ||| |||
|| ||| |||
|| ||| |||
|| |||____________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.
Chapter 29: Windows 664
When delete-window deletes the selected window of its frame, it has to make another
window the new selected window of that frame. The following option allows configuring
which window is chosen.
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__________________|
Chapter 29: Windows 667
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 40.8 [Temporary Displays], page 1053), and you want to continue
working with the initial layout.
Chapter 29: Windows 668
The behavior can be fixed by making a new parent window when splitting W2. The
variable described next allows that to be done.
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 29.13.2 [Buffer Display Action Functions],
page 680). 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 40.8 [Temporary Displays], page 1053). 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 40.8 [Temporary Dis-
plays], page 1053). Otherwise, window splitting behaves as for nil.
display-buffer
This means that when display-buffer (see Section 29.13.1 [Choosing
Window], page 678) 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.
that simply re-selects the selected window. When called interactively, count is the
numeric prefix argument.
The optional argument all-frames has the same meaning as in next-window, like a
nil minibuf argument to next-window.
This function does not select a window that has a non-nil no-other-window win-
dow parameter (see Section 29.27 [Window Parameters], page 728), 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 no-other [Function]
This function returns a live window which is heuristically the least recently used one.
The least recently used window is the least recently selected one—the window whose
use time is less than the use time of all other live windows (see Section 29.3 [Selecting
Windows], page 650). 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 29.15 [Dedicated
Windows], page 700) 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. The optional argument no-other, if non-nil, means to never return a
window whose no-other-window parameter is non-nil.
Chapter 29: Windows 673
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 41.5 [Time of Day], page 1168).
The next two commands are similar to switch-to-buffer, except for the described
features.
precedence which display-buffer uses to call action functions (see Section 29.13.5 [Prece-
dence of Action Functions], page 690). To avoid conflicts between Lisp programs calling
display-buffer and user customizations of its behavior, it may make sense to follow a
number of guidelines which are sketched in the final part of this section (see Section 29.13.6
[The Zen of Buffer Display], page 694).
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
Chapter 29: Windows 679
Splitting also fails when the selected frame has an unsplittable frame parameter;
see Section 30.4.3.5 [Buffer Parameters], page 762.
the window chosen will appear on the side of the reference window specified by the
direction entry, sharing at least one edge with the reference window.
If the reference window is live, the edge the chosen window will share with it is
always the opposite of the one specified by the direction entry. For example, if the
value of the direction entry is left, the chosen window’s right edge coordinate (see
Section 29.24 [Coordinates and Windows], page 721) will equal the reference window’s
left edge coordinate.
If the reference window is internal, a reused window must share with it the edge
specified by the direction entry. Hence if, for example, the reference window is the
frame’s root window and the value of the direction entry is left, a reused window
must be on the left of the frame. This means that the left edge coordinate of the
chosen window and that of the reference window are the same.
A new window, however, will be created by splitting the reference window such that
the chosen window will share the opposite edge with the reference window. In our
example, a new root window would be created with a new live window and the
reference window as its children. The chosen window’s right edge coordinate would
then equal the left edge coordinate of the reference window. Its left edge coordinate
would equal the left edge coordinate of the frame’s new root window.
Four special values for direction entries allow to implicitly specify
the selected frame’s main window as the reference window: leftmost,
top, rightmost and bottom. This means that instead of, for ex-
ample, (direction . left) (window . main) one can just specify
(direction . leftmost). An existing window alist entry is ignored in
such cases.
window-width
This entry is similar to the window-height entry described before, but used
to adjust the chosen window’s width instead. The value can be one of the
following:
• nil means to leave the width of the chosen window alone.
• An integer specifies the desired total width of the chosen window in
columns.
• A floating-point number specifies the fraction of the chosen window’s de-
sired total width with respect to the total width of the frame’s root window.
• If the value specifies a function, that function is called with one argument—
the chosen window. The function is supposed to adjust the width of the
window; its return value is ignored.
By convention, the width of the chosen window is adjusted only if the window
is part of a horizontal combination (see Section 29.2 [Windows and Frames],
page 646) to avoid changing the width of other, unrelated windows. Also, this
entry should be processed under only certain conditions which are specified
right below this list.
dedicated
If non-nil, such an entry tells display-buffer to mark any window it creates
as dedicated to its buffer (see Section 29.15 [Dedicated Windows], page 700).
It does that by calling set-window-dedicated-p with the chosen window as
first argument and the entry’s value as second. Side windows are by default
dedicated with the value side ((see Section 29.17.2 [Side Window Options and
Functions], page 705).
preserve-size
If non-nil such an entry tells Emacs to preserve the size of the window chosen
(see Section 29.6 [Preserving Window Sizes], page 660). The value should be
either (t . nil) to preserve the width of the window, (nil . t) to preserve its
height or (t . t) to preserve both, its width and its height. This entry should
be processed only under certain conditions which are specified right after this
list.
pop-up-frame-parameters
The value specifies an alist of frame parameters to give a new frame, if one is
created. display-buffer-pop-up-frame is its one and only addressee.
parent-frame
The value specifies the parent frame to be used when the buffer is displayed on
a child frame. This entry is used only by display-buffer-in-child-frame.
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
Chapter 29: Windows 687
be placed (see Section 29.17.1 [Displaying Buffers in Side Windows], page 704).
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 29.18
[Atomic Windows], page 708).
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.
direction
The value specifies a direction which, together with a window entry, allows
display-buffer-in-direction to determine the location of the window to
display the buffer.
window The value specifies a window that is in some way related to the window cho-
sen 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. It is also used by display-buffer-in-direction to specify the
reference window on whose side the resulting window shall appear.
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.
body-function
The value must be a function taking one argument (a displayed window). This
function can be used to fill the displayed window’s body with some contents
that might depend on dimensions of the displayed window. It is called after
the buffer is displayed, and before the entries window-height, window-width
and preserve-size are applied that could resize the window to fit it to the
inserted contents.
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.
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 29: Windows 690
(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 29: Windows 692
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 29: Windows 694
partially restore the layout of a frame when removing a buffer from it later (see Section 29.16
[Quitting Windows], page 701).
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 29.13.4 [Choosing Window Options], page 687). 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 29: Windows 697
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.
You can also tell display-buffer to mark a window it creates as dedicated to its buffer
by providing a suitable dedicated action alist entry (see Section 29.13.3 [Buffer Display
Action Alists], page 684).
append This means that if window is not deleted, its buffer is moved to the end
of window’s list of previous buffers (see Section 29.14 [Window History],
page 698), so it’s less likely that future invocations of switch-to-prev-
buffer will switch to it. Also, it moves the buffer to the end of the
frame’s buffer list (see Section 28.8 [Buffer List], page 636).
bury This means that if window is not deleted, its buffer is removed from win-
dow’s list of previous buffers. Also, it moves the buffer to the end of the
frame’s buffer list. This is the most reliable way to prevent switch-to-
prev-buffer from switching to this buffer again, short of killing the
buffer.
kill This means to kill window’s buffer.
The argument bury-or-kill also specifies what to do with window’s frame when win-
dow should be deleted, if it is the only window on its frame, and there are other frames
on that frame’s terminal. If bury-or-kill equals kill, it means to delete the frame.
Otherwise, the fate of the frame is determined by calling frame-auto-hide-function
(see below) with that frame as sole argument.
This function always sets window’s quit-restore parameter to nil unless it deletes
the window.
The window window’s quit-restore parameter (see Section 29.27 [Window Parame-
ters], page 728) should be nil or a list of four elements:
(method obuffer owindow this-buffer)
The first element, method, is one of the four symbols window, frame, same and other.
frame and window control how to delete window, while same and other control displaying
some other buffer in it.
Specifically, window means that the window has been specially created by
display-buffer; frame means that a separate frame has been created; same, that the
window has only ever displayed this buffer; other, that the window showed another buffer
before.
The second element, obuffer, is either one of the symbols window or frame, or a list of
the form
(prev-buffer prev-window-start prev-window-point height)
which says which buffer was shown in window before, that buffer’s window start (see
Section 29.20 [Window Start and End], page 711) and window point (see Section 29.19
[Window Point], page 710) positions at that time, and window’s height at that time. If
prev-buffer is still live when quitting window, quitting the window may reuse window to
display prev-buffer.
The third element, owindow, is the window that was selected just before the displaying
was done. If quitting deletes window, it tries to select owindow.
The fourth element, this-buffer, is the buffer whose displaying set the quit-restore
parameter. Quitting window may delete that window only if it still shows that buffer.
Quitting window tries to delete it if and only if (1) method is either window or frame,
(2) the window has no history of previously-displayed buffers and (3) this-buffer equals
the buffer currently displayed in window. If window is part of an atomic window (see
Chapter 29: Windows 703
Section 29.18 [Atomic Windows], page 708), quitting will try to delete the root of that
atomic window instead. In either case, it tries to avoid signaling an error when window
cannot be deleted.
If obuffer is a list, and prev-buffer is still live, quitting displays prev-buffer in window
according to the rest of the elements of obuffer. This includes resizing the window to height
if it was temporarily resized to display this-buffer.
Otherwise, if window was previously used for displaying other buffers (see Section 29.14
[Window History], page 698), the most recent buffer in that history will be displayed.
The following option specifies a function to do the right thing with a frame containing
one window when quitting that window.
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 29.8 [Deleting Windows], page 664).
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.
The following example illustrates how window parameters (see Section 29.27 [Window
Parameters], page 728) can be used with display-buffer-in-side-window (see
Section 29.17.1 [Displaying Buffers in Side Windows], page 704) to set up code for
producing the frame layout sketched above.
Chapter 29: Windows 707
(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)))
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.
Chapter 29: Windows 708
(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.
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 29.13.2
[Buffer Display Action Functions], page 680) 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.
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.
Chapter 29: Windows 710
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.
window-point-insertion-type [Variable]
This variable specifies the marker insertion type (see Section 32.5 [Marker Insertion
Types], page 814) of window-point. The default is nil, so window-point will stay
behind text inserted there.
If update is non-nil, window-end always returns an up-to-date value for where display
ends, based on the current window-start value. If a previously saved value of that
position is still valid, window-end returns that value; otherwise it computes the correct
value by scanning the buffer text.
Even if update is non-nil, window-end does not attempt to scroll the display if point
has moved off the screen, the way real redisplay would do. It does not alter the
window-start value. In effect, it reports where the displayed text will end if scrolling
is not required. Note that the position it returns might be only partially visible.
The display routines insist that the position of point be visible when a buffer is
displayed. Normally, they select the display-start position according to their internal
logic (and scroll the window if necessary) to make point visible. However, if you
specify the start position with this function using nil for noforce, it means you want
display to start at position even if that would put the location of point off the screen.
If this does place point off screen, the display routines attempt to move point to the
left margin on the middle line in the window.
For example, if point is 1 and you set the start of the window to 37, the start of
the next line, point will be above the top of the window. The display routines will
automatically move point if it is still 1 when redisplay occurs. Here is an example:
(set-window-start
(selected-window)
(save-excursion
(goto-char 1)
(forward-line 1)
(point)))
⇒ 37
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))
down. Thus, if you are looking at the middle of a buffer and repeatedly call scroll-down,
you will eventually see the beginning of the buffer.
Unfortunately, this sometimes causes confusion, because some people tend to think in
terms of the opposite convention: they imagine the window moving over text that remains
in place, so that “down” commands take you to the end of the buffer. This convention is
consistent with fact that such a command is bound to a key named PageDown on modern
keyboards.
Textual scrolling functions (aside from scroll-other-window) have unpredictable re-
sults if the current buffer is not the one displayed in the selected window. See Section 28.2
[Current Buffer], page 626.
If the window contains a row taller than the height of the window (for example in
the presence of a large image), the scroll functions will adjust the window’s vertical scroll
position to scroll the partially visible row. Lisp callers can disable this feature by binding
the variable auto-window-vscroll to nil (see Section 29.22 [Vertical Scrolling], page 718).
scroll-up &optional count [Command]
This function scrolls forward by count lines in the selected window.
If count is negative, it scrolls backward instead. If count is nil (or omitted), the
distance scrolled is next-screen-context-lines lines less than the height of the
window’s body.
If the selected window cannot be scrolled any further, this function signals an error.
Otherwise, it returns nil.
scroll-down &optional count [Command]
This function scrolls backward by count lines in the selected window.
If count is negative, it scrolls forward instead. In other respects, it behaves the same
way as scroll-up does.
scroll-up-command &optional count [Command]
This behaves like scroll-up, except that if the selected window cannot be scrolled
any further and the value of the variable scroll-error-top-bottom is t, it tries to
move to the end of the buffer instead. If point is already there, it signals an error.
scroll-down-command &optional count [Command]
This behaves like scroll-down, except that if the selected window cannot be scrolled
any further and the value of the variable scroll-error-top-bottom is t, it tries to
move to the beginning of the buffer instead. If point is already there, it signals an
error.
scroll-other-window &optional count [Command]
This function scrolls the text in another window upward count lines. Negative values
of count, or nil, are handled as in scroll-up.
You can specify which buffer to scroll by setting the variable other-window-scroll-
buffer to a buffer. If that buffer isn’t already displayed, scroll-other-window
displays it in some window.
When the selected window is the minibuffer, the next window is normally the left-
most one immediately above it. You can specify a different window to scroll, when
Chapter 29: Windows 716
other-window-scroll-buffer [Variable]
If this variable is non-nil, it tells scroll-other-window which buffer’s window to
scroll.
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.
recenter-window-group &optional count [Function]
This function is like recenter, except that when the selected window is part of a group
of windows (see [Window Group], page 652), recenter-window-group scrolls the
entire group. This condition holds when the buffer local variable recenter-window-
group-function is set to a function. In this case, recenter-window-group calls the
function with the argument count, then returns its result. The argument count has
the same meaning as in recenter, but with respect to the entire window group.
recenter-redisplay [User Option]
If this variable is non-nil, calling recenter with a nil count argument and non-nil
redisplay argument redraws the frame. The default value is tty, which means only
redraw the frame if it is a tty frame.
recenter-top-bottom &optional count [Command]
This command, which is the default binding for C-l, acts like recenter, except if
called with no argument. In that case, successive calls place point according to the
cycling order defined by the variable recenter-positions.
recenter-positions [User Option]
This variable controls how recenter-top-bottom behaves when called with no ar-
gument. The default value is (middle top bottom), which means that successive
calls of recenter-top-bottom with no argument cycle between placing point at the
middle, top, and bottom of the window.
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.
Note that set-window-hscroll may appear not to work if you test it by evaluating a
call with M-: in a simple way. What happens is that the function sets the horizontal
scroll value and returns, but then redisplay adjusts the horizontal scrolling to make
point visible, and this overrides what the function did. You can observe the function’s
effect if you call it while point is sufficiently far from the left margin that it will remain
visible.
The value returned is columns.
(set-window-hscroll (selected-window) 10)
⇒ 10
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)))))
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 30.3.2
[Frame Font], page 747), 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 29.4 [Window
Sizes], page 652). 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 30.3.2 [Frame Font], page 747) relative to the native
position of frame (see Section 30.3 [Frame Geometry], page 741).
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 30.3.2 [Frame Font], page 747) relative to the
native position of window’s frame (see Section 30.3 [Frame Geometry], page 741).
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.
mode-line
The coordinates are in the mode line of window.
header-line
The coordinates are in the header line of window.
tab-line The coordinates are in the tab line of window.
right-divider
The coordinates are in the divider separating window from a window on
the right.
Chapter 29: Windows 723
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 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.
The following functions return window positions in pixels, relative to the origin of the
display screen rather than that of the frame:
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 40.10 [Size of Displayed
Text], page 1064). Hence, this function may also return nil when the current glyph
matrix of window is not up-to-date.
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.
window (see Section 29.2 [Windows and Frames], page 646). If window is not a live
window, it is replaced by a new live window created on the same frame before putting
state into it. If window is nil, it puts the window state into a new window.
If the optional argument ignore is non-nil, it means to ignore minimum window sizes
and fixed-size restrictions. If ignore is safe, this means windows can get as small as
one line and/or two columns.
By default, the functions that save and restore window configurations or the states of
windows (see Section 29.26 [Window Configurations], page 726) do not care about window
parameters. This means that when you change the value of a parameter within the body
of a save-window-excursion, the previous value is not restored when that macro exits. It
also means that when you restore via window-state-put a window state saved earlier by
window-state-get, all cloned windows have their parameters reset to nil. The following
variable allows you to override the standard behavior:
Chapter 29: Windows 729
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 29.26 [Window Configurations],
page 726.
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 29.8 [Delet-
ing Windows], page 664).
delete-other-windows
This parameter affects the execution of delete-other-windows (see
Section 29.8 [Deleting Windows], page 664).
no-delete-other-windows
This parameter marks the window as not deletable by delete-other-windows
(see Section 29.8 [Deleting Windows], page 664).
split-window
This parameter affects the execution of split-window (see Section 29.7 [Split-
ting Windows], page 662).
Chapter 29: Windows 730
other-window
This parameter affects the execution of other-window (see Section 29.10 [Cyclic
Window Ordering], page 671).
no-other-window
This parameter marks the window as not selectable by other-window (see
Section 29.10 [Cyclic Window Ordering], page 671).
clone-of This parameter specifies the window that this one has been cloned from. It
is installed by window-state-get (see Section 29.26 [Window Configurations],
page 726).
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 29.6 [Preserving Window Sizes], page 660).
quit-restore
This parameter is installed by the buffer display functions (see Section 29.13.1
[Choosing Window], page 678) and consulted by quit-restore-window (see
Section 29.16 [Quitting Windows], page 701). It is a list of four elements, see
the description of quit-restore-window in Section 29.16 [Quitting Windows],
page 701, for details.
window-side
window-slot
These parameters are used internally for implementing side windows (see
Section 29.17 [Side Windows], page 703).
window-atom
This parameter is used internally for implementing atomic windows, see
Section 29.18 [Atomic Windows], page 708.
mode-line-format
This parameter replaces the value of the buffer-local variable mode-line-
format (see Section 24.4.1 [Mode Line Basics], page 516) 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 24.4.1 [Mode Line Basics], page 516) 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.
tab-line-format
This parameter replaces the value of the buffer-local variable tab-line-format
(see Section 24.4.1 [Mode Line Basics], page 516) of this window’s buffer when-
Chapter 29: Windows 731
ever this window is displayed. The symbol none means to suppress display of a
tab line for this window. Display and contents of the tab 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
(see Section 40.16.5 [Display Margins], page 1107. 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 29.28 [Window Hooks],
page 731) 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 a window and making a new
window also call 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 argument window is already set to its new value, and the buffer
to be displayed in the window is set as the current buffer.
These functions must take care when using window-end (see Section 29.20 [Window
Start and End], page 711); 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.
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 24.6.4 [Other Font Lock Variables], page 534.
The remainder of this section covers six hooks that are called during redisplay provided a
significant, non-scrolling change of a window has been detected. For simplicity, these hooks
and the functions they call will be collectively referred to as window change functions. As
Chapter 29: Windows 732
any hook, these hooks can be set either globally of buffer-locally via the local argument of
add-hook (see Section 24.1.2 [Setting Hooks], page 491) when the hook is installed.
The first of these hooks is run after a window buffer change is detected, which means
that a window was created, deleted or assigned another buffer.
window-buffer-change-functions [Variable]
This variable specifies functions called during redisplay when window buffers have
changed. The value should be a list of functions that take one argument.
Functions specified buffer-locally are called for any window showing the corresponding
buffer if that window has been created or assigned that buffer since the last time
window change functions were run. In this case the window is passed as argument.
Functions specified by the default value are called for a frame if at least one window
on that frame has been added, deleted or assigned another buffer since the last time
window change functions were run. In this case the frame is passed as argument.
The second of these hooks is run when a window size change has been detected which
means that a window was created, assigned another buffer, or changed its total size or that
of its text area.
window-size-change-functions [Variable]
This variable specifies functions called during redisplay when a window size change
occurred. The value should be a list of functions that take one argument.
Functions specified buffer-locally are called for any window showing the corresponding
buffer if that window has been added or assigned another buffer or changed its total
or body size since the last time window change functions were run. In this case the
window is passed as argument.
Functions specified by the default value are called for a frame if at least one window
on that frame has been added or assigned another buffer or changed its total or body
size since the last time window change functions were run. In this case the frame is
passed as argument.
The third of these hooks is run when a window selection change has selected another
window since the last redisplay.
window-selection-change-functions [Variable]
This variable specifies functions called during redisplay when the selected window or
a frame’s selected window has changed. The value should be a list of functions that
take one argument.
Functions specified buffer-locally are called for any window showing the corresponding
buffer if that window has been selected or deselected (among all windows or among
all windows on its frame) since the last time window change functions were run. In
this case the window is passed as argument.
Functions specified by the default value are called for a frame if that frame has been
selected or deselected or the frame’s selected window has changed since the last time
window change functions were run. In this case the frame is passed as argument.
The fourth of these hooks is run when a window state change has been detected, which
means that at least one of the three preceding window changes has occurred.
Chapter 29: Windows 733
window-state-change-functions [Variable]
This variable specifies functions called during redisplay when a window buffer or size
change occurred or the selected window or a frame’s selected window has changed.
The value should be a list of functions that take one argument.
Functions specified buffer-locally are called for any window showing the corresponding
buffer if that window has been added or assigned another buffer, changed its total or
body size or has been selected or deselected (among all windows or among all windows
on its frame) since the last time window change functions were run. In this case the
window is passed as argument.
Functions specified by the default value are called for a frame if at least one window
on that frame has been added, deleted or assigned another buffer, changed its total
or body size or that frame has been selected or deselected or the frame’s selected
window has changed since the last time window change functions were run. In this
case the frame is passed as argument.
Functions specified by the default value are also run for a frame when that frame’s
window state change flag (see below) has been set since last redisplay.
The fifth of these hooks is run when a window configuration change has been detected
which means that either the buffer or the size of a window changed. It differs from the four
preceding hooks in the way it is run.
window-configuration-change-hook [Variable]
This variable specifies functions called during redisplay when either the buffer or the
size of a window has changed. The value should be a list of functions that take no
argument.
Functions specified buffer-locally are called for any window showing the corresponding
buffer if at least one window on that frame has been added, deleted or assigned another
buffer or changed its total or body size since the last time window change functions
were run. Each call is performed with the window showing the buffer temporarily
selected and its buffer current.
Functions specified by the default value are called for each frame if at least one
window on that frame has been added, deleted or assigned another buffer or changed
its total or body size since the last time window change functions were run. Each call
is performed with the frame temporarily selected and the selected window’s buffer
current.
Finally, Emacs runs a normal hook that generalizes the behavior of window-state-
change-functions.
window-state-change-hook [Variable]
The default value of this variable specifies functions called during redisplay when a
window state change has been detected or the window state change flag has been set
on at least one frame. The value should be a list of functions that take no argument.
Applications should put a function on this hook only if they want to react to changes
that happened on (or have been signaled for) two or more frames since last redisplay.
In every other case, putting the function on window-state-change-functions should
be preferred.
Chapter 29: Windows 734
Window change functions are called during redisplay for each frame as follows: First, any
buffer-local window buffer change function, window size change function, selected window
change and window state change functions are called in this order. Next, the default values
for these functions are called in the same order. Then any buffer-local window configuration
change functions are called followed by functions specified by the default value of those
functions. Finally, functions on window-state-change-hook are run.
Window change functions are run for a specific frame only if a corresponding change
was registered for that frame earlier. Such changes include the creation or deletion of a
window or the assignment of another buffer or size to a window. Note that even when such
a change has been registered, this does not mean that any of the hooks described above is
run. If, for example, a change was registered within the scope of a window excursion (see
Section 29.26 [Window Configurations], page 726), this will trigger a call of window change
functions only if that excursion still persists at the time change functions are run. If it is
exited earlier, hooks will be run only if registered by a change outside the scope of that
excursion.
The window state change flag of a frame, if set, will cause the default values of
window-state-change-functions (for that frame) and window-state-change-hook to
be run during next redisplay regardless of whether a window state change actually occurred
for that frame or not. After running any functions on these hooks, the flag is reset for each
frame. Applications can set that flag and inspect its value using the following functions.
While window change functions are run, the functions described next can be called to get
more insight into what has changed for a specific window or frame since the last redisplay.
All these functions take a live window as single, optional argument, defaulting to the selected
window.
30 Frames
A frame is a screen object that contains one or more Emacs windows (see Chapter 29
[Windows], page 644). 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.5.4 [Frame Type], page 27.
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 29.7
[Splitting Windows], page 662.
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.5.5
[Terminal Type], page 27.
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 30.2 [Multiple Terminals], page 738.
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 30: Frames 737
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.
terminal-list [Function]
This function returns a list of all live terminal objects.
on a text terminal), it does so at this time. In all other respects, this function behaves
like make-frame (see Section 30.1 [Creating Frames], page 737).
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.
x-open-connection display &optional xrm-string must-succeed [Function]
This function opens a connection to the X display display, without creating a frame
on that display. Normally, Emacs Lisp programs need not call this function, as
make-frame-on-display calls it automatically. The only reason for calling it is to
check whether communication can be established with a given X display.
The optional argument xrm-string, if not nil, is a string of resource names and values,
in the same format used in the .Xresources file. See Section “X Resources” in The
GNU Emacs Manual. These values apply to all Emacs frames created on this display,
overriding the resource values recorded in the X server. Here’s an example of what
this string might look like:
"*BorderWidth: 3\n*InternalBorder: 2\n"
If must-succeed is non-nil, failure to open the connection terminates Emacs. Other-
wise, it is an ordinary Lisp error.
x-close-connection display [Function]
This function closes the connection to display display. Before you can do this, you
must first delete all the frames that were open on that display (see Section 30.7
[Deleting Frames], page 772).
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.
display-monitor-attributes-list &optional display [Function]
This function returns a list of physical monitor attributes on display, which can be a
display name (a string), a terminal, or a frame; if omitted or nil, it defaults to the
selected frame’s display. Each element of the list is an association list, representing
the attributes of a physical monitor. The first element corresponds to the primary
monitor. The attribute keys and values are:
‘geometry’
Position of the top-left corner of the monitor’s screen and its size, in
pixels, as ‘(x y width height)’. Note that, if the monitor is not the
primary monitor, some of the coordinates might be negative.
‘workarea’
Position of the top-left corner and size of the work area (usable space) in
pixels as ‘(x y width height)’. This may be different from ‘geometry’ in
that space occupied by various window manager features (docks, taskbars,
etc.) may be excluded from the work area. Whether or not such features
actually subtract from the work area depends on the platform and envi-
ronment. Again, if the monitor is not the primary monitor, some of the
coordinates might be negative.
Chapter 30: Frames 741
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 30.2 [Multiple Terminals], page 738) 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 30.11 [Visibility of Frames], page 778) 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 30.4.3.2 [Position Parameters], page 756). For a normal,
Chapter 30: Frames 743
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 30.14
[Child Frames], page 780) 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.
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 30.4.3.3 [Size Param-
eters], page 758). 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 30.4.3.8 [Management Parameters], page 765).
Outer Border
The outer border is a separate border whose width can be specified with
the border-width frame parameter (see Section 30.4.3.4 [Layout Parameters],
page 760). 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 40.25 [Tooltips], page 1147),
child frames (see Section 30.14 [Child Frames], page 780) and undecorated
or override-redirect frames (see Section 30.4.3.8 [Management Parameters],
page 765).
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 30.4.3.4 [Layout Parameters], page 760).
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 30.6 [Frame
Titles], page 771) 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 30.4.3.3 [Size Parameters],
page 758), tooltip (see Section 40.25 [Tooltips], page 1147) and child frames (see
Section 30.14 [Child Frames], page 780) 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 30.4.3.8 [Management Pa-
rameters], page 765).
Menu Bar The menu bar (see Section 23.17.5 [Menu Bar], page 482) 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 29.2 [Windows and
Chapter 30: Frames 744
Frames], page 646). As a rule, menu bars are never shown on child frames
(see Section 30.14 [Child Frames], page 780). Display of the menu bar can
be suppressed by setting the menu-bar-lines parameter (see Section 30.4.3.4
[Layout Parameters], page 760) to zero.
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 23.17.6 [Tool Bar], page 483) 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 30.14 [Child Frames],
page 780). Display of the tool bar can be suppressed by setting the tool-bar-
lines parameter (see Section 30.4.3.4 [Layout Parameters], page 760) 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.
Tab Bar The tab bar (see Section “Tab Bars” in The GNU Emacs Manual) is always
drawn by Emacs itself. The tab bar appears above the tool bar in Emacs built
with an internal tool bar, and below the tool bar in builds with an external tool
bar. Display of the tab bar can be suppressed by setting the tab-bar-lines
parameter (see Section 30.4.3.4 [Layout Parameters], page 760) to zero.
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
Chapter 30: Frames 745
frame, see Section 30.4.3.4 [Layout Parameters], page 760. Its height can be
obtained by removing from that of the native height the widths of the internal
border and the heights of the frame’s internal menu and tool bars, the tab bar
and one horizontal scroll bar if specified for this frame.
The absolute position of a frame is given as a pair (X, Y) of horizontal and vertical
pixel offsets relative to an origin (0, 0) of the frame’s display. Correspondingly, the absolute
edges of a frame are given as pixel offsets from that origin.
Note that with multiple monitors, the origin of the display does not necessarily coincide
with the top-left corner of the entire usable display area of the terminal. Hence the abso-
lute position of a frame can be negative in such an environment even when that frame is
completely visible.
By convention, vertical offsets increase “downwards”. This means that the height of a
frame is obtained by subtracting the offset of its top edge from that of its bottom edge.
Horizontal offsets increase “rightwards”, as expected, so a frame’s width is calculated by
subtracting the offset of its left edge from that of its right edge.
For a frame on a graphical terminal the following function returns the sizes of the areas
described above:
menu-bar-external
If non-nil, this means the menu bar is external (not part of the native
frame of frame).
menu-bar-size
A cons of the width and height of the menu bar of frame.
tool-bar-external
If non-nil, this means the tool bar is external (not part of the native
frame of frame).
tool-bar-position
This tells on which side the tool bar on frame is and can be one of left,
top, right or bottom. The only toolkit that currently supports a value
other than top is GTK+.
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.
The default font can be also set directly with the following function:
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 30.14 [Child
Frames], page 780), the functions are run only when the position of the frame changes
in relation to that of its parent frame.
multiple of its character size, however, may: be ignored, cause a rounding (GTK+),
or be accepted (Lucid, Motif, MS-Windows).
With some window managers you may have to set this to non-nil in order to make
a frame appear truly maximized or full-screen.
set-frame-size frame width height &optional pixelwise [Function]
This function sets the size of the text area of frame, measured in terms of the canonical
height and width of a character on frame (see Section 30.3.2 [Frame Font], page 747).
The optional argument pixelwise non-nil means to measure the new width and height
in units of pixels instead. Note that if frame-resize-pixelwise is nil, some toolkits
may refuse to truly honor the request if it does not increase/decrease the frame size
to a multiple of its character size.
set-frame-height frame height &optional pretend pixelwise [Function]
This function resizes the text area of frame to a height of height lines. The sizes of
existing windows in frame are altered proportionally to fit.
If pretend is non-nil, then Emacs displays height lines of output in frame, but does
not change its value for the actual height of the frame. This is only useful on text
terminals. Using a smaller height than the terminal actually implements may be useful
to reproduce behavior observed on a smaller screen, or if the terminal malfunctions
when using its whole screen. Setting the frame height directly does not always work,
because knowing the correct actual size may be necessary for correct cursor positioning
on text terminals.
The optional fourth argument pixelwise non-nil means that frame should be height
pixels high. Note that if frame-resize-pixelwise is nil, some window managers
may refuse to truly honor the request if it does not increase/decrease the frame height
to a multiple of its character height.
When used interactively, this command will ask the user for the number of lines to
set the height of the currently selected frame. You can also provide this value with a
numeric prefix.
set-frame-width frame width &optional pretend pixelwise [Function]
This function sets the width of the text area of frame, measured in characters. The
argument pretend has the same meaning as in set-frame-height.
The optional fourth argument pixelwise non-nil means that frame should be width
pixels wide. Note that if frame-resize-pixelwise is nil, some window managers
may refuse to fully honor the request if it does not increase/decrease the frame width
to a multiple of its character width.
When used interactively, this command will ask the user for the number of columns
to set the width of the currently selected frame. You can also provide this value with
a numeric prefix.
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
Chapter 30: Frames 752
parameters min-width and min-height (see Section 30.4.3.3 [Size Parameters], page 758)
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 29.28 [Window
Hooks], page 731) 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.
frame-size-changed-p &optional frame [Function]
This function returns non-nil when the inner width or height of frame has changed
since window-size-change-functions was run the last time for frame. It always
returns nil immediately after running window-size-change-functions for frame.
Note also that window managers usually do not ask for resizing a frame when they
change the number of lines occupied by an external menu or tool bar. Typically, such
“wrappings” occur when a user shrinks a frame horizontally, making it impossible to
display all elements of its menu or tool bar. They may also result from a change of the
major mode altering the number of items of a menu or tool bar. Any such wrappings
may implicitly alter the number of lines of a frame’s text area and are unaffected by
the setting of this option.
specifying that a frame should from now on have a menu and/or tool bar instead of
none and simultaneously specifying the new height of the frame will inevitably lead
to a recalculation of the frame’s height. Conceptually, in such case, this function will
try to have the explicit height specification prevail. It cannot be excluded, however,
that the addition (or removal) of the menu or tool bar, when eventually performed
by the toolkit, will defeat this intention.
Sometimes, binding frame-inhibit-implied-resize (see Section 30.3.5 [Implied
Frame Resizing], page 752) to a non-nil value around calls to this function may
fix the problem sketched here. Sometimes, however, exactly such binding may be hit
by the problem.
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.
Chapter 30: Frames 755
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.
If you specify the frame name explicitly when you create the frame, the name
is also used (instead of the name of the Emacs executable) when looking up X
resources for the frame.
explicit-name
If the frame name was specified explicitly when the frame was created, this pa-
rameter will be that name. If the frame wasn’t explicitly named, this parameter
will be nil.
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 window-system will display the window that corresponds to
the frame 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 30.12 [Raising and Lowering], page 779).
are more suited to ensure that a child frame always fits within
the area of its parent frame as, for example, when customizing
display-buffer-alist (see Section 29.13.1 [Choosing Window],
page 678) via display-buffer-in-child-frame.
Regardless of how this parameter was specified, functions reporting the value of
this parameter like frame-parameters always report the width of the frame’s
text area in characters as an integer rounded, if necessary, to a multiple of the
frame’s default character width. That value is also used by the desktop saving
routines.
height This parameter specifies the height of the frame. It works just like width,
except vertically instead of horizontally.
user-size
This does for the size parameters height and width what the user-position
parameter (see Section 30.4.3.2 [Position Parameters], page 756) does for the
position parameters top and left.
min-width
This parameter specifies the minimum native width (see Section 30.3 [Frame
Geometry], page 741) 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 30.3 [Frame
Geometry], page 741) 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
Chapter 30: Frames 760
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 30.3.4 [Frame Size], page 749) 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.
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 29.5 [Resizing Windows], page 657).
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 29.5 [Resizing Windows], page 657).
vertical-scroll-bars
Whether the frame has scroll bars (see Section 40.14 [Scroll Bars], page 1099) for
vertical scrolling, and which side of the frame they should be on. The possible
values are left, right, and nil for no scroll bars.
horizontal-scroll-bars
Whether the frame has scroll bars for horizontal scrolling (t and bottom mean
yes, nil means no).
scroll-bar-width
The width of vertical scroll bars, in pixels, or nil meaning to use the default
width.
scroll-bar-height
The height of horizontal scroll bars, in pixels, or nil meaning to use the default
height.
left-fringe
right-fringe
The default width of the left and right fringes of windows in this frame (see
Section 40.13 [Fringes], page 1093). If either of these is zero, that effectively
removes the corresponding fringe.
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 40.15 [Window
Dividers], page 1102) 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 40.15 [Win-
dow Dividers], page 1102) 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 23.17.5 [Menu Bar], page 482). 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 30.3.1 [Frame Layout], page 742),
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 30.3 [Frame Geometry], page 741) 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 23.17.6 [Tool Bar],
page 483). 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 30.3.1 [Frame Layout], page 742).
Chapter 30: Frames 762
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.
tab-bar-lines
The number of lines to use for the tab bar (see Section “Tab Bars” in The GNU
Emacs Manual). The default is one if Tab Bar mode is enabled and zero oth-
erwise. This value may change whenever the tab bar wraps (see Section 30.3.1
[Frame Layout], page 742).
line-spacing
Additional space to leave below each text line, in pixels (a positive integer).
See Section 40.11 [Line Height], page 1067, for more information.
no-special-glyphs
If this is non-nil, it suppresses the display of any truncation and continuation
glyphs (see Section 40.3 [Truncation], page 1038) 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 29.5 [Resizing Windows], page 657).
unsplittable
If non-nil, this frame’s window is never split automatically.
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.
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.
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 30.11 [Visibility of Frames], page 778). 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 30.10 [Input Focus], page 774) or
mouse-autoselect-window (see Section 29.25 [Mouse Window Auto-selection],
page 725). 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.
override-redirect
If non-nil, this means that this is an override redirect frame—a frame not han-
dled 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, and if set to light use the “aqua” 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.
Chapter 30: Frames 767
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 30.14 [Child Frames], page 780).
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 40.12.11 [Fontsets], page 1086). It is equivalent to the font attribute
of the default face.
foreground-color
The color to use for characters. 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 30: Frames 770
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.
30.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 30.4.3.2 [Position Parameters], page 756).
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.
list that you get is newly created, so modifying the list doesn’t have any effect on the
internals of Emacs.
visible-frame-list [Function]
This function returns a list of just the currently visible frames. See Section 30.11
[Visibility of Frames], page 778. Frames on text terminals always count as visible,
even though only the selected one is actually displayed.
a window Consider only the frames using that particular window as their minibuffer
window.
anything else
Consider all frames.
See also next-window and previous-window, in Section 29.10 [Cyclic Window Ordering],
page 671.
Chapter 30: Frames 774
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 30.2 [Multiple Terminals], page 738.
selected-frame [Function]
This function returns the selected frame.
Some window systems and window managers direct keyboard input to the window object
that the mouse is in; others require explicit clicks or commands to shift the focus to various
window objects. Either way, Emacs automatically keeps track of which frames have focus.
To explicitly switch to a different frame from a Lisp function, call select-frame-set-
input-focus.
The plural “frames” in the previous paragraph is deliberate: while Emacs itself has
only one selected frame, Emacs can have frames on many different terminals (recall that a
connection to a window system counts as a terminal), and each terminal has its own idea
Chapter 30: Frames 775
of which frame has input focus. When you set the input focus to a frame, you set the focus
for that frame’s terminal, but frames on other terminals may still remain focused.
Lisp programs can switch frames temporarily by calling the function select-frame. This
does not alter the window system’s concept of focus; rather, it escapes from the window
manager’s control until that control is somehow reasserted.
When using a text terminal, only one frame can be displayed at a time on the terminal,
so after a call to select-frame, the next redisplay actually displays the newly selected
frame. This frame remains selected until a subsequent call to select-frame. Each frame
on a text terminal has a number which appears in the mode line before the buffer name
(see Section 24.4.4 [Mode Line Variables], page 519).
select-frame-set-input-focus frame &optional norecord [Function]
This function selects frame, raises it (should it happen to be obscured by other frames)
and tries to give it the window system’s focus. On a text terminal, the next redisplay
displays the new frame on the entire terminal screen. The optional argument norecord
has the 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 30.14 [Child Frames], page 780), 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 29.3 [Selecting Windows], page 650.
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.
Chapter 30: Frames 776
Emacs cooperates with the window system by arranging to select frames as the server
and window manager request. When a window system informs Emacs that one of its
frames has been selected, Emacs internally generates a focus-in event. When an Emacs
frame is displayed on a text-terminal emulator, such as xterm, which supports reporting of
focus-change notification, the focus-in and focus-out events are available even for text-mode
frames. Focus events are normally handled by handle-focus-in.
see this last state in TTY frames running on terminals that do not support explicit
focus notifications.)
after-focus-change-function [Variable]
This function is an extension point that code can use to receive a notification that
focus has changed.
This function is called with no arguments when Emacs notices that the set of focused
frames may have changed. Code wanting to do something when frame focus changes
should use add-function to add a function to this one, and in this added function, re-
scan the set of focused frames, calling frame-focus-state to retrieve the last known
focus state of each frame. Focus events are delivered asynchronously, and frame input
focus according to an external system may not correspond to the notion of the Emacs
selected frame. Multiple frames may appear to have input focus simultaneously due
to focus event delivery differences, the presence of multiple Emacs terminals, and
other factors, and code should be robust in the face of this situation.
Depending on window system, focus events may also be delivered repeatedly and with
different focus states before settling to the expected values. Code relying on focus
notifications should “debounce” any user-visible updates arising from focus changes,
perhaps by deferring work until redisplay.
This function may be called in arbitrary contexts, including from inside read-event,
so take the same care as you might when writing a process filter.
focus-follows-mouse [User Option]
This option informs Emacs whether and how the window manager transfers focus
when you move the mouse pointer into a frame. It can have three meaningful values:
nil The default value nil should be used when your window manager follows
a “click-to-focus” policy where you have to click the mouse inside of a
frame in order for that frame to gain focus.
t The value t should be used when your window manager has the focus
automatically follow the position of the mouse pointer but a frame that
gains focus is not raised automatically and may even remain occluded by
other window-system windows.
auto-raise
The value auto-raise should be used when your window manager has
the focus automatically follow the position of the mouse pointer and a
frame that gains focus is raised automatically.
If this option is non-nil, Emacs moves the mouse pointer to the frame selected by
select-frame-set-input-focus. That function is used by a number of commands
like, for example, other-frame and pop-to-buffer.
The distinction between the values t and auto-raise is not needed for “normal”
frames because the window manager usually takes care of raising them. It is useful
to automatically raise child frames via mouse-autoselect-window (see Section 29.25
[Mouse Window Auto-selection], page 725).
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
Chapter 30: Frames 778
another window-system 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 29.25 [Mouse Window
Auto-selection], page 725).
The visibility status of a frame is also available as a frame parameter. You can read or
change it as such. See Section 30.4.3.8 [Management Parameters], page 765. 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 22.7.10 [Misc Events], page 424.
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 30.4.3.2 [Position
Parameters], page 756) 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 30.8 [Finding
All Frames], page 772).
On window systems, you can also enable auto-raising (on frame selection) or auto-
lowering (on frame deselection) using frame parameters. See Section 30.4.3.8 [Management
Parameters], page 765.
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.
they may overlap each other—changing the size or position of one child frame does not
change the size or position of any of its sibling child frames.
By design, operations to make or modify child frames are implemented with the help of
frame parameters (see Section 30.4 [Frame Parameters], page 753) without any specialized
functions or customizable variables. Note that child frames are meaningful on graphical
terminals only.
To create a new child frame or to convert a normal frame into a child frame, set that
frame’s parent-frame parameter (see Section 30.4.3.6 [Frame Interaction Parameters],
page 763) to that of an already existing frame. The frame specified by that parameter
will then be the frame’s parent frame as long as the parameter is not changed or reset.
Technically, this makes the child frame’s window-system window a child window of the
parent frame’s window-system window.
The parent-frame parameter can be changed at any time. Setting it to another frame
reparents the child frame. Setting it to another child frame makes the frame a nested child
frame. Setting it to nil restores the frame’s status as a top-level frame—a frame whose
window-system window is a child of its display’s root window.
Since child frames can be arbitrarily nested, a frame can be both a child and a parent
frame. Also, the relative roles of child and parent frame may be reversed at any time
(though it’s usually a good idea to keep the size of a child frame sufficiently smaller than
that of its parent). An error will be signaled for the attempt to make a frame an ancestor
of itself.
Most window-systems clip a child frame at the native edges (see Section 30.3 [Frame
Geometry], page 741) of its parent frame—everything outside these edges is usually invis-
ible. A child frame’s left and top parameters specify a position relative to the top-left
corner of its parent’s native frame. When the parent frame is resized, this position remains
conceptually unaltered.
NS builds do not clip child frames at the parent frame’s edges, allowing them to be
positioned so they do not obscure the parent frame while still being visible themselves.
Usually, moving a parent frame moves along all its child frames and their descendants as
well, keeping their relative positions unaltered. Note that the hook move-frame-functions
(see Section 30.3.3 [Frame Position], page 748) is run for a child frame only when the position
of the child frame relative to its parent frame changes.
When a parent frame is resized, its child frames conceptually retain their previous sizes
and their positions relative to the left upper corner of the parent. This means that a
child frame may become (partially) invisible when its parent frame shrinks. The parameter
keep-ratio (see Section 30.4.3.6 [Frame Interaction Parameters], page 763) can be used
to resize and reposition a child frame proportionally whenever its parent frame is resized.
This may avoid obscuring parts of a frame when its parent frame is shrunk.
A visible child frame always appears on top of its parent frame thus obscuring parts of
it, except on NS builds where it may be positioned beneath the parent. This is comparable
to the window-system window of a top-level frame which also always appears on top of
its parent window—the desktop’s root window. When a parent frame is iconified or made
invisible (see Section 30.11 [Visibility of Frames], page 778), its child frames are made
invisible. When a parent frame is deiconified or made visible, its child frames are made
visible.
Chapter 30: Frames 782
When a parent frame is about to be deleted (see Section 30.7 [Deleting Frames],
page 772), its child frames are recursively deleted before it. There is one exception to
this rule: When the child frame serves as a surrogate minibuffer frame (see Section 30.9
[Minibuffers and Frames], page 774) for another frame, it is retained until the parent frame
has been deleted. If, at this time, no remaining frame uses the child frame as its minibuffer
frame, Emacs will try to delete the child frame too. If that deletion fails for whatever
reason, the child frame is made a top-level frame.
Whether a child frame can have a menu or tool bar is window-system or window manager
dependent. Most window-systems explicitly disallow menu 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 30.3 [Frame Geometry], page 741). When the child frame
does not show a menu or tool bar, any other of the frame’s borders (see Section 30.4.3.4
[Layout Parameters], page 760) 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 30.4.3.8 [Management Parameters], page 765).
To resize or move an undecorated child frame with the mouse, special frame parameters
(see Section 30.4.3.7 [Mouse Dragging Parameters], page 764) 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 21.11 [Minibuffer Windows], page 396) 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 29.27 [Window
Parameters], page 728). 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.
When the user drags a frame with a mouse and overshoots, it’s easy to drag a frame out of
the screen area of its parent. Retrieving such a frame can be hairy once the mouse button has
been released. To prevent such a situation, it is advisable to set the frame’s top-visible or
bottom-visible parameter (see Section 30.4.3.7 [Mouse Dragging Parameters], page 764).
Set the top-visible parameter of a child frame to a number when you intend to al-
low the user dragging that frame by its header line. Setting top-visible to a number
inhibits dragging the top edge of the child frame above the top edge of its parent. Set the
bottom-visible parameter to a number when you intend to drag that frame via its mode
line; this inhibits dragging the bottom edge of the child frame beneath the bottom edge of
Chapter 30: Frames 783
its parent. In either case, that number also specifies width and height (in pixels) of the area
of the child frame that remains visible during dragging.
When a child frame is used for displaying a buffer via display-buffer-in-child-frame
(see Section 29.13.2 [Buffer Display Action Functions], page 680), the frame’s auto-hide-
function parameter (see Section 30.4.3.6 [Frame Interaction Parameters], page 763) 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 30.4.3.6 [Frame
Interaction Parameters], page 763) 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 30.12 [Raising and Lower-
ing], page 779) or changing the z-group (see Section 30.4.3.2 [Position Parameters],
page 756) 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 30.4.3.10 [Font
and Color Parameters], page 768) 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 29.25 [Mouse Window Auto-selection], page 725).
• Dropping (see Section 30.21 [Drag and Drop], page 790) 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:
ancestor of descendant’s parent frame. Both, ancestor and descendant must specify
live frames.
The usual purpose of tracking mouse motion is to indicate on the screen the consequences
of pushing or releasing a button at the current position.
In many cases, you can avoid the need to track the mouse by using the mouse-face text
property (see Section 33.19.4 [Special Properties], page 866). That works at a much lower
level and runs more smoothly than Lisp-level mouse tracking.
mouse-position [Function]
This function returns a description of the position of the mouse. The value looks
like (frame x . y), where x and y are integers giving the (possibly rounded) position
in multiples of the default character size of frame (see Section 30.3.2 [Frame Font],
page 747) relative to the native position of frame (see Section 30.3 [Frame Geometry],
page 741).
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.
tty-menu-calls-mouse-position-function [Variable]
If non-nil, TTY menus will call mouse-position-function as described above. This
exists for cases where mouse-position-function is not safe to be called by the TTY
menus, such as if it could trigger redisplay.
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:
frame-pointer-visible-p &optional frame [Function]
This predicate function returns non-nil if the mouse pointer displayed on frame is
visible; otherwise it returns nil. frame omitted or nil means the selected frame.
This is useful when make-pointer-invisible is set to t: it allows you to know if
the pointer has been hidden. See Section “Mouse Avoidance” in The Emacs Manual.
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 23.17.5
[Menu Bar], page 482.
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 nil appears in the list, it separates the left-hand items from the right-hand items;
items that precede the nil appear on the left, and items that follow the nil appear
on the right. If you don’t include a nil in the list, then approximately half the items
appear on each side.
Dialog boxes always appear in the center of a frame; the argument position specifies
which frame. The possible values are as in x-popup-menu, but the precise coordinates
or the individual window don’t matter; only the frame matters.
If header is non-nil, the frame title for the box is ‘Information’, otherwise it is
‘Question’. The former is used for message-box (see [message-box], page 1041). (On
text terminals, the box title is not displayed.)
In some configurations, Emacs cannot display a real dialog box; so instead it displays
the same items in a pop-up menu in the center of the frame.
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.
Chapter 30: Frames 789
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 30.4.3.10 [Font and Color Parameters], page 768.
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.
⇒ nil
The color values are returned for frame’s display. If frame is omitted or nil, the
information is returned for the selected frame’s display. If the frame cannot display
colors, the value is nil.
This function used to be called x-color-values, and that name is still supported as
an alias.
30.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-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.
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.
Chapter 30: Frames 794
Values can be the symbols always, when-mapped, or not-useful. The function can
also return nil when the question is inapplicable to a certain kind of display.
These functions obtain additional information about the window system in use where
Emacs shows the specified display. (Their names begin with x- for historical reasons.)
31 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 32 [Markers], page 811.
See also the field feature (see Section 33.19.9 [Fields], page 877), which provides functions
that are used by many cursor-motion commands.
31.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 31.4 [Narrowing], page 808), 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 29.19 [Window Point], page 710, 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 31.4 [Narrowing], page 808.)
Chapter 31: Positions 798
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 31.4 [Narrowing],
page 808.)
31.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 31.1 [Point], page 797.
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.
start of that screen line. Note that cols are counted from the visual start of the
line; if the window is scrolled horizontally (see Section 29.23 [Horizontal Scrolling],
page 719), 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.
count-screen-lines &optional beg end count-final-newline window [Function]
This function returns the number of screen lines in the text from beg to end. The
number of screen lines may be different from the number of actual lines, due to line
continuation, the display table, etc. If beg and end are nil or omitted, they default
to the beginning and end of the accessible portion of the buffer.
If the region ends with a newline, that is ignored unless the optional third argument
count-final-newline is non-nil.
The optional fourth argument window specifies the window for obtaining parameters
such as width, horizontal scrolling, and so on. The default is to use the selected
window’s parameters.
Like vertical-motion, count-screen-lines always uses the current buffer, regard-
less of which buffer is displayed in window. This makes possible to use count-screen-
lines in any buffer, whether or not it is currently displayed in some window.
move-to-window-line count [Command]
This function moves point with respect to the text currently displayed in the selected
window. It moves point to the beginning of the screen line count screen lines from the
top of the window; zero means the topmost line. If count is negative, that specifies a
position −count lines from the bottom (or the last line of the buffer, if the buffer ends
above the specified screen position); thus, count of −1 specifies the last fully visible
screen line of the window.
If count is nil, then point moves to the beginning of the line in the middle of the
window. If the absolute value of count is greater than the size of the window, then
point moves to the place that would appear on that screen line if the window were tall
enough. This will probably cause the next redisplay to scroll to bring that location
onto the screen.
In an interactive call, count is the numeric prefix argument.
The value returned is the screen line number point has moved to, relative to the top
line of the window.
Chapter 31: Positions 804
(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 21.12 [Minibuffer Contents], page 398.
(forward-sexp 3)
⇒ nil
beginning-of-defun-function [Variable]
If non-nil, this variable holds a function for finding the beginning of a defun. The
function beginning-of-defun calls this function instead of using its normal method,
passing it its optional argument. If the argument is non-nil, the function should
move back by that many functions, like beginning-of-defun does.
end-of-defun-function [Variable]
If non-nil, this variable holds a function for finding the end of a defun. The function
end-of-defun calls this function instead of using its normal method.
31.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 28.2 [Current Buffer], page 626). If
you need to save or restore window configurations, see the forms described in Section 29.26
[Window Configurations], page 726, and in Section 30.13 [Frame Configurations], page 780.
Chapter 31: Positions 808
31.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 31.1 [Point],
page 797); 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 31: Positions 809
If you need to display in a single buffer several very different types of text, consider using
an alternative facility described in Section 28.12 [Swapping Text], page 642.
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")))
32 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 31.1 [Point], page 797. 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 31.4 [Narrowing], page 808.
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 31.4 [Narrowing], page 808.
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 32: Markers 814
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 40 [Display], page 1037.)
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))).
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.
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).
Chapter 32: Markers 818
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.
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 32.8 [The Region], page 819).
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 when the region is
reactivated, for instance after using a command that switches back to a buffer that
has an active mark.
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 22.2.2 [Interactive
Codes], page 404).
If shift-select-mode is non-nil and the current command was invoked via shift
translation (see Section 22.8.1 [Key Sequence Input], page 432), 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>
...)
Chapter 32: Markers 819
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 22.1 [Command Overview], page 401). 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 135); 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.
820
33 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 33.9 [Undo], page 837).
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 32 [Markers], page 811) or numeric character positions (see Chapter 31 [Positions],
page 797). 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 31.1 [Point], page 797.
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 31.1 [Point], page 797.
bolp [Function]
This function returns t if point is at the beginning of a line. See Section 31.2.4 [Text
Lines], page 800. 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 33.19 [Text Properties], page 858.
However, overlays (see Section 40.9 [Overlays], page 1056) in the buffer and their
properties are ignored, not copied.
For example, if Font-Lock mode is enabled, you might get results like these:
(buffer-substring 1 10)
⇒ #("This is t" 0 1 (fontified t) 1 9 (fontified t))
buffer-substring-no-properties start end [Function]
This is like buffer-substring, except that it does not copy text properties, just the
characters themselves. See Section 33.19 [Text Properties], page 858.
buffer-string [Function]
This function returns the contents of the entire accessible portion of the current buffer,
as a string. If the text being copied has any text properties, these are copied into the
string along with the characters they belong to.
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 40.26 [Bidirectional
Display], page 1148).
filter-buffer-substring start end &optional delete [Function]
This function filters the buffer text between start and end using a function specified
by the variable filter-buffer-substring-function, and returns the result.
The default filter function consults the obsolete wrapper hook filter-buffer-
substring-functions (see the documentation string of the macro with-wrapper-
hook for the details about this obsolete facility), and the obsolete variable
buffer-substring-filters. If both of these are nil, it returns the unaltered text
from the buffer, i.e., what buffer-substring would return.
If delete is non-nil, the function deletes the text between start and end after copying
it, like delete-and-extract-region.
Lisp code should use this function instead of buffer-substring, buffer-substring-
no-properties, or delete-and-extract-region when copying into user-accessible
data structures such as the kill-ring, X clipboard, and registers. Major and minor
modes can modify filter-buffer-substring-function to alter such text as it is
copied out of the buffer.
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 33: Text 823
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 33: Text 824
thing-at-point-provider-alist [Variable]
This variable allows users and modes to tweak how thing-at-point works.
It’s an association list of things and functions (called with zero parameters) to
return that thing. Entries for thing will be evaluated in turn until a non-nil
result is returned.
For instance, a major mode could say:
(setq-local thing-at-point-provider-alist
(append thing-at-point-provider-alist
'((url . my-mode--url-at-point))))
If no providers have a non-nil return, the thing will be computed the standard
way.
at the place of insertion, insertion may or may not relocate the marker, depending on the
marker’s insertion type (see Section 32.5 [Marker Insertion Types], page 814). Certain
special functions such as insert-before-markers relocate all such markers to point after
the inserted text, regardless of the markers’ insertion type.
Insertion functions signal an error if the current buffer is read-only (see Section 28.7
[Read Only Buffers], page 635) or if they insert within read-only text (see Section 33.19.4
[Special Properties], page 866).
These functions copy text characters from strings and buffers along with their properties.
The inserted characters have exactly the same properties as the characters they were copied
from. By contrast, characters specified as separate arguments, not part of a string or buffer,
inherit their text properties from the neighboring text.
The insertion functions convert text from unibyte to multibyte in order to insert in a
multibyte buffer, and vice versa—if the text comes from a string or from a buffer. However,
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 34.3 [Converting Representa-
tions], page 902.
insert &rest args [Function]
This function inserts the strings and/or characters args into the current buffer, at
point, moving point forward. In other words, it inserts the text before point. An
error is signaled unless all args are either strings or characters. The value is nil.
insert-before-markers &rest args [Function]
This function inserts the strings and/or characters args into the current buffer, at
point, moving point forward. An error is signaled unless all args are either strings or
characters. The value is nil.
This function is unlike the other insertion functions in that it relocates markers ini-
tially pointing at the insertion point, to point after the inserted text. If an overlay
begins at the insertion point, the inserted text falls outside the overlay; if a nonempty
overlay ends at the insertion point, the inserted text falls inside that overlay.
insert-char character &optional count inherit [Command]
This command inserts count instances of character into the current buffer before
point. The argument count must be an integer, and character must be a character.
If called interactively, this command prompts for character using its Unicode name
or its code point. See Section “Inserting Text” in The GNU Emacs Manual.
This function does not convert unibyte character codes 128 through 255 to multibyte
characters, not even if the current buffer is a multibyte buffer. See Section 34.3
[Converting Representations], page 902.
If inherit is non-nil, the inserted characters inherit sticky text properties from the two
characters before and after the insertion point. See Section 33.19.6 [Sticky Properties],
page 873.
insert-buffer-substring from-buffer-or-name &optional start end [Function]
This function inserts a portion of buffer from-buffer-or-name into the current buffer
before point. The text inserted is the region between start (inclusive) and end (ex-
clusive). (These arguments default to the beginning and end of the accessible portion
of that buffer.) This function returns nil.
Chapter 33: Text 826
In this example, the form is executed with buffer ‘bar’ as the current buffer. We
assume that buffer ‘bar’ is initially empty.
---------- Buffer: foo ----------
We hold these truths to be self-evident, that all
---------- Buffer: foo ----------
See Section 33.19.6 [Sticky Properties], page 873, for other insertion functions that inherit
text properties from the nearby text in addition to inserting it. Whitespace inserted by
indentation functions also inherits text properties.
This command calls auto-fill-function whenever that is non-nil and the character
inserted is in the table auto-fill-chars (see Section 33.14 [Auto Filling], page 846).
This command performs abbrev expansion if Abbrev mode is enabled and the in-
serted character does not have word-constituent syntax. (See Chapter 37 [Abbrevs],
page 975, and Section 36.2.1 [Syntax Class Table], page 959.) It is also responsible
for calling blink-paren-function when the inserted character has close parenthesis
syntax (see Section 40.21 [Blinking], page 1139).
The final thing this command does is to run the hook post-self-insert-hook. You
could use this to automatically reindent text as it is typed, for example. If any function
on this hook needs to act on the region (see Section 32.8 [The Region], page 819), it
should make sure Delete Selection mode (see Section “Using Region” in The GNU
Emacs Manual) doesn’t delete the region before post-self-insert-hook functions
are invoked. The way to do so is to add a function that returns nil to self-insert-
uses-region-functions, a special hook that tells Delete Selection mode it should
not delete the region.
Do not try substituting your own definition of self-insert-command for the standard
one. The editor command loop handles this function specially.
newline &optional number-of-newlines interactive [Command]
This command inserts newlines into the current buffer before point. If number-of-
newlines is supplied, that many newline characters are inserted. In an interactive call,
number-of-newlines is the numeric prefix argument.
This command calls self-insert-command to insert newlines, which may subse-
quently break the preceding line by calling auto-fill-function (see Section 33.14
[Auto Filling], page 846). Typically what auto-fill-function does is insert a new-
line; 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 does not run the hook post-self-insert-hook unless called interac-
tively or interactive is non-nil.
This command indents to the left margin if that is not zero. See Section 33.12
[Margins], page 844.
The value returned is nil.
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).
erase-buffer [Command]
This function deletes the entire text of the current buffer (not just the accessible por-
tion), leaving it empty. If the buffer is read-only, it signals a buffer-read-only error;
if some of the text in it is read-only, it signals a text-read-only error. Otherwise,
it deletes the text without asking for any confirmation. It returns nil.
Normally, deleting a large amount of text from a buffer inhibits further auto-saving
of that buffer because it has shrunk. However, erase-buffer does not do this, the
idea being that the future text is not really related to the former text, and its size
should not be compared with that of the former text.
delete-indentation joins this line to the following line instead. Otherwise, if beg
and end are non-nil, this function joins all lines in the region they define.
In an interactive call, join-following-p is the prefix argument, and beg and end are,
respectively, the start and end of the region if it is active, else nil. The function
returns nil.
If there is a fill prefix, and the second of the lines being joined starts with the pre-
fix, then delete-indentation deletes the fill prefix before joining the lines. See
Section 33.12 [Margins], page 844.
In the example below, point is located on the line starting ‘events’, and it makes no
difference if there are trailing spaces in the preceding line.
---------- Buffer: foo ----------
When in the course of human
? events, it becomes necessary
---------- Buffer: foo ----------
(delete-indentation)
⇒ nil
After the lines are joined, the function fixup-whitespace is responsible for deciding
whether to leave a space at the junction.
fixup-whitespace [Command]
This function replaces all the horizontal whitespace surrounding point with either one
space or no space, according to the context. It returns nil.
At the beginning or end of a line, the appropriate amount of space is none. Before
a character with close parenthesis syntax, or after a character with open parenthesis
or expression-prefix syntax, no space is also appropriate. Otherwise, one space is
appropriate. See Section 36.2.1 [Syntax Class Table], page 959.
In the example below, fixup-whitespace is called the first time with point before
the word ‘spaces’ in the first line. For the second invocation, point is directly after
the ‘(’.
---------- Buffer: foo ----------
This has too many ?spaces
This has too many spaces at the start of (? this list)
---------- Buffer: foo ----------
(fixup-whitespace)
⇒ nil
(fixup-whitespace)
⇒ nil
When the list reaches kill-ring-max entries in length, adding a new entry automatically
deletes the last entry.
When kill commands are interwoven with other commands, each kill command makes
a new entry in the kill ring. Multiple kill commands in succession build up a single kill
ring entry, which would be yanked as a unit; the second and subsequent consecutive kill
commands add text to the entry made by the first one.
For yanking, one entry in the kill ring is designated the front of the ring. Some yank
commands rotate the ring by designating a different element as the front. But this virtual
rotation doesn’t change the list itself—the most recent entry always comes first in the list.
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.
33.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.
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.
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.
The value should be an alist of elements (prop . fun). Each alist element is handled
in order. The inserted text is scanned for stretches of text having text properties eq
to prop; for each such stretch, fun is called with three arguments: the value of the
property, and the start and end positions of the text.
yank-excluded-properties [User Option]
The value of this variable is the list of properties to remove from inserted text. Its
default value contains properties that might lead to annoying results, such as causing
the text to respond to the mouse or specifying key bindings. It takes effect after
yank-handled-properties.
This command can also be invoked after a command that is not a yank command.
In that case, it prompts in the minibuffer for a kill-ring entry, with completion, and
uses the kill ring elements as the minibuffer history (see Section 21.4 [Minibuffer
History], page 371). This allows the user to interactively select one of the previous
kills recorded in the kill ring.
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.
of the entry, but if before-p is non-nil, it goes at the beginning. This function calls
kill-new as a subroutine, thus causing the values of interprogram-cut-function
and possibly interprogram-paste-function (see below) to be invoked by extension.
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 30.20
[Window System Selections], page 789. 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 30.20 [Window System Selections], page 789.
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.
33.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 28.3 [Buffer Names],
page 629.) All the primitives that modify the text in the buffer automatically add elements
to the front of the undo list, which is in the variable buffer-undo-list.
buffer-undo-list [Variable]
This buffer-local variable’s value is the undo list of the current buffer. A value of t
disables the recording of undo information.
(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 that is a non-integer Lisp timestamp 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 41.5 [Time of Day], page 1168. 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.
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.
Chapter 33: Text 839
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 33.5 [Commands
for Insertion], page 826), and delete-char, which deletes characters (see Section 33.6
[Deletion], page 827), 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.
This function can be called before an amalgamating command. It removes the previ-
ous undo-boundary if a series of such calls have been made.
The maximum number of changes that can be amalgamated is controlled by the
amalgamating-undo-limit variable. If this variable is 1, no changes are amalga-
mated.
A Lisp program can amalgamate a series of changes into a single change group by calling
undo-amalgamate-change-group (see Section 33.31 [Atomic Changes], page 896). Note
that amalgamating-undo-limit has no effect on the groups produced by that function.
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.
Some commands leave the region active after execution in such a way that it interferes
with selective undo of that command. To make undo ignore the active region when in-
voked immediately after such a command, set the property undo-inhibit-region of the
command’s function symbol to a non-nil value. See Section 9.4.2 [Standard Properties],
page 136.
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.
33.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 33.14 [Auto Filling], page 846) 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 33.12 [Margins], page 844). 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.
If nosqueeze is non-nil, that means to leave whitespace other than line breaks un-
touched. If to-eop is non-nil, that means to keep filling to the end of the paragraph—
or the next hard newline, if use-hard-newlines is enabled (see below).
The variable paragraph-separate controls how to distinguish paragraphs. See
Section 35.8 [Standard Regexps], page 957.
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.
Chapter 33: Text 844
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.
current-left-margin [Function]
This function returns the proper left margin value to use for filling the text around
point. The value is the sum of the left-margin property of the character at the start
of the current line (or zero if none), and the value of the variable left-margin.
current-fill-column [Function]
This function returns the proper fill column value to use for filling the text around
point. The value is the value of the fill-column variable, minus the value of the
right-margin property of the character after point.
Chapter 33: Text 845
line starting with this prefix wouldn’t look like the start of a paragraph. Should this
happen, the function signals the anomaly by returning nil instead.
In detail, fill-context-prefix does this:
1. It takes a candidate for the fill prefix from the first line—it tries first the
function in adaptive-fill-function (if any), then the regular expression
adaptive-fill-regexp (see below). The first non-nil result of these, or the
empty string if they’re both nil, becomes the first line’s candidate.
2. If the paragraph has as yet only one line, the function tests the validity of the
prefix candidate just found. The function then returns the candidate if it’s valid,
or a string of spaces otherwise. (see the description of adaptive-fill-first-
line-regexp below).
3. When the paragraph already has two lines, the function next looks for a prefix
candidate on the second line, in just the same way it did for the first line. If it
doesn’t find one, it returns nil.
4. The function now compares the two candidate prefixes heuristically: if the non-
whitespace characters in the line 2 candidate occur in the same order in the line
1 candidate, the function returns the line 2 candidate. Otherwise, it returns the
largest initial substring which is common to both candidates (which might be
the empty string).
used by Auto Fill mode. For a description of functions that you can call explicitly to fill
and justify existing text, see Section 33.11 [Filling], page 841.
Auto Fill mode also enables the functions that change the margins and justification style
to refill portions of the text. See Section 33.12 [Margins], page 844.
auto-fill-function [Variable]
The value of this buffer-local variable should be a function (of no arguments) to be
called after self-inserting a character from the table auto-fill-chars, see below. It
may be nil, in which case nothing special is done in that case.
The value of auto-fill-function is do-auto-fill when Auto Fill mode is enabled.
That is a function whose sole purpose is to implement the usual strategy for breaking
a line.
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.
The next four arguments to sort-subr are functions that are called to move point
across a sort record. They are called many times from within sort-subr.
1. nextrecfun is called with point at the end of a record. This function moves point
to the start of the next record. The first record is assumed to start at the position
of point when sort-subr is called. Therefore, you should usually move point to
the beginning of the buffer before calling sort-subr.
This function can indicate there are no more sort records by leaving point at the
end of the buffer.
2. endrecfun is called with point within a record. It moves point to the end of the
record.
3. startkeyfun is called to move point from the start of a record to the start of the
sort key. This argument is optional; if it is omitted, the whole record is the sort
key. If supplied, the function should either return a non-nil value to be used as
the sort key, or return nil to indicate that the sort key is in the buffer starting
at point. In the latter case, endkeyfun is called to find the end of the sort key.
4. endkeyfun is called to move point from the start of the sort key to the end of
the sort key. This argument is optional. If startkeyfun returns nil and this
argument is omitted (or nil), then the sort key extends to the end of the record.
There is no need for endkeyfun if startkeyfun returns a non-nil value.
The argument predicate is the function to use to compare keys. It is called with two
arguments, the keys to compare, and should return non-nil if the first key should
come before the second in the sorting order. What exactly are the key arguments
depends on what startkeyfun and endkeyfun return. If predicate is omitted or nil,
it defaults to < if the keys are numbers, to compare-buffer-substrings if the keys
are cons cells (whose car and cdr are start and end buffer positions of the key), and
to string< otherwise (with keys assumed to be strings).
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)))))
Chapter 33: Text 849
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
(lambda ()
(while (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1)))
'forward-paragraph)
Markers pointing into any sort records are left with no useful position after sort-subr
returns.
a regular expression
then sort-regexp-fields searches for a match for the regular expression
within the record. If such a match is found, it is the sort key. If there
is no match for key-regexp within a record then that record is ignored,
which means its position in the buffer is not changed. (The other records
may move around it.)
For example, if you plan to sort all the lines in the region by the first word on each line
starting with the letter ‘f’, you should set record-regexp to ‘^.*$’ and set key-regexp
to ‘\<f\w*\>’. The resulting expression looks like this:
(sort-regexp-fields nil "^.*$" "\\<f\\w*\\>"
(region-beginning)
(region-end))
If you call sort-regexp-fields interactively, it prompts for record-regexp and key-
regexp in the minibuffer.
sort-lines reverse start end [Command]
This command alphabetically sorts lines in the region between start and end. If
reverse is non-nil, the sort is in reverse order.
sort-paragraphs reverse start end [Command]
This command alphabetically sorts paragraphs in the region between start and end.
If reverse is non-nil, the sort is in reverse order.
sort-pages reverse start end [Command]
This command alphabetically sorts pages in the region between start and end. If
reverse is non-nil, the sort is in reverse order.
sort-fields field start end [Command]
This command sorts lines in the region between start and end, comparing them
alphabetically by the fieldth field of each line. Fields are separated by whitespace
and numbered starting from 1. If field is negative, sorting is by the −fieldth field
from the end of the line. This command is useful for sorting tables.
sort-numeric-fields field start end [Command]
This command sorts lines in the region between start and end, comparing them
numerically by the fieldth field of each line. Fields are separated by whitespace and
numbered starting from 1. The specified field must contain a number in each line of
the region. Numbers starting with 0 are treated as octal, and numbers starting with
‘0x’ are treated as hexadecimal.
If field is negative, sorting is by the −fieldth field from the end of the line. This
command is useful for sorting tables.
sort-numeric-base [User Option]
This variable specifies the default radix for sort-numeric-fields to parse numbers.
sort-columns reverse &optional beg end [Command]
This command sorts the lines in the region between beg and end, comparing them
alphabetically by a certain range of columns. The column positions of beg and end
bound the range of columns to sort on.
Chapter 33: Text 851
33.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.
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:
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.
If there is a fill prefix, indent-region indents each line by making it start with the
fill prefix.
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.
indent-rigidly start end count [Command]
This function indents all lines starting between start (inclusive) and end (exclusive)
sideways by count columns. This preserves the shape of the affected region, moving
it as a rigid unit.
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-code-rigidly start end columns &optional [Command]
nochange-regexp
This is like indent-rigidly, except that it doesn’t alter lines that start within strings
or comments.
In addition, it doesn’t alter a line if nochange-regexp matches at the beginning of the
line (if nochange-regexp is non-nil).
If the previous nonblank line has no next indent point (i.e., none at a great enough
column position), indent-relative either does nothing (if unindented-ok is non-nil)
or calls tab-to-tab-stop. Thus, if point is underneath and to the right of the last
column of a short line of text, this command ordinarily moves point to the next tab
stop by inserting whitespace.
If first-only is non-nil, only the first indent point is considered.
The return value of indent-relative is unpredictable.
In the following example, point is at the beginning of the second line:
This line is indented twelve spaces.
?The quick brown fox jumped.
Evaluation of the expression (indent-relative nil) produces the following:
This line is indented twelve spaces.
?The quick brown fox jumped.
In this next example, point is between the ‘m’ and ‘p’ of ‘jumped’:
This line is indented twelve spaces.
The quick brown fox jum?ped.
Evaluation of the expression (indent-relative nil) produces the following:
This line is indented twelve spaces.
The quick brown fox jum ?ped.
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.
back-to-indentation [Command]
This command moves point to the first non-whitespace character in the current line
(which is the line in which point is located). It returns nil.
(capitalize-region 1 37)
⇒ 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.
Chapter 33: Text 860
default-text-properties [Variable]
This variable holds a property list giving default values for text properties. Whenever
a character does not specify a value for a property, neither directly, through a category
symbol, or through char-property-alias-alist, the value stored in this list is used
instead. Here is an example:
(setq default-text-properties '(foo 69)
char-property-alias-alist nil)
;; Make sure character 1 has no properties of its own.
(set-text-properties 1 2 nil)
;; What we get, when we ask, is the default value.
(get-text-property 1 'foo)
⇒ 69
The return value is t if the function actually changed some property’s value; nil
otherwise (if props is nil or its values agree with those in the text).
For example, here is how to set the comment and face properties of a range of text:
(add-text-properties start end
'(comment t face highlight))
first element (by default) and the pre-existing faces as the remaining elements. If the
optional argument appendp is non-nil, face is appended to the end of the list instead.
Note that in a face list, the first occurring value for each attribute takes precedence.
For example, the following code would assign an italicized green face to the text
between start and end:
(add-face-text-property start end 'italic)
(add-face-text-property start end '(:foreground "red"))
(add-face-text-property start end '(:foreground "green"))
The optional argument object, if non-nil, specifies a buffer or string to act on, rather
than the current buffer. If object is a string, then start and end are zero-based indices
into the string.
The easiest way to make a string with text properties is with propertize:
See Section 33.2 [Buffer Contents], page 821, for the function buffer-substring-no-
properties, which copies text from the buffer but does not copy its properties.
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 28.5 [Buffer Modification], page 632.
For good performance, it’s very important to use the limit argument to these functions,
especially the ones that search for a single property—otherwise, they may spend a long time
scanning to the end of the buffer, if the property you are interested in does not change.
These functions do not move point; instead, they return a position (or nil). Remember
that a position is always between two characters; the position returned by these functions
is between two characters with different properties.
predicate can either be t (which is a synonym for equal), nil (which means “not
equal”), or a predicate that will be called with two parameters: The first is value,
and the second is the value of the text property we’re inspecting.
If not-current, if point is in a region where we have a match, then skip past that and
find the next instance instead.
The prop-match structure has the following accessors: prop-match-beginning (the
start of the match), prop-match-end (the end of the match), and prop-match-value
(the value of property at the start of the match).
In the examples below, imagine that you’re in a buffer that looks like this:
This is a bold and here's bolditalic and this is the end.
That is, the “bold” words are the bold face, and the “italic” word is in the italic
face.
With point at the start:
(while (setq match (text-property-search-forward 'face 'bold t))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
This will pick out all the words that use the bold face.
(while (setq match (text-property-search-forward 'face nil t))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
This will pick out all the bits that have no face properties, which will result in the
list ‘("This is a " "and here's " "and this is the end")’ (only reversed, since we
used push).
(while (setq match (text-property-search-forward 'face nil nil))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
This will pick out all the regions where face is set to something, but this is split up into
where the properties change, so the result here will be ‘("bold" "bold" "italic")’.
For a more realistic example where you might use this, consider that you have a buffer
where certain sections represent URLs, and these are tagged with shr-url.
(while (setq match (text-property-search-forward 'shr-url nil nil))
(push (prop-match-value match) urls))
This will give you a list of all those URLs.
mouse-face
This property is used instead of face when the mouse is on or near the character.
For this purpose, “near” means that all text between the character and where
the mouse is have the same mouse-face property value.
Emacs ignores all face attributes from the mouse-face property that alter the
text size (e.g., :height, :weight, and :slant). Those attributes are always
the same as for the unhighlighted text.
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 40.12.7 [Auto Faces], page 1082) 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 40.16 [Display Property],
page 1103.
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 40.25 [Tooltips], page 1147), after passing it through
substitute-command-keys.
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 872).
This feature is used in the mode line and for other active text.
help-echo-inhibit-substitution
If the first character of a help-echo string has a non-nil help-echo-inhibit-
substitution property, then it is displayed as-is by show-help-function,
without being passed through substitute-command-keys.
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
Chapter 33: Text 868
before the buffer’s local map. See Section 23.7 [Active Keymaps], page 458. If
the property value is a symbol, the symbol’s function definition is used as the
keymap.
The property’s value for the character before point applies if it is non-nil and
rear-sticky, and the property’s value for the character after point applies if it
is non-nil and front-sticky. (For mouse clicks, the position of the click is used
instead of the position of point.)
local-map
This property works like keymap except that it specifies a keymap to use instead
of the buffer’s local map. For most purposes (perhaps all purposes), it is better
to use the keymap property.
syntax-table
The syntax-table property overrides what the syntax table says about this
particular character. See Section 36.4 [Syntax Properties], page 965.
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 33.19.6 [Sticky Properties], page 873.
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 28.7 [Read Only Buffers], page 635.
inhibit-read-only
Characters that have the property inhibit-read-only can be edited even in
read-only buffers. See Section 28.7 [Read Only Buffers], page 635.
invisible
A non-nil invisible property can make a character invisible on the screen.
See Section 40.6 [Invisible Text], page 1049, 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
Chapter 33: Text 869
strings to cue the Emacs display about the places where to put the cursor while
traversing these strings. This directly communicates to the display engine where
the Lisp program wants to put the cursor, or where the user would expect the
cursor, when point is located on some buffer position that is “covered” by the
display or overlay string.
pointer This specifies a specific pointer shape when the mouse pointer is over this text
or image. See Section 30.19 [Pointer Shape], page 788, for possible pointer
shapes.
line-spacing
A newline can have a line-spacing text or overlay property that controls the
height of the display line ending with that newline. The property value overrides
the default frame line spacing and the buffer local line-spacing variable. See
Section 40.11 [Line Height], page 1067.
line-height
A newline can have a line-height text or overlay property that controls the
total height of the display line ending in that newline. See Section 40.11 [Line
Height], page 1067.
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 40.16.4 [Other Display Specs], page 1106), or a stretch of
whitespace such as specified by the :width or :align-to display properties
(see Section 40.16.2 [Specified Space], page 1104).
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 40.3 [Truncation],
page 1038.
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 40.16.4 [Other Display Specs], page 1106), or a stretch of
whitespace such as specified by the :width or :align-to display properties
(see Section 40.16.2 [Specified Space], page 1104).
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 40.3 [Truncation],
page 1038.
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
Chapter 33: Text 871
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.
Unlike with other similar hooks, when Emacs calls these functions,
inhibit-modification-hooks does not get bound to non-nil. If the
functions modify the buffer, you should consider binding this variable to
non-nil to prevent any buffer changes running the change hooks. Otherwise,
you must be prepared for recursive calls. See Section 33.32 [Change Hooks],
page 897.
Overlays also support the modification-hooks property, but the details are
somewhat different (see Section 40.9.2 [Overlay Properties], page 1059).
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.
When these functions are called, inhibit-modification-hooks is bound
to non-nil. If the functions modify the buffer, you might want to bind
inhibit-modification-hooks to nil, so as to cause the change hooks to run
for these modifications. However, doing this may call your own change hook
recursively, so be sure to prepare for that.
See also Section 33.32 [Change Hooks], page 897, for other hooks that are called
when you change text in a buffer.
point-entered
point-left
The special properties point-entered and point-left record hook functions
that report motion of point. Each time point moves, Emacs compares these
two property values:
• the point-left property of the character after the old location, and
• 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.
Chapter 33: Text 872
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:
See Section 33.4 [Insertion], page 824, for the ordinary insertion functions which do not
inherit.
buffer-access-fontify-functions [Variable]
This variable holds a list of functions for computing text properties. Before
buffer-substring copies the text and text properties for a portion of the buffer,
it calls all the functions in this list. Each of the functions receives two arguments
that specify the range of the buffer being accessed. (The buffer itself is always the
current buffer.)
buffer-access-fontified-property [Variable]
If this variable’s value is non-nil, it is a symbol which is used as a text property
name. A non-nil value for that text property means the other text properties for
this character have already been computed.
If all the characters in the range specified for buffer-substring have a non-nil value
for this property, buffer-substring does not call the buffer-access-fontify-
functions functions. It assumes these characters already have the right text proper-
ties, and just copies the properties they already have.
The normal way to use this feature is that the buffer-access-fontify-functions
functions add this property, as well as others, to the characters they operate on. That
way, they avoid being called over and over for the same text.
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]
Chapter 33: Text 877
(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 overlay property 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 40.19 [Buttons], page 1130. 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%]")
When the characters before and after pos are part of the same field, there is no doubt
which field contains pos: the one those characters both belong to. When pos is at a bound-
ary between fields, which field it belongs to depends on the stickiness of the field properties
of the two surrounding characters (see Section 33.19.6 [Sticky Properties], page 873). The
field whose property would be inherited by text inserted at pos is the field that contains
pos.
There is an anomalous case where newly inserted text at pos would not inherit the field
property from either side. This happens if the previous character’s field property is not
rear-sticky, and the following character’s field property is not front-sticky. In this case,
pos belongs to neither the preceding field nor the following field; the field functions treat it
as belonging to an empty field whose beginning and end are both at pos.
In all of these functions, if pos is omitted or nil, the value of point is used by default.
If narrowing is in effect, then pos should fall within the accessible portion. See Section 31.4
[Narrowing], page 808.
If old-pos is at the boundary of two fields, then the acceptable final positions depend
on the argument escape-from-edge. If escape-from-edge is nil, then new-pos must
be in the field whose field property equals what new characters inserted at old-
pos would inherit. (This depends on the stickiness of the field property for the
characters before and after old-pos.) If escape-from-edge is non-nil, new-pos can
be anywhere in the two adjacent fields. Additionally, if two fields are separated by
another field with the special value boundary, then any point within this special field
is also considered to be on the boundary.
Commands like C-a with no argument, that normally move backward to a specific
kind of location and stay there once there, probably should specify nil for escape-
from-edge. Other motion commands that check fields should probably pass t.
If the optional argument only-in-line is non-nil, and constraining new-pos in the
usual way would move it to a different line, new-pos is returned unconstrained. This
used in commands that move by line, such as next-line and beginning-of-line,
so that they respect field boundaries only in the case where they can still move to the
right line.
If the optional argument inhibit-capture-property is non-nil, and old-pos has a non-
nil property of that name, then any field boundaries are ignored.
You can cause constrain-to-field to ignore all field boundaries (and so never con-
strain anything) by binding the variable inhibit-field-text-motion to a non-nil
value.
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 33.19.3 [Property Search],
page 862.
Emacs also provides explicit intervals as a presentation feature; see Section 40.9 [Over-
lays], page 1056.
(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.
33.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 33: Text 882
of the current buffer will be equal to the text of the accessible portion of the source
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 external
code formatting programs: they typically write the reformatted text into a tempo-
rary buffer or file, and using delete-region and insert-buffer-substring would
destroy these properties. However, the latter combination is typically faster (See
Section 33.6 [Deletion], page 827, and Section 33.4 [Insertion], page 824).
For its working, replace-buffer-contents needs to compare the contents of the
original buffer with that of source which is a costly operation if the buffers are
huge and there is a high number of differences between them. In order to keep
replace-buffer-contents’s runtime in bounds, it has two optional arguments.
max-secs defines a hard boundary in terms of seconds. If given and exceeded, it will
fall back to delete-region and insert-buffer-substring.
max-costs defines the quality of the difference computation. If the actual costs exceed
this limit, heuristics are used to provide a faster but suboptimal solution. The default
value is 1000000.
replace-buffer-contents returns t if a non-destructive replacement could be per-
formed. Otherwise, i.e., if max-secs was exceeded, it returns nil.
replace-region-contents beg end replace-fn &optional max-secs [Function]
max-costs
This function replaces the region between beg and end using the given replace-fn.
The function replace-fn is run in the current buffer narrowed to the specified region
and it should return either a string or a buffer replacing the region.
The replacement is performed using replace-buffer-contents (see above) which
also describes the max-secs and max-costs arguments and the return value.
Note: If the replacement is a string, it will be placed in a temporary buffer so
that replace-buffer-contents can operate on it. Therefore, if you already have
the replacement in a buffer, it makes no sense to convert it to a string using
buffer-substring or similar.
On success, the function replaces the contents of the region with the decompressed
data. If allow-partial is nil or omitted, then on failure, the function leaves the region
unchanged and returns nil. Otherwise, it returns the number of bytes that were
not decompressed and replaces the region text by whatever data was successfully
decompressed. This function can be called only in unibyte buffers.
33.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 and SHA-1 are not collision resistant (i.e., it is possible to deliberately
design different pieces of data which have the same MD5 or SHA-1 hash), so you should
not use them for anything security-related. For security-related applications you should use
the other hash types, such as SHA-2 (e.g. sha256 or sha512).
secure-hash-algorithms [Function]
This function returns a list of symbols representing algorithms that secure-hash can
use.
(iv-auto length)
This generates a random IV (Initialization Vector) of the specified length and
passes it to the function. This ensures that the IV is unpredictable and unlikely
to be reused in the same session.
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.
libxml-available-p [Function]
This function returns non-nil if built-in libxml2 support is available in this Emacs
session.
Chapter 33: Text 889
When libxml2 support is available, the following functions can be used to parse HTML
or XML text into Lisp object trees.
(div nil
"Yes")))
dom-node tag &optional attributes &rest children [Function]
This function creates a DOM node of type tag. If given, attributes should be a
key/value pair list. If given, children should be DOM nodes.
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-remove-attribute node attribute
Remove attribute from node.
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 33: Text 891
• JSON has only one sequence type, the array. JSON arrays are represented using Lisp
vectors.
• JSON has only one map type, the object. JSON objects are represented using Lisp
hashtables, alists or plists. When an alist or plist contains several elements with the
same key, Emacs uses only the first element for serialization, in accordance with the
behavior of assq.
Note that nil, being both a valid alist and a valid plist, represents {}, the empty JSON
object; not null, false, or an empty array, all of which are different JSON values.
json-available-p [Function]
This predicate returns non-nil if Emacs has been built with JSON support, and the
library is available on the current system.
If some Lisp object can’t be represented in JSON, the serialization functions will signal
an error of type wrong-type-argument. The parsing functions can also signal the following
errors:
json-unavailable
Signaled when the parsing library isn’t available.
json-end-of-file
Signaled when encountering a premature end of the input text.
json-trailing-content
Signaled when encountering unexpected input after the first JSON object
parsed.
json-parse-error
Signaled when encountering invalid JSON syntax.
Top-level values and the subobjects within these top-level values can be serialized to
JSON. Likewise, the parsing functions will return any of the possible types described
above.
33.30.1 Overview
Quoting from the spec (https://www.jsonrpc.org/), JSONRPC "is transport agnostic in
that the concepts can be used within the same process, over sockets, over http, or in many
various message passing environments."
To model this agnosticism, the jsonrpc library uses objects of a jsonrpc-connection
class, which represent a connection to a remote JSON endpoint (for details on Emacs’s
object system, see EIEIO). In modern object-oriented parlance, this class is “abstract”, i.e.
the actual class of a useful connection object is always a subclass of jsonrpc-connection.
Nevertheless, we can define two distinct APIs around the jsonrpc-connection class:
1. A user interface for building JSONRPC applications
Chapter 33: Text 894
standard output); or TCP hosts (using sockets); or any other remote endpoint that Emacs’s
process object can represent (see Chapter 39 [Processes], page 987).
Using this transport, the JSONRPC messages are encoded on the wire as plain text and
prefaced by some basic HTTP-style enveloping headers, such as “Content-Length”.
For an example of an application using this transport scheme on top of JSONRPC, see the
Language Server Protocol (https://microsoft.github.io/language-server-protocol/
specification).
Along with the mandatory :request-dispatcher and :notification-dispatcher ini-
targs, users of the jsonrpc-process-connection class should pass the following initargs
as keyword-value pairs to make-instance:
:process Value must be a live process object or a function of no arguments producing
one such object. If passed a process object, the object is expected to contain a
pre-established connection; otherwise, the function is called immediately after
the object is made.
:on-shutdown
Value must be a function of a single argument, the jsonrpc-process-
connection object. The function is called after the underlying process object
has been deleted (either deliberately by jsonrpc-shutdown, or unexpectedly,
because of some external cause).
the remote endpoint. Furthermore, acting on these events may only sometimes demand
synchronization, depending on the event’s specific nature.
The :deferred keyword argument to jsonrpc-request and jsonrpc-async-request
is designed to let the caller indicate that the specific request needs synchronization and its
actual issuance may be delayed to the future, until some condition is satisfied. Specifying
:deferred for a request doesn’t mean it will be delayed, only that it can be. If the request
isn’t sent immediately, jsonrpc will make renewed efforts to send it at certain key times
during communication, such as when receiving or sending other messages to the endpoint.
Before any attempt to send the request, the application-specific conditions are checked.
Since the jsonrpc library can’t know what these conditions are, the program can use
the jsonrpc-connection-ready-p generic function (see Section 13.8 [Generic Functions],
page 234) to specify them. The default method for this function returns t, but you can add
overriding methods that return nil in some situations, based on the arguments passed to
it, which are the jsonrpc-connection object (see Section 33.30.1 [JSONRPC Overview],
page 893) and whichever value you passed as the :deferred keyword argument.
To use the change group, you must activate it. You must do this before making any
changes in the text of buffer.
After you activate the change group, any changes you make in that buffer become part
of it. Once you have made all the desired changes in the buffer, you must finish the change
group. There are two ways to do this: you can either accept (and finalize) all the changes,
or cancel them all.
accept-change-group handle [Function]
This function accepts all the changes in the change group specified by handle, making
them final.
cancel-change-group handle [Function]
This function cancels and undoes all the changes in the change group specified by
handle.
You can cause some or all of the changes in a change group to be considered as a single
unit for the purposes of the undo commands (see Section 33.9 [Undo], page 837) by using
undo-amalgamate-change-group.
undo-amalgamate-change-group [Function]
Amalgamate all the changes made in the change-group since the state identified by
handle. This function removes all undo boundaries between undo records of changes
since the state described by handle. Usually, handle is the handle returned by
prepare-change-group, in which case all the changes since the beginning of the
change-group are amalgamated into a single undo unit.
Your code should use unwind-protect to make sure the group is always finished. The call
to activate-change-group should be inside the unwind-protect, in case the user types C-
g just after it runs. (This is one reason why prepare-change-group and activate-change-
group are separate functions, because normally you would call prepare-change-group
before the start of that unwind-protect.) Once you finish the group, don’t use the handle
again—in particular, don’t try to finish the same group twice.
To make a multibuffer change group, call prepare-change-group once for each buffer
you want to cover, then use nconc to combine the returned values, like this:
(nconc (prepare-change-group buffer-1)
(prepare-change-group buffer-2))
You can then activate the multibuffer change group with a single call to
activate-change-group, and finish it with a single call to accept-change-group or
cancel-change-group.
Nested use of several change groups for the same buffer works as you would expect.
Non-nested use of change groups for the same buffer will get Emacs confused, so don’t let it
happen; the first change group you start for any given buffer should be the last one finished.
before-change-functions [Variable]
This variable holds a list of functions to call 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 using either the before- or the
after-change hook, 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.
combine-change-calls beg end body. . . [Macro]
This executes body normally, except any buffer changes it makes do not trigger the
calls to before-change-functions and after-change-functions. Instead there
Chapter 33: Text 899
is a single call of each of these hooks for the region enclosed by beg and end, the
parameters supplied to after-change-functions reflecting the changes made to the
size of the region by body.
The result of this macro is the result returned by body.
This macro is useful when a function makes a possibly large number of repetitive
changes to the buffer, and the change hooks would otherwise take a long time to run,
were they to be run for each individual buffer modification. Emacs itself uses this
macro, for example, in the commands comment-region and uncomment-region.
Warning: You must not alter the values of before-change-functions or
after-change-function within body.
Warning: You must not make any buffer changes outside of the region specified by
beg and end.
first-change-hook [Variable]
This variable is a normal hook that is run whenever a buffer is changed that was
previously in the unmodified state.
inhibit-modification-hooks [Variable]
If this variable is non-nil, all of the change hooks are disabled; none of them run.
This affects all the hook variables described above in this section, as well as the hooks
attached to certain special text properties (see Section 33.19.4 [Special Properties],
page 866) and overlay properties (see Section 40.9.2 [Overlay Properties], page 1059).
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. However, doing this may cause recursive calls
to the modification hooks, so be sure to prepare for that (for example, by binding
some variable which tells your hook to do nothing).
We recommend that you only bind this variable for modifications that do not result
in lasting changes to buffer text contents (for example face changes or temporary
modifications). If you need to delay change hooks during a series of changes (typically
for performance reasons), use combine-change-calls or combine-after-change-
calls instead.
900
34 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 34: Non-ASCII Characters 901
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 34: Non-ASCII Characters 902
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.
with Unicode; and values #x3FFF80 (4194176) through #x3FFFFF (4194303) represent
eight-bit raw bytes.
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
This section assumes you are already familiar with that chapter of the Unicode Standard,
and want to apply that knowledge to Emacs Lisp programs.
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 40.26 [Bidirectional
Display], page 1148). 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.
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 34: Non-ASCII Characters 907
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
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 40.26 [Bidirectional Display], page 1148). 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 40.26 [Bidirectional Display], page 1148).
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 34: Non-ASCII Characters 908
;; 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
unicode-category-table [Variable]
The value of this variable is a char-table (see Section 6.6 [Char-Tables], page 115) 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. Note
that Emacs’ classification of characters into scripts is not a 1-for-1 reflection of the
Unicode standard, e.g. there is no ‘symbol’ script in Unicode.
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.
Chapter 34: Non-ASCII Characters 910
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.
charset-list [Variable]
The value is a list of all defined character set names.
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 34.10.1 [Basic
Concepts of Coding Systems], page 914.) 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
Chapter 34: Non-ASCII Characters 913
standard-translation-table-for-decode [Variable]
This is the default translation table for decoding. If a coding system 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 system specifies its own
translation tables, the table that is the value of this variable, if non-nil, is applied
after them.
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 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 34.10.4 [User-Chosen Coding Systems], page 919). 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.
Chapter 34: Non-ASCII Characters 916
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 34.10.7
[Explicit Encoding], page 925) set it too.
Warning: Since receiving subprocess output sets this variable, it can change whenever
Emacs waits; therefore, you should copy the value shortly after the function call that
stores the value you are interested in.
The variable selection-coding-system specifies how to encode selections for the win-
dow system. See Section 30.20 [Window System Selections], page 789.
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.
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.
• If coding-system supports all the characters in the internal coding system used
by Emacs version 21 (prior to the implementation of internal Unicode support),
the value is emacs-mule.
See [Process Information], page 1003, 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.
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
of this variable, unless coding-system-for-write is bound to a non-nil value (see
Section 34.10.6 [Specifying Coding Systems], page 923).
Here are two functions you can use to let the user specify a coding system, with com-
pletion. See Section 21.6 [Completion], page 373.
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.
Chapter 34: Non-ASCII Characters 922
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.
The first element, decoding-system, is the coding system to use for decoding (in case
operation does decoding), and encoding-system is the coding system for encoding (in
case operation does encoding).
The argument operation is a symbol; it should be one of write-region,
start-process, call-process, call-process-region, insert-file-contents, or
open-network-stream. These are the names of the Emacs I/O primitives that can
do character code and eol conversion.
The remaining arguments should be the same arguments that might be given to the
corresponding I/O primitive. Depending on the primitive, one of those arguments is
selected as the target. For example, if operation does file I/O, whichever argument
specifies the file name is the target. For subprocess primitives, the process name is
the target. For open-network-stream, the target is the service name or port number.
Depending on operation, this function looks up the target in file-coding-system-
alist, process-coding-system-alist, or network-coding-system-alist. If the
target is found in the alist, find-operation-coding-system returns its association
in the alist; otherwise it returns nil.
If operation is insert-file-contents, the argument corresponding to the target may
be a cons cell of the form (filename . buffer). In that case, filename is a file name
to look up in file-coding-system-alist, and buffer is a buffer that contains the
file’s contents (not yet decoded). If file-coding-system-alist specifies a function
to call for this file, and that function needs to examine the file’s contents (as it usually
does), it should examine the contents of buffer instead of reading the file.
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.
Chapter 34: Non-ASCII Characters 924
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 34.10.4 [User-Chosen Coding Systems], page 919). This is because C-x
RET c (universal-coding-system-argument) works by binding coding-system-
for-write, and Emacs should obey user selection. If a Lisp program binds
coding-system-for-write to a value that might not be safe for encoding the text
to be written, it can also bind coding-system-require-warning to a non-nil value,
which will force the output primitives to check the encoding by calling the value of
select-safe-coding-system-function even though coding-system-for-write
is non-nil. Alternatively, call select-safe-coding-system explicitly before using
the specified encoding.
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 34.10.3 [Lisp and Coding Systems], page 916).
Each input method has a name, which is currently a string; in the future, symbols may
also be usable as input method names.
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.
default-input-method [User Option]
This variable holds the default input method for commands that choose an input
method. Unlike current-input-method, this variable is normally global.
set-input-method input-method [Command]
This command activates input method input-method for the current buffer. It also
sets default-input-method to input-method. If input-method is nil, this command
deactivates any input method for the current buffer.
read-input-method-name prompt &optional default inhibit-null [Function]
This function reads an input method name with the minibuffer, prompting with
prompt. If default is non-nil, that is returned by default, if the user enters empty
input. However, if inhibit-null is non-nil, empty input signals an error.
The returned value is a string.
input-method-alist [Variable]
This variable defines all the supported input methods. Each element defines one input
method, and should have the form:
(input-method language-env activate-func
title description args...)
Here input-method is the input method name, a string; language-env is another string,
the name of the language environment this input method is recommended for. (That
serves only for documentation purposes.)
activate-func is a function to call to activate this method. The args, if any, are
passed as arguments to activate-func. All told, the arguments to activate-func are
input-method and the args.
title is a string to display in the mode line while this method is active. description is
a string describing this method and what it is good for.
The fundamental interface to input methods is through the variable input-method-
function. See Section 22.8.2 [Reading One Event], page 434, and Section 22.8.4 [Invoking
the Input Method], page 438.
34.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
Chapter 34: Non-ASCII Characters 929
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.
(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.
‘^’ 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 35.3.1.2 [Char Classes], page 937.
‘^’ When matching a buffer, ‘^’ matches the empty string, but only at the beginning
of a line in the text being matched (or the beginning of the accessible portion
of the buffer). Otherwise it fails to match anything. Thus, ‘^foo’ matches a
‘foo’ that occurs at the beginning of a line.
When matching a string instead of a buffer, ‘^’ matches at the beginning of the
string or after a newline character.
For historical compatibility reasons, ‘^’ can be used only at the beginning of
the regular expression, or after ‘\(’, ‘\(?:’ or ‘\|’.
‘$’ is similar to ‘^’ but matches only at the end of a line (or the end of the accessible
portion of the buffer). Thus, ‘x+$’ matches a string of one ‘x’ or more at the
end of a line.
When matching a string instead of a buffer, ‘$’ matches at the end of the string
or before a newline character.
For historical compatibility reasons, ‘$’ can be used only at the end of the
regular expression, or before ‘\)’ or ‘\|’.
‘\’ has two functions: it quotes the special characters (including ‘\’), and it intro-
duces additional special constructs.
Because ‘\’ quotes special characters, ‘\$’ is a regular expression that matches
only ‘$’, and ‘\[’ is a regular expression that matches only ‘[’, and so on.
Note that ‘\’ also has special meaning in the read syntax of Lisp strings (see
Section 2.4.8 [String Type], page 19), and must be quoted with ‘\’. For exam-
ple, the regular expression that matches the ‘\’ character is ‘\\’. To write a
Lisp string that contains the characters ‘\\’, Lisp syntax requires you to quote
each ‘\’ with another ‘\’. Therefore, the read syntax for a regular expression
matching ‘\’ is "\\\\".
Please note: For historical compatibility, special characters are treated as ordinary ones
if they are in contexts where their special meanings make no sense. For example, ‘*foo’
treats ‘*’ as ordinary since there is no preceding expression on which the ‘*’ can act. It is
poor practice to depend on this behavior; quote the special character anyway, regardless of
where it appears.
As a ‘\’ is not special inside a character alternative, it can never remove the special
meaning of ‘-’ or ‘]’. So you should not quote these characters when they have no special
meaning either. This would not clarify anything, since backslashes can legitimately precede
these characters where they have special meaning, as in ‘[^\]’ ("[^\\]" for Lisp string
syntax), which matches any single character except a backslash.
Chapter 35: Searching and Matching 937
In practice, most ‘]’ that occur in regular expressions close a character alternative and
hence are special. However, occasionally a regular expression may try to match a complex
pattern of literal ‘[’ and ‘]’. In such situations, it sometimes may be necessary to carefully
parse the regexp from the start to determine which square brackets enclose a character al-
ternative. For example, ‘[^][]]’ consists of the complemented character alternative ‘[^][]’
(which matches any single character that is not a square bracket), followed by a literal ‘]’.
The exact rules are that at the beginning of a regexp, ‘[’ is special and ‘]’ not. This lasts
until the first unquoted ‘[’, after which we are in a character alternative; ‘[’ is no longer
special (except when it starts a character class) but ‘]’ is special, unless it immediately
follows the special ‘[’ or that ‘[’ followed by a ‘^’. This lasts until the next special ‘]’
that does not end a character class. This ends the character alternative and restores the
ordinary syntax of regular expressions; an unquoted ‘[’ is special again and a ‘]’ not.
on the numbering, e.g., you can have several groups with the same number in
which case the last one to match (i.e., the rightmost match) will win. Implicitly
numbered groups always get the smallest integer larger than the one of any
previous group.
‘\digit’ matches the same text that matched the digitth occurrence of a grouping (‘\(
... \)’) construct.
In other words, after the end of a group, the matcher remembers the beginning
and end of the text matched by that group. Later on in the regular expression
you can use ‘\’ followed by digit to match that same text, whatever it may have
been.
The strings matching the first nine grouping constructs appearing in the entire
regular expression passed to a search or matching function are assigned num-
bers 1 through 9 in the order that the open parentheses appear in the regular
expression. So you can use ‘\1’ through ‘\9’ to refer to the text matched by
the corresponding grouping constructs.
For example, ‘\(.*\)\1’ matches any newline-free string that is composed of
two identical halves. The ‘\(.*\)’ matches the first half, which may be any-
thing, but the ‘\1’ that follows must match the same exact text.
If a ‘\( ... \)’ construct matches more than once (which can happen, for
instance, if it is followed by ‘*’), only the last match is recorded.
If a particular grouping construct in the regular expression was never
matched—for instance, if it appears inside of an alternative that wasn’t used,
or inside of a repetition that repeated zero times—then the corresponding
‘\digit’ construct never matches anything. To use an artificial example,
‘\(foo\(b*\)\|lose\)\2’ cannot match ‘lose’: the second alternative inside
the larger group matches it, but then ‘\2’ is undefined and can’t match
anything. But it can match ‘foobb’, because the first alternative matches
‘foob’ and ‘\2’ matches ‘b’.
‘\w’ matches any word-constituent character. The editor syntax table determines
which characters these are. See Chapter 36 [Syntax Tables], page 958.
‘\W’ matches any character that is not a word constituent.
‘\scode’ matches any character whose syntax is code. Here code is a character that
represents a syntax code: thus, ‘w’ for word constituent, ‘-’ for whitespace, ‘(’
for open parenthesis, etc. To represent whitespace syntax, use either ‘-’ or a
space character. See Section 36.2.1 [Syntax Class Table], page 959, for a list of
syntax codes and the characters that stand for them.
‘\Scode’ matches any character whose syntax is not code.
‘\cc’ matches any character whose category is c. Here c is a character that repre-
sents a category: thus, ‘c’ for Chinese characters or ‘g’ for Greek characters in
the standard category table. You can see the list of all the currently defined
categories with M-x describe-categories RET. You can also define your own
categories in addition to the standard ones using the define-category function
(see Section 36.8 [Categories], page 972).
Chapter 35: Searching and Matching 941
Below, we show first the regexp as a string in Lisp syntax (to distinguish spaces from tab
characters), and then the result of evaluating it. The string constant begins and ends with
a double-quote. ‘\"’ stands for a double-quote as part of the string, ‘\\’ for a backslash as
part of the string, ‘\t’ for a tab and ‘\n’ for a newline.
"[.?!][]\"')}]*\\($\\| $\\|\t\\| \\)[ \t\n]*"
⇒ "[.?!][]\"')}]*\\($\\| $\\| \\| \\)[
]*"
In the output, tab and newline appear as themselves.
This regular expression contains four parts in succession and can be deciphered as follows:
[.?!] The first part of the pattern is a character alternative that matches any one
of three characters: period, question mark, and exclamation mark. The match
must begin with one of these three characters. (This is one point where the
new default regexp used by Emacs differs from the old. The new value also
allows some non-ASCII characters that end a sentence without any following
whitespace.)
[]\"')}]*
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.
(re-search-forward
(concat "\\s-" (regexp-quote string) "\\s-"))
The returned string may be string itself if it does not contain any special characters.
regexp-unmatchable [Variable]
This variable contains a regexp that is guaranteed not to match any string at all. It
is particularly useful as default value for variables that may be set to a pattern that
actually matches something.
If you run into regexp stack overflow despite following the above advice, don’t be afraid
of performing the matching in multiple function calls, each using a simpler regexp where
backtracking can more easily be contained.
Chapter 35: Searching and Matching 945
(match-end 0)
⇒ 32
This function does not move point, but it does update the match data. See
Section 35.6 [Match Data], page 948. 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 ----------
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
later use. Here is an example that shows the problem that arises if you fail to save the
match data:
(re-search-forward "The \\(cat \\)")
⇒ 48
(foo) ; foo does more searching.
(match-end 0)
⇒ 61 ; Unexpected result—not 48!
You can save and restore the match data with save-match-data:
save-match-data body. . . [Macro]
This macro executes body, saving and restoring the match data around it. The return
value is the value of the last form in body.
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
functions (see Section 39.9.2 [Filter Functions], page 1010) and process sentinels (see
Section 39.10 [Sentinels], page 1014).
If you want to write a command along the lines of query-replace, you can use
perform-replace to do the work.
query-replace-map [Variable]
This variable holds a special keymap that defines the valid user responses for
perform-replace and the commands that use it, as well as y-or-n-p and
map-y-or-n-p. This map is unusual in two ways:
• The key bindings are not commands, just symbols that are meaningful to the
functions that use this map.
• Prefix keys are not supported; each key binding must be for a single-event key
sequence. This is because the functions don’t use read-key-sequence to get the
input; instead, they read a single event and look it up “by hand”.
Here are the meaningful bindings for query-replace-map. Several of them are mean-
ingful only for query-replace and friends.
act Do take the action being considered—in other words, “yes”.
skip Do not take action for this question—in other words, “no”.
exit Answer this question “no”, and give up on the entire series of questions, assum-
ing that the answers will be “no”.
exit-prefix
Like exit, but add the key that was pressed to unread-command-events (see
Section 22.8.6 [Event Input Misc], page 440).
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.
Chapter 35: Searching and Matching 956
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.
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 35.1
[String Search], page 930).
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 35.4 [Regexp Search], page 945).
Chapter 35: Searching and Matching 957
The following two regular expressions should not assume the match always starts at the
beginning of a line; they should not use ‘^’ to anchor the match. Most often, the paragraph
commands do check for a match only at the beginning of a line, which means that ‘^’ would
be superfluous. When there is a nonzero left margin, they accept matches that start after
the left margin. In that case, a ‘^’ would be incorrect. However, a ‘^’ is harmless in modes
where a left margin is never used.
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 843), sentence-end-without-period, and sentence-end-without-space.
958
36 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 24.6
[Font Lock Mode], page 527) and the various complex movement commands (see Section 31.2
[Motion], page 798).
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 24.2.9 [Example
Major Modes], page 508, 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 36.2.1 [Syntax Class Table], page 959). 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 36: Syntax Tables 959
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 36.5 [Motion
and Syntax], page 966.
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.
parse-sexp-lookup-properties [Variable]
If this is non-nil, the syntax scanning functions, like forward-sexp, pay attention
to syntax-table text properties. Otherwise they use only the current syntax table.
syntax-propertize-function [Variable]
This variable, if non-nil, should store a function for applying syntax-table proper-
ties to a specified stretch of text. It is intended to be used by major modes to install
a function which applies syntax-table properties in some mode-appropriate way.
The function is called by syntax-ppss (see Section 36.6.2 [Position Parse], page 968),
and by Font Lock mode during syntactic fontification (see Section 24.6.8 [Syntactic
Font Lock], page 537). It is called with two arguments, start and end, which are
the starting and ending positions of the text on which it should act. It is allowed
to arbitrarily move point within the region delimited by start and end; such motions
don’t need to use save-excursion (see Section 31.3 [Excursions], page 807). It is also
allowed to call syntax-ppss on any position before end, but if a Lisp program calls
syntax-ppss on some position and later modifies the buffer at some earlier position,
then it is that program’s responsibility to call syntax-ppss-flush-cache to flush
the now obsolete info from the cache.
Caution: When this variable is non-nil, Emacs removes syntax-table text proper-
ties arbitrarily and relies on syntax-propertize-function to reapply them. Thus if
this facility is used at all, the function must apply all syntax-table text properties
used by the major mode. In particular, Modes derived from a CC Mode mode must
not use this variable, since CC Mode uses other means to apply and remove these
text properties.
Chapter 36: Syntax Tables 966
syntax-propertize-extend-region-functions [Variable]
This abnormal hook is run by the syntax parsing code prior to calling
syntax-propertize-function. Its role is to help locate safe starting and ending
buffer positions for passing to syntax-propertize-function. For example, a major
mode can add a function to this hook to identify multi-line syntactic constructs, and
ensure that the boundaries do not fall in the middle of one.
Each function in this hook should accept two arguments, start and end. It should
return either a cons cell of two adjusted buffer positions, (new-start . new-end), or
nil if no adjustment is necessary. The hook functions are run in turn, repeatedly,
until they all return nil.
Section 31.2.6 [List Motion], page 805, for convenient higher-level functions for moving over
balanced expressions.
A character’s syntax controls how it changes the state of the parser, rather than de-
scribing the state itself. For example, a string delimiter character toggles the parser state
between in-string and in-code, but the syntax of characters does not directly say whether
they are inside a string. For example (note that 15 is the syntax code for generic string
delimiters),
(put-text-property 1 9 'syntax-table '(15 . nil))
does not tell Emacs that the first eight chars of the current buffer are a string, but rather
that they are all string delimiters. As a result, Emacs treats them as four consecutive empty
string constants.
are found as expected, with nothing except whitespace between them, it returns t;
otherwise it returns nil.
This function cannot tell whether the comments it traverses are embedded within a
string. If they look like comments, it treats them as comments.
To move forward over all comments and whitespace following point, use
(forward-comment (buffer-size)). (buffer-size) is a good argument to use,
because the number of comments in the buffer cannot exceed that many.
1. The character position of the start of the innermost parenthetical grouping containing
the stopping point; nil if none.
2. The character position of the start of the last complete subexpression terminated; nil
if none.
3. Non-nil if inside a string. More precisely, this is the character that will terminate the
string, or t if a generic string delimiter character should terminate it.
4. t if inside a non-nestable comment (of any comment style; see Section 36.2.2 [Syntax
Flags], page 962); or the comment nesting level if inside a comment that can be nested.
5. t if the end point is just after a quote character.
6. The minimum parenthesis depth encountered during this scan.
7. What kind of comment is active: nil if not in a comment or in a comment of style
‘a’; 1 for a comment of style ‘b’; 2 for a comment of style ‘c’; and syntax-table for a
comment that should be ended by a generic comment delimiter character.
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 36.7 [Syntax Table Internals], page 970) of that position.
Otherwise nil.
Elements 1, 2, and 6 are ignored in a state which you pass as an argument to
parse-partial-sexp to continue parsing. Elements 9 and 10 are mainly used internally
by the parser code.
Some additional useful information is available from a parser state using these functions:
sets point to the location where parsing stops. It returns a parser state describing
the status of the parse at the point where it stops.
If the third argument target-depth is non-nil, parsing stops if the depth in parentheses
becomes equal to target-depth. The depth starts at 0, or at whatever is given in state.
If the fourth argument stop-before is non-nil, parsing stops when it comes to any
character that starts a sexp. If stop-comment is non-nil, parsing stops after the start
of an unnested comment. If stop-comment is the symbol syntax-table, parsing stops
after the start of an unnested comment or a string, or after the end of an unnested
comment or a string, whichever comes first.
If state is nil, start is assumed to be at the top level of parenthesis structure, such
as the beginning of a function definition. Alternatively, you might wish to resume
parsing in the middle of the structure. To do this, you must provide a state argument
that describes the initial status of parsing. The value returned by a previous call to
parse-partial-sexp will do nicely.
comment-end-can-be-escaped [Variable]
If this buffer local variable is non-nil, a single character which usually terminates a
comment doesn’t do so when that character is escaped. This is used in C and C++
Modes, where line comments starting with ‘//’ can be continued onto the next line
by escaping the newline with ‘\’.
You can use forward-comment to move forward or backward over one comment or several
comments.
syntax flags, according to the table below. matching-char, if non-nil, specifies a matching
character (similar to the second character in a syntax descriptor).
Use aref (see Section 6.3 [Array Functions], page 112) to get the raw syntax descriptor
of a character, e.g. (aref (syntax-table) ch).
Here are the syntax codes corresponding to the various syntax classes:
Code Class Code Class
0 whitespace 8 paired delimiter
1 punctuation 9 escape
2 word 10 character quote
3 symbol 11 comment-start
4 open parenthesis 12 comment-end
5 close parenthesis 13 inherit
6 expression prefix 14 generic comment
7 string quote 15 generic string
For example, in the standard syntax table, the entry for ‘(’ is (4 . 41). 41 is the character
code for ‘)’.
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’ (ash 1 16) ‘p’ (ash 1 20)
‘2’ (ash 1 17) ‘b’ (ash 1 21)
‘3’ (ash 1 18) ‘n’ (ash 1 22)
‘4’ (ash 1 19) ‘c’ (ash 1 23)
36.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 115). 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.
category-table [Function]
This function returns the current buffer’s category table.
standard-category-table [Function]
This function returns the standard category table.
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 37: Abbrevs and Abbrev Expansion 978
expand-abbrev [Command]
This command expands the abbrev before point, if any. If point does not follow an
abbrev, this command does nothing. To do the expansion, it calls the function that is
the value of the abbrev-expand-function variable, with no arguments, and returns
whatever that function does.
The default expansion function returns the abbrev symbol if it did expansion, and
nil otherwise. If the abbrev symbol has a hook function that is a symbol whose
no-self-insert property is non-nil, and if the hook function returns nil as its
value, then the default expansion function returns nil, even though expansion did
occur.
indicate the start of the next abbrev to be expanded. The actual expansion removes
the hyphen.
abbrev-start-location [Variable]
The value of this variable is a buffer position (an integer or a marker) for
expand-abbrev to use as the start of the next abbrev to be expanded. The
value can also be nil, which means to use the word before point instead.
abbrev-start-location is set to nil each time expand-abbrev is called. This
variable is also set by abbrev-prefix-mark.
abbrev-start-location-buffer [Variable]
The value of this variable is the buffer for which abbrev-start-location has been
set. Trying to expand an abbrev in any other buffer clears abbrev-start-location.
This variable is set by abbrev-prefix-mark.
last-abbrev [Variable]
This is the abbrev-symbol of the most recent abbrev expanded. This information is
left by expand-abbrev for the sake of the unexpand-abbrev command (see Section
“Expanding Abbrevs” in The GNU Emacs Manual).
last-abbrev-location [Variable]
This is the location of the most recent abbrev expanded. This contains information
left by expand-abbrev for the sake of the unexpand-abbrev command.
last-abbrev-text [Variable]
This is the exact expansion text of the most recent abbrev expanded, after case
conversion (if any). Its value is nil if the abbrev has already been unexpanded. This
contains information left by expand-abbrev for the sake of the unexpand-abbrev
command.
abbrev-expand-function [Variable]
The value of this variable is a function that expand-abbrev will call with no argu-
ments to do the expansion. The function can do anything it wants before and after
performing the expansion. It should return the abbrev symbol if expansion took place.
(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 37.7 [Abbrev Table Properties], page 981.
38 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 28.2 [Current Buffer], page 626) and its own match data (see Section 35.6 [Match
Data], page 948).
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 195), a closure
is an object like any other in Emacs Lisp, and bindings in a closure are shared by any
threads invoking the closure.
thread-yield [Function]
Yield execution to the next runnable thread.
current-thread [Function]
Return the current thread.
all-threads [Function]
Return a list of all the live thread objects. A new list is returned by each invocation.
main-thread [Variable]
This variable keeps the main thread Emacs is running, or nil if Emacs is compiled
without thread support.
When code run by a thread signals an error that is unhandled, the thread exits. Other
threads can access the error form which caused the thread to exit using the following
function.
38.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.
mutexp object [Function]
This function returns t if object represents an Emacs mutex, nil otherwise.
make-mutex &optional name [Function]
Create a new mutex and return it. If name is specified, it is a name given to the
mutex. It must be a string. The name is for debugging purposes only; it has no
meaning to Emacs.
mutex-name mutex [Function]
Return the name of mutex, as specified to make-mutex.
mutex-lock mutex [Function]
This will block until this thread acquires mutex, or until this thread is signaled using
thread-signal. If mutex is already owned by this thread, this simply returns.
mutex-unlock mutex [Function]
Release mutex. If mutex is not owned by this thread, this will signal an error.
with-mutex mutex body. . . [Macro]
This macro is the simplest and safest way to evaluate forms while holding a mutex.
It acquires mutex, invokes body, and then releases mutex. It returns the result of
body.
that the backtrace is a snapshot; the thread could have meanwhile resumed
execution, and be in a different state, or could have exited.
You may use g in the thread’s backtrace buffer to get an updated backtrace, as
backtrace buffers do not automatically update. See Section 19.1.7 [Backtraces],
page 320, for a description of backtraces and the other commands which work
on them.
s Signal the thread at point. After s, type q to send a quit signal or e to send
an error signal. Threads may implement handling of signals, but the default
behavior is to exit on any signal. Therefore you should only use this command
if you understand how to restart the target thread, because your Emacs session
may behave incorrectly if necessary threads are killed.
g Update the list of threads and their statuses.
987
39 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 39.12 [System Processes], page 1016.
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 39.9.2
[Filter Functions], page 1010, and Chapter 20 [Read and Print], page 352.) 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 41.3 [System Environment], page 1163. 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.
exec-path [Function]
This function is an extension of the variable exec-path. If default-directory indi-
cates a remote directory, this function returns a list of directories used for searching
programs on the respective remote host. In case of a local default-directory, the
function returns just the value of the variable exec-path.
1
On other systems, Emacs uses a Lisp emulation of ls; see Section 26.10 [Contents of Directories],
page 601.
Chapter 39: Processes 991
Otherwise the function call-process does no redisplay, and the results become vis-
ible on the screen only when Emacs redisplays that buffer in the normal course of
events.
The remaining arguments, args, are strings that specify command line arguments for
the program. Each string is passed to program as a separate argument.
The value returned by call-process (unless you told it not to wait) indicates the
reason for process termination. A number gives the exit status of the subprocess; 0
means success, and any other value means failure. If the process terminated with a
signal, call-process returns a string describing the signal. If you told call-process
not to wait, it returns nil.
In the examples below, the buffer ‘foo’ is current.
(call-process "pwd" nil t)
⇒ 0
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 name 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.
In the following example, we use call-process-region to run the cat utility, with
standard input being the first five characters in buffer ‘foo’ (the word ‘input’). cat
copies its standard input into its standard output. Since the argument destination is
t, this output is inserted in the current buffer.
---------- Buffer: foo ----------
input?
---------- Buffer: foo ----------
end-of-line characters are stripped from each line. The arguments beyond program,
args, are strings that specify command-line arguments with which to run the program.
If program exits with a non-zero exit status, this function signals an error.
This function works by calling call-process, so program output is decoded in the
same way as for call-process.
process-lines-ignore-status program &rest args [Function]
This function is just like process-lines, but does not signal an error if program
exits with a non-zero exit status.
to give to the program as its arguments. If the first element of the list
is nil, Emacs opens a new pseudoterminal (pty) and associates its input
and output with buffer, without actually running any program; the rest
of the list elements are ignored in that case.
:coding coding
If coding is a symbol, it specifies the coding system to be used for both
reading and writing of data from and to the connection. If coding is a
cons cell (decoding . encoding), then decoding will be used for read-
ing and encoding for writing. The coding system used for encoding the
data written to the program is also used for encoding the command-line
arguments (but not the program itself, whose file name is encoded as any
other file name; see Section 34.10.2 [Encoding and I/O], page 915).
If coding is nil, the default rules for finding the coding system will apply.
See Section 34.10.5 [Default Coding Systems], page 920.
:connection-type type
Initialize the type of device used to communicate with the subprocess.
Possible values are pty to use a pty, pipe to use a pipe, or nil to use the
default derived from the value of the process-connection-type variable.
This parameter and the value of process-connection-type are ignored
if a non-nil value is specified for the :stderr parameter; in that case,
the type will always be pipe. On systems where ptys are not available
(MS-Windows), this parameter is likewise ignored, and pipes are used
unconditionally.
:noquery query-flag
Initialize the process query flag to query-flag. See Section 39.11 [Query
Before Exit], page 1016.
:stop stopped
If provided, stopped must be nil; it is an error to use any non-nil value.
The :stop key is ignored otherwise and is retained for compatibility with
other process types such as pipe processes. Asynchronous subprocesses
never start in the stopped state.
:filter filter
Initialize the process filter to filter. If not specified, a default filter will
be provided, which can be overridden later. See Section 39.9.2 [Filter
Functions], page 1010.
:sentinel sentinel
Initialize the process sentinel to sentinel. If not specified, a default sen-
tinel will be used, which can be overridden later. See Section 39.10 [Sen-
tinels], page 1014.
:stderr stderr
Associate stderr with the standard error of the process. A non-nil value
should be either a buffer or a pipe process created with make-pipe-
process, described below. If stderr is nil, standard error is mixed with
standard output, and both are sent to buffer or filter.
Chapter 39: Processes 997
If stderr is a buffer, Emacs will create a pipe process, the standard er-
ror process. This process will have the default filter (see Section 39.9.2
[Filter Functions], page 1010), sentinel (see Section 39.10 [Sentinels],
page 1014), and coding systems (see Section 34.10.5 [Default Coding
Systems], page 920). On the other hand, it will use query-flag as its
query-on-exit flag (see Section 39.11 [Query Before Exit], page 1016).
It will be associated with the stderr buffer (see Section 39.9.1 [Process
Buffers], page 1008) and send its output (which is the standard error of
the main process) there. To get the process object for the standard error
process, pass the stderr buffer to get-buffer-process.
If stderr is a pipe process, Emacs will use it as standard error process for
the new process.
:file-handler file-handler
If file-handler is non-nil, then look for a file name handler for the current
buffer’s default-directory, and invoke that file name handler to make
the process. If there is no such handler, proceed as if file-handler were
nil.
The original argument list, modified with the actual connection information, is avail-
able via the process-contact function.
The current working directory of the subprocess is set to the current buffer’s value
of default-directory if that is local (as determined by unhandled-file-name-
directory), or ~ otherwise. If you want to run a process in a remote directory, pass
:file-handler t to make-process. In that case, the current working directory is the
local name component of default-directory (as determined by file-local-name).
Depending on the implementation of the file name handler, it might not be possible
to apply filter or sentinel to the resulting process object. The :stderr argument
cannot be a pipe process, file name handlers do not support pipe processes for this. A
buffer as :stderr argument is accepted, its contents is shown without the use of pipe
processes. See Section 39.9.2 [Filter Functions], page 1010, Section 39.10 [Sentinels],
page 1014, and Section 39.9.4 [Accepting Output], page 1012.
Some file name handlers may not support make-process. In such cases, this function
does nothing and returns nil.
make-pipe-process &rest args [Function]
This function creates a bidirectional pipe which can be attached to a child process.
This is useful with the :stderr keyword of make-process. The function returns a
process object.
The arguments args are a list of keyword/argument pairs. Omitting a keyword is
always equivalent to specifying it with value nil.
Here are the meaningful keywords:
:name name
Use the string name as the process name. As with make-process, it is
modified if necessary to make it unique.
:buffer buffer
Use buffer as the process buffer.
Chapter 39: Processes 998
:coding coding
If coding is a symbol, it specifies the coding system to be used for both
reading and writing of data from and to the connection. If coding is a
cons cell (decoding . encoding), then decoding will be used for reading
and encoding for writing.
If coding is nil, the default rules for finding the coding system will apply.
See Section 34.10.5 [Default Coding Systems], page 920.
:noquery query-flag
Initialize the process query flag to query-flag. See Section 39.11 [Query
Before Exit], page 1016.
: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 39.8 [Signals to Processes],
page 1005).
:filter filter
Initialize the process filter to filter. If not specified, a default filter will
be provided, which can be changed later. See Section 39.9.2 [Filter Func-
tions], page 1010.
: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 39.10 [Sen-
tinels], page 1014.
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 39.6 [Process Information], page 1001.
(delete-process "*shell*")
⇒ nil
nection, (port speed) for a serial connection, and t for a pipe connection. For an
ordinary child process, this function always returns t when called with a nil key.
If key is t, the value is the complete status information for the connection, server,
serial port, or pipe; that is, the list of keywords and values specified in make-network-
process, make-serial-process, or make-pipe-process, except that some of the
values represent the current status instead of what you specified.
For a network process, the values include (see make-network-process for a complete
list):
:buffer The associated value is the process buffer.
:filter The associated value is the process filter function. See Section 39.9.2
[Filter Functions], page 1010.
:sentinel
The associated value is the process sentinel function. See Section 39.10
[Sentinels], page 1014.
: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.
If process is a non-blocking network stream that hasn’t been fully set up yet, then this
function will block until that has happened. If given the optional no-block parameter,
this function will return nil instead of blocking.
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.
Chapter 39: Processes 1003
signal is sent to the process-group that owns the terminal, but only if it is not the shell
itself.
The flag current-group has no effect when a pipe is used to communicate with the
subprocess, because the operating system does not support the distinction in the case
of pipes. For the same reason, job-control shells won’t work when a pipe is used. See
process-connection-type in Section 39.4 [Asynchronous Processes], page 995.
It is usually a bad idea to have more than one process associated with the same buffer.
(get-buffer-process "*shell*")
⇒ #<process shell>
Killing the process’s buffer deletes the process, which kills the subprocess with a
SIGHUP signal (see Section 39.8 [Signals to Processes], page 1005).
If the process’s buffer is displayed in a window, your Lisp program may wish to tell
the process the dimensions of that window, so that the process could adapt its output to
those dimensions, much as it adapts to the screen dimensions. The following functions allow
communicating this kind of information to processes; however, not all systems support the
underlying functionality, so it is best to provide fallbacks, e.g., via command-line arguments
or environment variables.
When windows that display buffers associated with process change their dimensions,
the affected processes should be told about these changes. By default, when the window
configuration changes, Emacs will automatically call set-process-window-size on behalf
of every process whose buffer is displayed in a window, passing it the smallest dimensions
of all the windows displaying the process’s buffer. This works via window-configuration-
change-hook (see Section 29.28 [Window Hooks], page 731), which is told to invoke the
function that is the value of the variable window-adjust-process-window-size-function
for each process whose buffer is displayed in at least one window. You can customize this
behavior by setting the value of that variable.
If the process has the adjust-window-size-function property (see Section 39.6 [Pro-
cess Information], page 1001), its value overrides the global and buffer-local values of
window-adjust-process-window-size-function.
Chapter 39: Processes 1010
Note that Emacs automatically saves and restores the match data while executing filter
functions. See Section 35.6 [Match Data], page 948.
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.
set-process-filter process filter [Function]
This function gives process the filter function filter. If filter is nil, it gives the process
the default filter, which inserts the process output into the process buffer. If filter is
t, Emacs stops accepting output from the process, unless it’s a network server process
that listens for incoming connections.
process-filter process [Function]
This function returns the filter function of process.
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 240.
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
")
null bytes, Emacs by default uses no-conversion for it; see Section 34.10.3 [Lisp and Coding
Systems], page 916, for how to control this behavior.
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 has to process asynchronous subprocess output in batches, as it arrives. Emacs
must try to detect the proper coding system from one batch at a time, and this does not
always work. Therefore, if at all possible, specify a coding system that 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.
When Emacs calls a process filter function, it provides the process output as a multi-
byte string or as a unibyte string according to the process’s filter coding system. Emacs
decodes the output according to the process output coding system, which usually produces
a multibyte string, except for coding systems such as binary and raw-text.
(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))
If you have passed a non-nil stderr to make-process, it will have a standard error
process. See Section 39.4 [Asynchronous Processes], page 995. In that case, waiting for
process output from the main process doesn’t wait for output from the standard error
process. To make sure you have received both all of standard output and all of standard
error from a process, use the following code:
(while (accept-process-output process))
(while (accept-process-output stderr-process))
If you passed a buffer to the stderr argument of make-process, you still have to wait
for the standard error process, like so:
(let* ((stdout (generate-new-buffer "stdout"))
(stderr (generate-new-buffer "stderr"))
(process (make-process :name "test"
:command '("my-program")
:buffer stdout
:stderr stderr))
(stderr-process (get-buffer-process stderr)))
(unless (and process stderr-process)
(error "Process unexpectedly nil"))
(while (accept-process-output process))
(while (accept-process-output stderr-process)))
Only when both accept-process-output forms return nil, you can be sure that the
process has exited and Emacs has read all its output.
Reading pending standard error from a process running on a remote host is not possible
this way.
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 22.11 [Quitting], page 443.
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 19.1 [Debugger], page 316.
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 35.6 [Match Data], page 948.
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 240.
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 39: Processes 1016
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 applica-
tion’s code. The corresponding value is a Lisp timestamp (see Section 41.5
[Time of Day], page 1168).
Chapter 39: Processes 1018
stime Time spent by the process in the system (kernel) context, for processing
system calls. The corresponding value is a Lisp timestamp.
time The sum of utime and stime. The corresponding value is a Lisp time-
stamp.
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, as a Lisp timestamp.
etime The time elapsed since the process started, as a Lisp timestamp.
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 39.6 [Process Information],
page 1001.
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 39.17.1 [Network Processes], page 1023.) 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 the built-in support for 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 func-
tion gnutls-available-p is defined and returns non-nil. For more details, see Section
“Overview” in The Emacs-GnuTLS manual. The open-network-stream function can
transparently handle the details of creating encrypted connections for you, using whatever
support is available.
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
an encrypted connection via STARTTLS. If that fails, retain
the unencrypted connection.
starttls As for nil, but if STARTTLS fails drop the connection.
shell A shell connection.
:always-query-capabilities boolean
If non-nil, always ask for the server’s capabilities, even when doing a
‘plain’ connection.
:capability-command capability-command
Command to query the host capabilities. This can either be a string
(which will then be sent verbatim to the server), or a function (called with
a single parameter; the "greeting" from the server when connecting), and
should return a string.
:end-of-command regexp
:end-of-capability regexp
Regular expression matching the end of a command, or the end of the
command capability-command. The latter defaults to the former.
:starttls-function function
Function of one argument (the response to capability-command), which
returns either nil, or the command to activate STARTTLS if supported.
:success regexp
Regular expression matching a successful STARTTLS negotiation.
:use-starttls-if-possible boolean
If non-nil, do opportunistic STARTTLS upgrades even if Emacs doesn’t
have built-in TLS support.
:warn-unless-encrypted boolean
If non-nil, and :return-value is also non-nil, Emacs will warn if the
connection isn’t encrypted. This is useful for protocols like IMAP and the
like, where most users would expect the network traffic to be encrypted.
:client-certificate list-or-t
Either a list of the form (key-file cert-file), naming the certificate
key file and certificate file itself, or t, meaning to query auth-source
for this information (see Section “auth-source” in Emacs auth-source Li-
brary). Only used for TLS or STARTTLS. To enable automatic queries
of auth-source when :client-certificate is not specified customize
network-stream-use-client-certificates to t.
Chapter 39: Processes 1022
:return-list cons-or-nil
The return value of this function. If omitted or nil, return a process
object. Otherwise, a cons of the form (process-object . plist), where
plist has keywords:
:greeting string-or-nil
If non-nil, the greeting string returned by the host.
:capabilities string-or-nil
If non-nil, the host’s capability string.
:type symbol
The connection type: ‘plain’ or ‘tls’.
: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’.
39.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 39.7 [Input to Processes],
page 1004), and each datagram received results in one call to the filter function.
The datagram connection doesn’t have to talk with the same remote peer all the time.
It has a remote peer address which specifies where to send datagrams to. Each time an
incoming datagram is passed to the filter function, the peer address is set to the address that
datagram came from; that way, if the filter function sends a datagram, it will go back to that
place. You can specify the remote peer address when you create the datagram connection
using the :remote keyword. You can change it later on by calling set-process-datagram-
address.
process-datagram-address process [Function]
If process is a datagram connection or server, this function returns its remote peer
address.
set-process-datagram-address process address [Function]
If process is a datagram connection or server, this function sets its remote peer address
to address.
39.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.
make-network-process &rest args [Function]
This function creates a network connection or server and returns the process object
that represents it. The arguments args are a list of keyword/argument pairs. Omitting
a keyword is always equivalent to specifying it with value nil, except for :coding,
:filter-multibyte, and :reuseaddr. Here are the meaningful keywords (those
corresponding to network options are listed in the following section):
:name name
Use the string name as the process name. It is modified if necessary to
make it unique.
:type type Specify the communication type. A value of nil specifies a stream connec-
tion (the default); datagram specifies a datagram connection; seqpacket
specifies a sequenced packet stream connection. Both connections and
servers can be of these types.
:server server-flag
If server-flag is non-nil, create a server. Otherwise, create a connection.
For a stream type server, server-flag may be an integer, which then spec-
ifies the length of the queue of pending connections to the server. The
default queue length is 5.
Chapter 39: Processes 1024
:host host Specify the host to connect to. host should be a host name or Internet
address, as a string, or the symbol local to specify the local host. If you
specify host for a server, it must specify a valid address for the local host,
and only clients connecting to that address will be accepted. When using
local, by default IPv4 will be used, specify a family of ipv6 to override
this. To listen on all interfaces, specify an address of ‘"0.0.0.0"’ for
IPv4 or ‘"::"’ for IPv6. Note that on some operating systems, listening
on ‘"::"’ will also listen on IPv4, so attempting to then listen separately
on IPv4 will result in EADDRINUSE errors (‘"Address already in use"’).
:service service
service specifies a port number to connect to; or, for a server, the port
number to listen on. It should be a service name like ‘"https"’ that
translates to a port number, or an integer like ‘443’ or an integer string
like ‘"443"’ 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.
Chapter 39: Processes 1025
:noquery query-flag
Initialize the process query flag to query-flag. See Section 39.11 [Query
Before Exit], page 1016.
:filter filter
Initialize the process filter to filter.
:filter-multibyte multibyte
If multibyte is non-nil, strings given to the process filter are multibyte,
otherwise they are unibyte. The default is t.
:sentinel sentinel
Initialize the process sentinel to sentinel.
:log log Initialize the log function of a server process to log. The log function is
called each time the server accepts a network connection from a client.
The arguments passed to the log function are server, connection, and
message; where server is the server process, connection is the new process
for the connection, and message is a string describing what has happened.
:plist plist Initialize the process plist to plist.
The original argument list, modified with the actual connection information, is avail-
able via the process-contact function.
:linger linger-arg
If linger-arg is non-nil, wait for successful transmission of all queued packets
on the connection before it is deleted (see delete-process). If linger-arg is an
integer, it specifies the maximum time in seconds to wait for queued packets
to be sent before closing the connection. The default is nil, which means to
discard unsent queued packets when the process is deleted.
:oobinline oobinline-flag
If oobinline-flag is non-nil for a stream connection, receive out-of-band data
in the normal data stream. Otherwise, ignore out-of-band data.
:priority priority
Set the priority for packets sent on this connection to the integer priority. The
interpretation of this number is protocol specific; such as setting the TOS (type
of service) field on IP packets sent on this connection. It may also have system
dependent effects, such as selecting a specific output queue on the network
interface.
:reuseaddr reuseaddr-flag
If reuseaddr-flag is non-nil (the default) for a stream server process, allow this
server to reuse a specific port number (see :service), unless another process
on this host is already listening on that port. If reuseaddr-flag is nil, there
may be a period of time after the last use of that port (by any process on the
host) where it is not possible to make a new server on that port.
(: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 39.17.2 [Network Options], page 1026. This form returns non-nil
if that particular network option is supported by make-network-process (or
set-network-process-option).
("vmnet1"
[172 16 206 1 0]
[172 16 206 255 0]
[255 255 255 0 0])
("lo0"
[65152 0 0 0 0 0 0 1 0]
[65152 0 0 0 65535 65535 65535 65535 0]
[65535 65535 65535 65535 0 0 0 0 0])
("lo0"
[0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1 0]
[65535 65535 65535 65535 65535 65535 65535 65535 0])
("lo0"
[127 0 0 1 0]
[127 255 255 255 0]
[255 0 0 0 0]))
By default both IPv4 and IPv6 lookups are attempted. The optional argument family
controls this behavior, specifying the symbol ipv4 or ipv6 restricts lookups to IPv4
and IPv6 respectively.
:name name
The name of the process. If name is not given, port will serve as the
process name as well.
:buffer buffer
The buffer to associate with the process. The value can be either a buffer
or a string that names a buffer. Process output goes at the end of that
buffer, unless you specify an output stream or filter function to handle
the output. If buffer is not given, the process buffer’s name is taken from
the value of the :name keyword.
:coding coding
If coding is a symbol, it specifies the coding system used for both reading
and writing for this process. If coding is a cons (decoding . encoding),
decoding is used for reading, and encoding is used for writing. If not
specified, the default is to determine the coding systems from the data
itself.
:noquery query-flag
Initialize the process query flag to query-flag. See Section 39.11 [Query
Before Exit], page 1016. The flags defaults to nil if unspecified.
:stop bool
Start process in the stopped state if bool is non-nil. In the stopped
state, a serial process does not accept incoming data, but you can send
outgoing data. The stopped state is cleared by continue-process and
set by stop-process.
: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)
serial-process-configure &rest args [Function]
This function configures a serial port connection. Arguments are specified as key-
word/argument pairs. Attributes that are not given are re-initialized from the pro-
Chapter 39: Processes 1032
Conversion from byte arrays to nested alists is also known as deserializing or unpacking,
while going in the opposite direction is also known as serializing or packing.
A field’s type describes the size (in bytes) of the object that the field represents and, in
the case of multibyte fields, how the bytes are ordered within the field. The two possible
orderings are big endian (also known as “network byte ordering”) and little endian. For
instance, the number #x23cd (decimal 9165) in big endian would be the two bytes #x23
#xcd; and in little endian, #xcd #x23. Here are the possible type values:
u8
byte Unsigned byte, with length 1.
uint bitlen
Unsigned integer in network byte order, with bitlen bits. bitlen has to be a
multiple of 8.
uintr bitlen
Unsigned integer in little endian order, with bitlen bits. bitlen has to be a
multiple of 8.
str len String of bytes of length len.
strz &optional len
Zero-terminated string of bytes, can be of arbitrary length or in a fixed-size
field with length len.
vec len [type]
Vector of len elements. The type of the elements is given by type, defaulting to
bytes. The type can be any Bindat type expression.
repeat len [type]
Like vec, but it unpacks to and packs from lists, whereas vec unpacks to vectors.
bits len List of bits that are set to 1 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).
fill len len bytes used as a mere filler. In packing, these bytes are are left unchanged,
which normally means they remain zero. When unpacking, this just returns
nil.
Chapter 39: Processes 1034
align len Same as fill except the number of bytes is that needed to skip to the next
multiple of len bytes.
type exp This lets you refer to a type indirectly: exp is a Lisp expression which should
return a Bindat type value.
unit exp This is a trivial type which uses up 0 bits of space. exp describes the value
returned when we try to “unpack” such a field.
struct fields...
Composite type made of several fields. Every field is of the form (name type)
where type can be any Bindat type expression. name can be _ when the field’s
value does not deserve to be named, as is often the case for align and fill
fields. When the context makes it clear that this is a Bindat type expression,
the symbol struct can be omitted.
In the types above, len and bitlen are given as an integer specifying the number of bytes
(or bits) in the field. When the length of a field is not fixed, it typically depends on the
value of preceding fields. For this reason, the length len does not have to be a constant but
can be any Lisp expression and it can refer to the value of previous fields via their name.
For example, the specification of a data layout where a leading byte gives the size of a
subsequent vector of 16 bit integers could be:
(bindat-type
(len u8)
(payload vec (1+ len) uint 16))
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,
Chapter 39: Processes 1035
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"
40 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 40: Emacs Display 1038
pre-redisplay-function [Variable]
A function run just before redisplay. It is called with one argument, the set of windows
to be redisplayed. The set can be nil, meaning only the selected window, or t,
meaning all the windows.
pre-redisplay-functions [Variable]
This hook is run just before redisplay. It is called once in each window that is about
to be redisplayed, with current-buffer set to the buffer displayed in that window.
40.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 33.11 [Filling], page 841.
On a graphical display, tiny arrow images in the window fringes indicate truncated
and continued lines (see Section 40.13 [Fringes], page 1093). 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 40.22.2 [Display Tables], page 1141).
Since wrapping and truncation of text contradict each other, Emacs turns off line trun-
cation when wrapping is requested, and vice versa.
When horizontal scrolling (see Section 29.23 [Horizontal Scrolling], page 719) is in use
in a window, that forces truncation.
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 40.16.4 [Other Display
Specs], page 1106), or a stretch of whitespace such as specified by the :width or
:align-to display properties (see Section 40.16.2 [Specified Space], page 1104). The
value is interpreted in the same way as a display text property. See Section 40.16
[Display Property], page 1103.
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 33.19.4 [Special Properties], page 866.
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 40.16.4 [Other Display Specs], page 1106), or a stretch of whitespace
such as specified by the :width or :align-to display properties (see Section 40.16.2
[Specified Space], page 1104). The value is interpreted in the same way as a display
text property. See Section 40.16 [Display Property], page 1103.
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 33.19.4 [Special Properties], page 866.
Typically grave accent and apostrophe in the format translate to matching curved
quotes, e.g., "Missing ‘%s’" might result in "Missing ‘foo’". See Section 25.4
[Text Quoting Style], page 556, for how to influence or inhibit this translation.
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’..."
set-message-function [Variable]
If this variable is non-nil, it should be a function of one argument, the text of a
message to display in the echo area. This function will be called by message and
related functions. If the function returns nil, the message is displayed in the echo
area as usual. If this function returns a string, that string is displayed in the echo
area instead of the original one. If this function returns other non-nil values, that
means the message was already handled, so message will not display anything in the
echo area. See also clear-message-function that can be used to clear the message
displayed by this function.
The default value is the function that displays the message at the end of the minibuffer
when the minibuffer is active. However, if the text shown in the active minibuffer
has the minibuffer-message text property (see Section 33.19.4 [Special Properties],
page 866) on some character, the message will be displayed before the first character
having that property.
clear-message-function [Variable]
If this variable is non-nil, message and related functions call it with no arguments
when their argument message is nil or the empty string.
Usually this function is called when the next input event arrives after displaying an
echo-area message. The function is expected to clear the message displayed by its
counterpart function specified by set-message-function.
Chapter 40: Emacs Display 1041
The default value is the function that clears the message displayed in an active mini-
buffer.
inhibit-message [Variable]
When this variable is non-nil, message and related functions will not use the Echo
Area to display messages.
current-message [Function]
This function returns the message currently being displayed in the echo area, or nil
if there is none.
Chapter 40: Emacs Display 1042
messages-buffer [Function]
This function returns the *Messages* buffer. If it does not exist, it creates it, and
switches it to messages-buffer-mode.
To make *Messages* more convenient for the user, the logging facility combines suc-
cessive identical messages. It also combines successive related messages for the sake of two
cases: question followed by answer, and a series of progress messages.
A question followed by an answer has two messages like the ones produced by y-or-n-p:
the first is ‘question’, and the second is ‘question...answer’. The first message conveys
no additional information beyond what’s in the second, so logging the second message
discards the first from the log.
A series of progress messages has successive messages like those produced by
make-progress-reporter. They have the form ‘base...how-far’, where base is the same
each time, while how-far varies. Logging each message in the series discards the previous
one, provided they are consecutive.
The functions make-progress-reporter and y-or-n-p don’t have to do anything spe-
cial to activate the message log combination feature. It operates whenever two consecutive
messages are logged that share a common prefix ending in ‘...’.
Chapter 40: Emacs Display 1045
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.
Chapter 40: Emacs Display 1047
warning-prefix-function [Variable]
If non-nil, the value is a function to generate prefix text for warnings. Programs can
bind the variable to a suitable function. display-warning calls this function with
the warnings buffer current, and the function can insert text in it. That text becomes
the beginning of the warning message.
The function is called with two arguments, the severity level and its entry in
warning-levels. It should return a list to use as the entry (this value need not be
an actual member of warning-levels). By constructing this value, the function can
change the severity of the warning, or specify different handling for a given severity
level.
If the variable’s value is nil then there is no function to call.
warning-series [Variable]
Programs can bind this variable to t to say that the next warning should begin a
series. When several warnings form a series, that means to leave point on the first
warning of the series, rather than keep moving it for each warning so that it appears on
the last one. The series ends when the local binding is unbound and warning-series
becomes nil again.
The value can also be a symbol with a function definition. That is equivalent to t,
except that the next warning will also call the function with no arguments with the
warnings buffer current. The function can insert text which will serve as a header for
the series of warnings.
Once a series has begun, the value is a marker which points to the buffer position in
the warnings buffer of the start of the series.
The variable’s normal value is nil, which means to handle each warning separately.
warning-fill-prefix [Variable]
When this variable is non-nil, it specifies a fill prefix to use for filling each warning’s
text.
warning-fill-column [Variable]
The column at which to fill warnings.
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. Immediately after running post-command-hook (see Section 22.1
[Command Overview], page 401), 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.
Chapter 40: Emacs Display 1049
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.
Ordinarily, functions that operate on text or move point do not care whether the text
is invisible, they process invisible characters and visible characters alike. The user-level
line motion commands, such as next-line, previous-line, ignore invisible newlines if
line-move-ignore-invisible is non-nil (the default), i.e., behave like these invisible
newlines didn’t exist in the buffer, but only because they are explicitly programmed to do
so.
If a command ends with point inside or at the boundary of invisible text, the main
editing loop relocates point to one of the two ends of the invisible text. Emacs chooses
the direction of relocation so that it is the same as the overall movement direction of the
command; if in doubt, it prefers a position where an inserted char would not inherit the
invisible property. Additionally, if the text is not replaced by an ellipsis and the command
only moved within the invisible text, then point is moved one extra character so as to try
and reflect the command’s movement by a visible movement of the cursor.
Thus, if the command moved point back to an invisible range (with the usual stickiness),
Emacs moves point back to the beginning of that range. If the command moved point
Chapter 40: Emacs Display 1051
forward into an invisible range, Emacs moves point forward to the first visible character
that follows the invisible text and then forward one more character.
These adjustments of point that ended up in the middle of invisible text can be disabled
by setting disable-point-adjustment to a non-nil value. See Section 22.6 [Adjusting
Point], page 415.
Incremental search can make invisible overlays visible temporarily and/or permanently
when a match includes invisible text. To enable this, the overlay should have a non-nil
isearch-open-invisible property. The property value should be a function to be called
with the overlay as an argument. This function should make the overlay visible permanently;
it is used when the match overlaps the overlay on exit from the search.
During the search, such overlays are made temporarily visible by temporarily modifying
their invisible and intangible properties. If you want this to be done differently for a certain
overlay, give it an isearch-open-invisible-temporary property which is a function. The
function is called with two arguments: the first is the overlay, and the second is nil to make
the overlay visible, or t to make it invisible again.
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.
Chapter 40: Emacs Display 1052
• 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.
(setq selective-display nil)
⇒ nil
(setq selective-display 2)
⇒ 2
(with-output-to-temp-buffer "foo"
(print 20)
(print standard-output))
⇒ #<buffer foo>
20
#<buffer foo>
temp-buffer-setup-hook [Variable]
This normal hook is run by with-output-to-temp-buffer before evaluating body.
When the hook runs, the temporary buffer is current. This hook is normally set up
with a function to put the buffer in Help mode.
temp-buffer-show-hook [Variable]
This normal hook is run by with-output-to-temp-buffer after displaying the tem-
porary buffer. When the hook runs, the temporary buffer is current, and the window
it was displayed in is selected.
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 29.5 [Resizing Windows],
page 657) for resizing. You can specify a different function by customizing the options
temp-buffer-max-height and temp-buffer-max-width below.
temp-buffer-max-height [User Option]
This option specifies the maximum height (in lines) of a window displaying a tempo-
rary buffer when temp-buffer-resize-mode is enabled. It can also be a function to
be called to choose the height for such a buffer. It gets one argument, the buffer, and
should return a positive integer. At the time the function is called, the window to be
resized is selected.
temp-buffer-max-width [User Option]
This option specifies the maximum width of a window (in columns) displaying a tem-
porary buffer when temp-buffer-resize-mode is enabled. It can also be a function
to be called to choose the width for such a buffer. It gets one argument, the buffer,
and should return a positive integer. At the time the function is called, the window
to be resized is selected.
The following function uses the current buffer for temporary display:
momentary-string-display string position &optional char message [Function]
This function momentarily displays string in the current buffer at position. It has no
effect on the undo list or on the buffer’s modification status.
The momentary display remains until the next input event. If the next input event
is char, momentary-string-display ignores it and returns. Otherwise, that event
remains buffered for subsequent use as input. Thus, typing char will simply remove
the string from the display, while typing (say) C-f will remove the string from the
display and later (presumably) move point forward. The argument char is a space by
default.
The return value of momentary-string-display is not meaningful.
If the string string does not contain control characters, you can do the same job in
a more general way by creating (and then subsequently deleting) an overlay with a
before-string property. See Section 40.9.2 [Overlay Properties], page 1059.
If message is non-nil, it is displayed in the echo area while string is displayed in the
buffer. If it is nil, a default message says to type char to continue.
In this example, point is initially located at the beginning of the second line:
---------- Buffer: foo ----------
This is the contents of foo.
?Second line.
---------- Buffer: foo ----------
Chapter 40: Emacs Display 1056
(momentary-string-display
"**** Important Message! ****"
(point) ?\r
"Type RET when done reading")
⇒ t
40.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 33.19 [Text Properties], page 858). 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.
deleted by giving it the ‘evaporate’ property (see Section 40.9.2 [Overlay Properties],
page 1059).
The arguments front-advance and rear-advance specify the marker insertion type for
the start of the overlay and for the end of the overlay, respectively. See Section 32.5
[Marker Insertion Types], page 814. If they are both nil, the default, then the overlay
extends to include any text inserted at the beginning, but not text inserted at the end.
If front-advance is non-nil, text inserted at the beginning of the overlay is excluded
from the overlay. If rear-advance is non-nil, text inserted at the end of the overlay
is included in the overlay.
⇒ 1
(overlay-end foo)
⇒ 20
(overlay-buffer foo)
⇒ #<buffer display.texi>
;; Moving and deleting the overlay does not change its properties.
(overlay-get foo 'happy)
⇒ t
Emacs stores the overlays of each buffer in two lists, divided around an arbitrary center
position. One list extends backwards through the buffer from that center position, and the
other extends forwards from that center position. The center position can be anywhere in
the buffer.
A loop that scans the buffer forwards, creating overlays, can run faster if you do
(overlay-recenter (point-max)) first.
See also the function get-char-property which checks both overlay properties and text
properties for a given character. See Section 33.19.1 [Examining Properties], page 859.
Many overlay properties have special meanings; here is a table of them:
priority This property’s value determines the priority of the overlay. If you want to
specify a priority value, use either nil (or zero), or a positive integer. Any
other value has undefined behavior.
The priority matters when two or more overlays cover the same character and
both specify the same property; the one whose priority value is larger overrides
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 40.9.3 [Finding Overlays],
page 1063.
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 40.12 [Faces],
page 1069). 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.
Chapter 40: Emacs Display 1061
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
or narrower, or replaced with an image. See Section 40.16 [Display Property],
page 1103.
help-echo
If an overlay has a help-echo property, then when you move the mouse onto
the text in the overlay, Emacs displays a help string in the echo area, or in the
tooltip window. For details see [Text help-echo], page 867.
field Consecutive characters with the same field property constitute a field. Some
motion functions including forward-word and beginning-of-line stop mov-
ing at a field boundary. See Section 33.19.9 [Fields], page 877.
modification-hooks
This property’s value is a list of functions to be called if any character within
the overlay is changed or if text is inserted strictly within the overlay.
The hook functions are called both before and after each change. If the functions
save the information they receive, and compare notes between calls, they can
determine exactly what change has been made in the buffer text.
When called before a change, each function receives four arguments: the overlay,
nil, and the beginning and end of the text range to be modified.
When called after a change, each function receives five arguments: the overlay,
t, the beginning and end of the text range just modified, and the length of
the pre-change text replaced by that range. (For an insertion, the pre-change
length is zero; for a deletion, that length is the number of characters deleted,
and the post-change beginning and end are equal.)
When these functions are called, inhibit-modification-hooks is bound
to non-nil. If the functions modify the buffer, you might want to bind
inhibit-modification-hooks to nil, so as to cause the change hooks to run
for these modifications. However, doing this may call your own change hook
recursively, so be sure to prepare for that. See Section 33.32 [Change Hooks],
page 897.
Text properties also support the modification-hooks property, but the details
are somewhat different (see Section 33.19.4 [Special Properties], page 866).
insert-in-front-hooks
This property’s value is a list of functions to be called before and after inserting
text right at the beginning of the overlay. The calling conventions are the same
as for the modification-hooks functions.
Chapter 40: Emacs Display 1062
insert-behind-hooks
This property’s value is a list of functions to be called before and after inserting
text right at the end of the overlay. The calling conventions are the same as for
the modification-hooks functions.
invisible
The invisible property can make the text in the overlay invisible, which
means that it does not appear on the screen. See Section 40.6 [Invisible Text],
page 1049, for details.
intangible
The intangible property on an overlay works just like the intangible text
property. It is obsolete. See Section 33.19.4 [Special Properties], page 866, for
details.
isearch-open-invisible
This property tells incremental search how to make an invisible overlay visible,
permanently, if the final match overlaps it. See Section 40.6 [Invisible Text],
page 1049.
isearch-open-invisible-temporary
This property tells incremental search how to make an invisible overlay visible,
temporarily, during the search. See Section 40.6 [Invisible Text], page 1049.
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 40.3 [Truncation], page 1038.
wrap-prefix
This property specifies a display spec to prepend to each continuation line at
display-time. See Section 40.3 [Truncation], page 1038.
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 40.9.1 [Managing Overlays], page 1056) 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 takes precedence over most other keymaps (see Section 23.7 [Active
Keymaps], page 458), and it is used when point is within the overlay, where the
Chapter 40: Emacs Display 1063
front- and rear-advance properties define whether the boundaries are considered
as being within or not.
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 33.19.4 [Special Properties], page 866.
searches forward from position pos for the next position where the value of a given property
prop, as obtained from either overlays or text properties, changes.
(defun next-single-char-property-change (position prop)
(save-excursion
(goto-char position)
(let ((propval (get-char-property (point) prop)))
(while (and (not (eobp))
(eq (get-char-property (point) prop) propval))
(goto-char (min (next-overlay-change (point))
(next-single-property-change (point) prop)))))
(point)))
many times as needed to reach width. It is also prepended at the beginning of the
result if a multi-column character in string extends across the column start-column.
If ellipsis is non-nil, it should be a string which will replace the end of string when it
is truncated. In this case, more characters will be removed from string to free enough
space for ellipsis to fit within width columns. However, if the display width of string
is less than the display width of ellipsis, ellipsis will not be appended to the result. If
ellipsis is non-nil and not a string, it stands for the value returned by the function
truncate-string-ellipsis, described below.
The optional argument ellipsis-text-property, if non-nil, means hide the excess
parts of string with a display text property (see Section 40.16 [Display Property],
page 1103) showing the ellipsis, instead of actually truncating the string.
(truncate-string-to-width "\tab\t" 12 4)
⇒ "ab"
(truncate-string-to-width "\tab\t" 12 4 ?\s)
⇒ " ab "
This function uses string-width and char-width to find the suitable truncation
point when string is too wide, so it suffers from the same basic issues as string-width
does. In particular, when character composition happens within string, the display
width of a string could be smaller than the sum of widths of the constituent characters,
and this function might return inaccurate results.
truncate-string-ellipsis [Function]
This function returns the string to be used as an ellipses in truncate-string-to-
width and other similar contexts. The value is that of the variable truncate-string-
ellipsis, if it’s non-nil, the string with the single character U+2026 HORIZON-
TAL ELLIPSIS if that character can be displayed on the selected frame, and the
string ‘...’ otherwise.
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 29.5 [Resizing Windows], page 657) to make a window exactly as large as the text
it contains.
The optional argument x-limit, if non-nil, specifies the maximum X coordinate be-
yond which text should be ignored; it is therefore also the largest value of pixel-width
that the function can return. If x-limit nil or omitted, it means to use the pixel-width
of window’s body (see Section 29.4 [Window Sizes], page 652); this default means that
text of truncated lines wider than the window will be ignored. This default 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; in particular, if
truncated lines are expected and their text needs to be accounted for, x-limit should
be set to a large value. 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 Y coordinate be-
yond which text is to be ignored; it is therefore also the maximum pixel-height that
the function can return. If y-limit is nil or omitted, it means to considers all the lines
of text till the buffer position specified by to. 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-lines nil or omitted means to not include the height
of the mode-, tab- or header-line of window in the return value. If it is either the
symbol mode-line, tab-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 all of these lines, 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 40.22.4 [Glyphs], page 1143) 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 40: Emacs Display 1067
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 40.11 [Line Height],
page 1067).
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 29.3
[Selecting Windows], page 650) 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 30.3.2 [Frame Font], page 747.)
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. The property value can be one of several forms:
t If the property value is t, the newline character has no effect on the dis-
played 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.
(height total)
If the property value is a list of the form shown, 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 30.4.3.4 [Layout Parameters], page 760). 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.
Chapter 40: Emacs Display 1069
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
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.
40.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 33.19.4 [Special Properties], page 866.
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 40.12.2 [Defining Faces], page 1073). Emacs comes with several standard named
faces (see Section 40.12.8 [Basic Faces], page 1083).
Some parts of Emacs require named faces (e.g., the functions documented in
Section 40.12.3 [Attribute Functions], page 1076). Unless otherwise stated, we will use the
term face to refer only to named faces.
1
For backward compatibility, you can also use a string to specify a face name; that is equivalent to a Lisp
symbol with the same name.
Chapter 40: Emacs Display 1070
Some of these attributes are meaningful only on certain kinds of displays. If your display
cannot handle a certain attribute, the attribute is ignored.
: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 40.12.4 [Displaying Faces], page 1079).
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.
:weight Font weight—one of the symbols (from densest to faintest) ultra-bold,
extra-bold, bold, semi-bold, normal, semi-light, light, extra-light, or
ultra-light. On text terminals which support variable-brightness text, any
weight greater than normal is displayed as extra bright, and any weight less
than normal is displayed as half-bright.
:slant Font slant—one of the symbols italic, oblique, normal, reverse-italic,
or reverse-oblique. On text terminals that support variable-brightness text,
slanted text is displayed as half-bright.
:foreground
Foreground color, a string. The value can be a system-defined color name, or
a hexadecimal color specification. See Section 30.22 [Color Names], page 790.
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 30.22 [Color Names], page 790.
Chapter 40: Emacs Display 1071
: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 (vwidth . hwidth) :color color :style style)
This way you can explicitly specify all aspects of the box. The
values vwidth and hwidth specifies respectively the width of the
vertical and horizontal lines to draw; they default to (1 . 1). A
negative horizontal or vertical width −n means to draw a line of
width n that occupies the space of the underlying text, thus avoid-
ing any increase in the character height or width. For simplification
the width could be specified with only a single number n instead of
a list, such case is equivalent to ((abs n) . n).
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, flat-button or omitted,
a plain 2D box is used.
The value color specifies the color to draw with. The default is the
background color of the face for 3D boxes and flat-button, and
the foreground color of the face for other boxes.
Chapter 40: Emacs Display 1072
:inverse-video
Whether or not characters should be displayed in inverse video. The value
should be t (yes) or nil (no).
:stipple The background stipple, a bitmap.
The value can be a string; that should be the name of a file containing external-
format X bitmap data. The file is found in the directories listed in the variable
x-bitmap-file-path.
Alternatively, the value can specify the bitmap directly, with a list of the form
(width height data). Here, width and height specify the size in pixels, and
data is a string containing the raw bits of the bitmap, row by row. Each row
occupies (width+7)/8 consecutive bytes in the string (which should be a unibyte
string for best results). This means that each row always occupies at least one
whole byte.
If the value is nil, that means use no stipple pattern.
Normally you do not need to set the stipple attribute, because it is used auto-
matically to handle certain shades of gray.
:font The font used to display the face. Its value should be a font object or a fontset. If
it is a font object, it specifies the font to be used by the face for displaying ASCII
characters. See Section 40.12.12 [Low-Level Font], page 1088, for information
about font objects, font specs, and font entities. See Section 40.12.11 [Fontsets],
page 1086, for information about fontsets.
When specifying this attribute using set-face-attribute or set-face-font
(see Section 40.12.3 [Attribute Functions], page 1076), you may also supply a
font spec, a font entity, or a string. Emacs converts such values to an appro-
priate font object, and stores that font object as the actual attribute value.
If you specify a string, the contents of the string should be a font name (see
Section “Fonts” in The GNU Emacs Manual); if the font name is an XLFD
containing wildcards, Emacs chooses the first font matching those wildcards.
Specifying this attribute also changes the values of the :family, :foundry,
:width, :height, :weight, and :slant attributes.
:inherit The name of a face from which to inherit attributes, or a list of face names.
Attributes from inherited faces are merged into the face like an underlying
face would be, with higher priority than underlying faces (see Section 40.12.4
[Displaying Faces], page 1079). If the face to inherit from is unspecified, it is
treated the same as nil, since Emacs never merges :inherit attributes. If a
list of faces is used, attributes from faces earlier in the list override those from
later faces.
:extend Whether or not this face will be extended beyond end of line and will affect
the display of the empty space between the end of line and the edge of the
window. The value should be t to display the empty space between end of
line and edge of the window using this face, or nil to not use this face for the
space between the end of the line and the edge of the window. When Emacs
merges several faces for displaying the empty space beyond end of line, only
those faces with :extend non-nil will be merged. By default, only a small
Chapter 40: Emacs Display 1073
number of faces, notably, region, have this attribute set. This attribute is
different from the others in that when a theme doesn’t specify an explicit value
for a face, the value from the original face definition by defface is inherited
(see Section 40.12.2 [Defining Faces], page 1073).
Some modes, like hl-line-mode, use a face with an :extend property to mark
the entire current line. Note, however, that Emacs will always allow you to
move point after the final character in a buffer, and if the buffer ends with a
newline character, point can be placed on what is seemingly a line at the end
of the buffer—but Emacs can’t highlight that “line”, because it doesn’t really
exist.
The default face spec determines face’s appearance when no customizations are in
effect (see Chapter 15 [Customization], page 264). If face has already been customized
(via Custom themes or via customizations read from the init file), its appearance is
determined by the custom face spec(s), which override the default face spec spec.
However, if the customizations are subsequently removed, the appearance of face will
again be determined by its default face spec.
As an exception, if you evaluate a defface form with C-M-x (eval-defun) or with
C-x C-e (eval-last-sexp) in Emacs Lisp mode, a special feature of these commands
overrides any custom face specs on the face, causing the face to reflect exactly what
the defface says.
The spec argument is a face spec, which states how the face should appear on different
kinds of terminals. It should be an alist whose elements each have the form
(display . plist)
display specifies a class of terminals (see below). plist is a property list of face
attributes and their values, specifying how the face appears on such terminals. For
backward compatibility, you can also write an element as (display plist).
The display part of an element of spec determines which terminals the element
matches. If more than one element of spec matches a given terminal, the first el-
ement that matches is the one used for that terminal. There are three possibilities
for display:
default This element of spec doesn’t match any terminal; instead, it specifies
defaults that apply to all terminals. This element, if used, must be the
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 40.24
[Window Systems], page 1146.
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.
Chapter 40: Emacs Display 1075
supports Whether or not the terminal can display the face attributes
given in value . . . (see Section 40.12.1 [Face Attributes],
page 1069). See [Display Face Attribute Testing], page 794,
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.
specs on face of all the other types mentioned below. This is useful when calling this
function outside of Custom code. If spec-type is customized-face or saved-face,
this function sets the customized spec or the saved custom spec, respectively. If it
is face-defface-spec, this function sets the default face spec (the same one set by
defface). If it is reset, this function clears out all customization specs and override
specs from face (in this case, the value of spec is ignored). The effect of any other
value of spec-type on the face specs is reserved for internal use, but the function will
still define face itself and recalculate its attributes, as described above.
Normally, Emacs uses the face specs of each face to automatically calculate its attributes
on each frame (see Section 40.12.2 [Defining Faces], page 1073). 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.
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.
Chapter 40: Emacs Display 1078
• If the text lies within the mode line of the selected window, Emacs applies the
mode-line face. For the mode line of a non-selected window, Emacs applies the
mode-line-inactive face. For a header line, Emacs applies the header-line face.
For a tab line, Emacs applies the tab-line face.
• If the text comes from an overlay string via before-string or after-string proper-
ties (see Section 40.9.2 [Overlay Properties], page 1059), or from a display string (see
Section 40.16.4 [Other Display Specs], page 1106), and the string doesn’t contain a
face or mouse-face property, or these properties leave some face attributes undefined,
but the buffer text affected by the overlay/display property does define a face or those
attributes, 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 40.16.5 [Display Margins], page 1107).
• 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 40.12.1 [Face Attributes], page 1069. 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 33.19.4 [Special Properties],
page 866. 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. If face-remapping-alist includes faces applicable only to certain windows,
by using the (:filtered (:window param val) spec), that face takes effect only in
windows that match the filter conditions (see Section 33.19.4 [Special Properties],
page 866). To turn off face filtering temporarily, bind face-filters-always-match
to a non-nil value, then all face filters will match any window.
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)
Chapter 40: Emacs Display 1081
then the new definition of the mode-line face inherits from the italic face, and the
normal (non-remapped) definition of mode-line face.
face-list [Function]
This function returns a list of all defined face names.
A face alias provides an equivalent name for a face. You can define a face alias by
giving the alias symbol the face-alias property, with a value of the target face name. The
following example makes modeline an alias for the mode-line face.
(put 'modeline 'face-alias 'mode-line)
fontification-functions [Variable]
This variable holds a list of functions that are called by Emacs redisplay as needed,
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.
Chapter 40: Emacs Display 1083
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.
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 40.12.1 [Face Attributes], page 1069).
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 33.19.4 [Special Properties], page 866).
Chapter 40: Emacs Display 1084
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.
Emacs can make use of scalable fonts, but by default it does not use them.
face-font-rescale-alist [Variable]
This variable specifies scaling for certain faces. Its value should be a list of elements
of the form
(fontname-regexp . scale-factor)
If fontname-regexp matches the font name that is about to be used, this says to choose
a larger similar font according to the factor scale-factor. You would use this feature
to normalize the font size if certain fonts are bigger or smaller than their nominal
heights and widths would suggest.
40.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
Chapter 40: Emacs Display 1087
for that character set. You can use this construct any number of times in the specification
string.
For the remaining character sets, those that you don’t specify explicitly, Emacs chooses
a font based on fontpattern: it replaces ‘fontset-alias’ with a value that names one
character set. For the ASCII character set, ‘fontset-alias’ is replaced with ‘ISO8859-1’.
In addition, when several consecutive fields are wildcards, Emacs collapses them into a
single wildcard. This is to prevent use of auto-scaled fonts. Fonts made by scaling larger
fonts are not usable for editing, and scaling a smaller font is not useful because it is better
to use the smaller font in its own size, which Emacs does.
Thus if fontpattern is this,
-*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24
the font specification for ASCII characters would be this:
-*-fixed-medium-r-normal-*-24-*-ISO8859-1
and the font specification for Chinese GB2312 characters would be this:
-*-fixed-medium-r-normal-*-24-*-gb2312*-*
You may not have any Chinese font matching the above font specification. Most X
distributions include only Chinese fonts that have ‘song ti’ or ‘fangsong ti’ in the family
field. In such a case, ‘Fontset-n’ can be specified as below:
Emacs.Fontset-0: -*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24,\
chinese-gb2312:-*-*-medium-r-normal-*-24-*-gb2312*-*
Then, the font specifications for all but Chinese GB2312 characters have ‘fixed’ in the
family field, and the font specification for Chinese GB2312 characters has a wild card ‘*’
in the family field.
font-spec may be a cons cell (family . registry), where family is a family name
of a font (possibly including a foundry name at the head), and registry is a registry
name of a font (possibly including an encoding name at the tail).
font-spec may be a font name, a string.
font-spec may be nil, which explicitly specifies that there’s no font for the specified
characters. This is useful, for example, to avoid expensive system-wide search for
fonts for characters that have no glyphs, like those from the Unicode Private Use
Area (PUA).
The optional argument add, if non-nil, specifies how to add font-spec to the font
specifications previously set for characters. If it is prepend, font-spec is prepended
to the existing specs. If it is append, font-spec is appended. By default, font-spec
overwrites the previously set font specs.
For instance, this changes the default fontset to use a font whose 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 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.
font-spec &rest arguments [Function]
Return a new font spec using the specifications in arguments, which should come in
property-value pairs. The possible specifications are as follows:
:name The font name (a string), in either XLFD, Fontconfig, or GTK+ format.
See Section “Fonts” in The GNU Emacs Manual.
:family
:foundry
:weight
:slant
:width These have the same meanings as the face attributes of the same name.
See Section 40.12.1 [Face Attributes], page 1069. :family and :foundry
are strings, while the other three are symbols. As example values, :slant
may be italic, :weight may be bold and :width may be normal.
: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.
:dpi The resolution in dots per inch for which the font is designed. The value
must be a non-negative number.
:spacing The spacing of the font: proportional, dual, mono, or charcell. The value
should be either an integer (0 for proportional, 90 for dual, 100 for mono,
110 for charcell) or a one-letter symbol (one of P, D, M, or C).
:avgwidth
The average width of the font in 1/10 pixel units. The value should be a
non-negative number.
: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)
Chapter 40: Emacs Display 1090
If font is a font spec and the font spec does not specify property, the return value is
nil. If font is a font object or font entity, the value for the :script property may be
a list of scripts supported by the font, and the value of the :otf property is a cons
of the form (gsub . gpos), where gsub and gpos are lists representing OpenType
features supported by the font, of the form
((script-tag (langsys-tag feature...) ...) ...)
where script-tag, langsys-tag, and feature are symbols representing OpenType layout
tags.
If font is a font object, the special property :combining-capability is non-nil if the
font backend of font supports rendering of combining characters for non-OpenType
fonts.
font-face-attributes font &optional frame [Function]
This function returns a list of face attributes corresponding to font. The optional
argument frame specifies the frame on which the font is to be displayed. If it is nil,
the selected frame is used. The return value has the form
(:family family :height height :weight weight
:slant slant :width width)
where the values of family, height, weight, slant, and width are face attribute values.
Some of these key-attribute pairs may be omitted from the list if they are not specified
by font.
font-xlfd-name font &optional fold-wildcards [Function]
This function returns the XLFD (X Logical Font Descriptor), a string, matching font.
See Section “Fonts” in The GNU Emacs Manual, for information about XLFDs. If
the name is too long for an XLFD (which can contain at most 255 characters), the
function returns nil.
If the optional argument fold-wildcards is non-nil, consecutive wildcards in the XLFD
are folded into one.
The following two functions return important information about a font.
font-info name &optional frame [Function]
This function returns information about a font specified by its name, a string, as it
is used on frame. If frame is omitted or nil, it defaults to the selected frame.
The value returned by the function is a vector of the form [opened-name full-name
size height baseline-offset relative-compose default-ascent max-width
ascent descent space-width average-width filename capability]. Here’s the
description of each components of this vector:
opened-name
The name used to open the font, a string.
full-name The full name of the font, a string.
size The pixel size of the font.
height The height of the font in pixels.
baseline-offset
The offset in pixels from the ASCII baseline, positive upward.
Chapter 40: Emacs Display 1092
relative-compose
default-ascent
Numbers controlling how to compose characters.
max-width
The maximum advance width of the font.
ascent
descent The ascent and descent of this font. The sum of these two numbers should
be equal to the value of height above.
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.
filename The file name of the font as a string. This can be nil if the font back-end
does not provide a way to find out the font’s file name.
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.
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 40.12.5 [Face Remapping], page 1080.
default-font-width [Function]
This function returns the average width in pixels of the font used by the current
buffer’s default face, as that face is defined for the selected frame.
default-font-height [Function]
This function returns the height in pixels of the font used by the current buffer’s
default face, as that face is defined for the selected frame.
window-font-width &optional window face [Function]
This function returns the average width in pixels for the font used by face in window.
The specified window must be a live window. If nil or omitted, window defaults to
the selected window, and face defaults to the default face in window.
window-font-height &optional window face [Function]
This function returns the height in pixels for the font used by face in window. The
specified window must be a live window. If nil or omitted, window defaults to the
selected window, and face defaults to the default face in window.
40.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.
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 30.4.3.4 [Layout
Parameters], page 760).
The above variables actually take effect via the function set-window-buffer (see
Section 29.11 [Buffers and Windows], page 673), 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.
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 after the buffer end when indicate-empty-
lines is non-nil.
Chapter 40: Emacs Display 1096
overlay-arrow
Used for overlay arrows (see Section 40.13.6 [Overlay Arrow], page 1098).
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
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 40.13.4 [Fringe Bitmaps], page 1096, 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.
Lisp programs can also directly display a bitmap in the left or right fringe, by using a
display property for one of the characters appearing in the line (see Section 40.16.4 [Other
Display Specs], page 1106). Such a display specification has the form
(fringe bitmap [face])
fringe is either the symbol left-fringe or right-fringe. bitmap is a symbol identifying
the bitmap to display. The optional face names a face whose foreground and background
colors are to be used to display the bitmap, using the attributes of the fringe face for
colors that face didn’t specify. If face is omitted, that means to use the attributes of the
default face for the colors which the fringe face didn’t specify. For predictable results
that don’t depend on the attributes of the default and fringe faces, we recommend you
never omit face, but always provide a specific face. In particular, if you want the bitmap to
be always displayed in the fringe face, use fringe as face.
For instance, to display an arrow in the left fringe, using the warning face, you could
say something like:
(overlay-put
(make-overlay (point) (point))
'before-string (propertize
"x" 'display
`(left-fringe right-arrow warning)))
Here is a list of the standard fringe bitmaps defined in Emacs, and how they are currently
used in Emacs (via fringe-indicator-alist and fringe-cursor-alist):
left-arrow, right-arrow
Used to indicate truncated lines.
left-curly-arrow, right-curly-arrow
Used to indicate continued lines.
right-triangle, left-triangle
The former is used by overlay arrows. The latter is unused.
up-arrow, down-arrow
bottom-left-angle, bottom-right-angle
top-left-angle, top-right-angle
left-bracket, right-bracket
empty-line
Used to indicate buffer boundaries.
filled-rectangle, hollow-rectangle
filled-square, hollow-square
vertical-bar, horizontal-bar
Used for different types of fringe cursors.
exclamation-mark, question-mark
Not used by core Emacs features.
The next subsection describes how to define your own fringe bitmaps.
fringe-bitmaps-at-pos &optional pos window [Function]
This function returns the fringe bitmaps of the display line containing position pos in
window window. The return value has the form (left right ov), where left is the
Chapter 40: Emacs Display 1098
symbol for the fringe bitmap in the left fringe (or nil if no bitmap), right is similar
for the right fringe, and ov is non-nil if there is an overlay arrow in the left fringe.
The value is nil if pos is not visible in window. If window is nil, that stands for the
selected window. If pos is nil, that stands for the value of point in window.
overlay-arrow-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, or when the left
fringe is not shown, 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 40.9.2 [Overlay Properties], page 1059.
You can define multiple overlay arrows via the variable overlay-arrow-variable-list.
overlay-arrow-variable-list [Variable]
This variable’s value is a list of variables, each of which specifies the position of
an overlay arrow. The variable overlay-arrow-position has its normal meaning
because it is on this list.
You can override the frame specific settings for individual windows by using the following
function:
The value width is the value that was specified for the width of the vertical scroll bar
(which may be nil); columns is the (possibly rounded) number of columns that the
vertical scroll bar actually occupies.
The value height is the value that was specified for the height of the horizontal scroll
bar (which may be nil); lines is the (possibly rounded) number of lines that the
horizontally scroll bar actually occupies.
The value of persistent is the value specified for window with the last successful
invocation of set-window-scroll-bars, nil if there never was one.
If you do not specify a window’s scroll bar settings via 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.
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.
Chapter 40: Emacs Display 1102
window-divider
When a divider is less than three pixels wide, it is drawn solidly with the
foreground of this face. For larger dividers this face is used for the inner part
only, excluding the first and last pixel.
window-divider-first-pixel
This is the face used for drawing the first 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.
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.
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.
Note that space properties are treated as paragraph separators for the purposes of re-
ordering bidirectional text for display. See Section 40.26 [Bidirectional Display], page 1148,
for the details.
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.
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.
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.
the display property. There is currently no way to make text or images in the margin
mouse-sensitive.
The way to display something in the margins is to specify it in a margin display spec-
ification in the display property of some text. This is a replacing display specification,
meaning that the text you put it on does not get displayed; the margin display appears,
but that text does not.
A margin display specification looks like ((margin right-margin) spec) or ((margin
left-margin) spec). Here, spec is another display specification that says what to display
in the margin. Typically it is a string of text to display, or an image descriptor.
To display something in the margin in association with certain buffer text, without
altering or preventing the display of that text, put a before-string property on the text
and put the margin display specification on the contents of the before-string.
Note that if the string to be displayed in the margin doesn’t specify a face, its face is
determined using the same rules and priorities as it is for strings displayed in the text area
(see Section 40.12.4 [Displaying Faces], page 1079). If this results in undesirable “leaking”
of faces into the margin, make sure the string has an explicit face specified for it.
Before the display margins can display anything, you must give them a nonzero width.
The usual way to do that is to set these variables:
left-margin-width [Variable]
This variable specifies the width of the left margin, in character cell (a.k.a. “column”)
units. It is buffer-local in all buffers. A value of nil means no left marginal area.
right-margin-width [Variable]
This variable specifies the width of the right margin, in character cell units. It is
buffer-local in all buffers. A value of nil means no right marginal area.
Setting these variables does not immediately affect the window. These variables are
checked when a new buffer is displayed in the window. Thus, you can make changes take
effect by calling set-window-buffer. Do not use these variables to try to determine the
current width of the left or right margin. Instead, use the function window-margins.
You can also set the margin widths immediately.
set-window-margins window left &optional right [Function]
This function specifies the margin widths for window window, in character cell units.
The argument left controls the left margin, and right controls the right margin (default
0).
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 29.11 [Buffers and Windows], page 673) on window with its keep-margins
argument nil or omitted.
window-margins &optional window [Function]
This function returns the width of the left and right margins of window as a cons cell
of the form (left . right). If one of the two marginal areas does not exist, its width
is returned as nil; if neither of the two margins exist, the function returns (nil). If
window is nil, the selected window is used.
Chapter 40: Emacs Display 1109
40.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 40.16
[Display Property], page 1103).
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 30.25
[Display Feature Testing], page 794).
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.
Each image descriptor has the form (image . props), where props is a property list
of alternating keyword symbols and values, including at least the pair :type type that
specifies the image type.
Image descriptors which define image dimensions, :width, :height, :max-width and
:max-height, may take either an integer, which represents the dimension in pixels, or a
pair (value . em), where value is the dimension’s length in ems 3 . One em is equivalent to
the height of the font and value may be an integer or a float.
The following is a list of properties that are meaningful for all image types (there are
also properties which are meaningful only for certain image types, as documented in the
following subsections):
:type type
The image type. Every image descriptor must include this property.
:file file
This says to load the image from file file. If file is not an absolute file name,
it is expanded relative to the images subdirectory of data-directory, and
failing that, relative to the directories listed by x-bitmap-file-path (see
Section 40.12.1 [Face Attributes], page 1069).
:data data
This specifies the raw image data. Each image descriptor must have either
:data or :file, but not both.
For most image types, the value of a :data property should be a string contain-
ing the image data. Some image types do not support :data; for some others,
:data alone is not enough, so you need to use other image properties along
with :data. See the following subsections for details.
:margin margin
This specifies how many pixels to add as an extra margin around the image.
The value, margin, must be a non-negative number, or a pair (x . y) of such
numbers. If it is a pair, x specifies how many pixels to add horizontally, and
y specifies how many pixels to add vertically. If :margin is not specified, the
default is zero.
:ascent ascent
This specifies the amount of the image’s height to use for its ascent—that is,
the part above the baseline. The value, ascent, must be a number in the range
0 to 100, or the symbol center.
If ascent is a number, that percentage of the image’s height is used for its ascent.
If ascent is center, the image is vertically centered around a centerline which
would be the vertical centerline of text drawn at the position of the image,
in the manner specified by the text properties and overlays that apply to the
image.
If this property is omitted, it defaults to 50.
3
In typography an em is a distance equivalent to the height of the type. For example when using 12 point
type 1 em is equal to 12 points. Its use ensures distances and type remain proportional.
Chapter 40: Emacs Display 1111
:relief relief
This adds a shadow rectangle around the image. The value, relief, specifies the
width of the shadow lines, in pixels. If relief is negative, shadows are drawn
so that the image appears as a pressed button; otherwise, it appears as an
unpressed button.
: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 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.
If both :max-width and :height are specified, but :width is not, preserving
the aspect ratio might require that width exceeds :max-width. If this happens,
scaling will use a smaller value for the height so as to preserve the aspect
ratio while not exceeding :max-width. Similarly when both :max-height and
:width are specified, but :height is not. For example, 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, by multiplying both the width and
height. For instance, a value of 0.25 will 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.
:rotation angle
Specifies a rotation angle in degrees. Only multiples of 90 degrees are supported,
unless the image type is imagemagick. Positive values rotate clockwise, negative
values counter-clockwise. Rotation is performed after scaling and cropping.
:transform-smoothing smooth
If this is t, any image transform will have smoothing applied; if nil, no smooth-
ing will be applied. The exact algorithm used is platform dependent, but should
be equivalent to bilinear filtering. Disabling smoothing will use the nearest
neighbor algorithm.
If this property is not specified, create-image will use the image-transform-
smoothing user option to say whether scaling should be done or not. This
option can be nil (no smoothing), t (use smoothing) or a predicate function
Chapter 40: Emacs Display 1112
that’s called with the image object as the only parameter, and should return
either nil or t. The default is for down-scaling to apply smoothing, and for
large up-scaling to not apply smoothing.
:index frame
See Section 40.17.10 [Multi-Frame Images], page 1127.
:conversion algorithm
This specifies a conversion algorithm that should be applied to the image before
it is displayed; the value, algorithm, specifies which algorithm.
laplace
emboss Specifies the Laplace edge detection algorithm, which blurs out
small differences in color while highlighting larger differences. Peo-
ple sometimes consider this useful for displaying the image for a
disabled button.
(edge-detection :matrix matrix :color-adjust adjust)
Specifies a general edge-detection algorithm. matrix must be either
a nine-element list or a nine-element vector of numbers. A pixel at
position x/y in the transformed image is computed from original
pixels around that position. matrix specifies, for each pixel in the
neighborhood of x/y, a factor with which that pixel will influence
the transformed pixel; element 0 specifies the factor for the pixel
at x − 1/y − 1, element 1 the factor for the pixel at x/y − 1 etc., as
shown below:
The resulting pixel is computed from the color intensity of the color
resulting from summing up the RGB values of surrounding pixels,
multiplied by the specified factors, and dividing that sum by the
sum of the factors’ absolute values.
Laplace edge-detection currently uses a matrix of
1 0 0
0 0 0
0 0 −1
2 −1 0
−1 0 1
0 1 −2
: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 30.19 [Pointer Shape], page 788, 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 30.19 [Pointer Shape],
page 788, 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). XBM files usually specify this themselves, and it’s an error to use these
two properties on these files. Also note that :width and :height are used by
most other image formats to specify what the displayed image is supposed to
be, which usually means performing some sort of scaling. This isn’t supported
for XBM images.
:stride stride
The number of bool vector entries stored for each row; the smallest multiple of
8 greater than or equal to width.
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.
: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.
:crop geometry
The value of geometry should be a list of the form (width height x y). width
and height specify the width and height of the cropped image. If x is a positive
number it specifies the offset of the cropped area from the left of the original
image, and if negative the offset from the right. If y is a positive number it
specifies the offset from the top of the original image, and if negative from the
bottom. If x or y are nil or unspecified the crop area will be centered on the
original image.
If the crop area is outside or overlaps the edge of the image it will be reduced
to exclude any areas outside of the image. This means it is not possible to use
:crop to increase the size of the image by entering large width or height values.
Cropping is performed after scaling but before rotation.
SVG library
If your Emacs build has SVG support, you can create and manipulate these images with
the following functions from the svg.el library.
svg-create width height &rest args [Function]
Create a new, empty SVG image with the specified dimensions. args is an argument
plist with you can specify following:
Chapter 40: Emacs Display 1117
:stroke-width
The default width (in pixels) of any lines created.
:stroke The default stroke color on any lines created.
This function returns an SVG object, a Lisp data structure that specifies an SVG
image, and all the following functions work on that structure. The argument svg in
the following functions specifies such an SVG object.
svg-gradient svg id type stops [Function]
Create a gradient in svg with identifier id. type specifies the gradient type, and can
be either linear or radial. stops is a list of percentage/color pairs.
The following will create a linear gradient that goes from red at the start, to green
25% of the way, to blue at the end:
(svg-gradient svg "gradient1" 'linear
'((0 . "red") (25 . "green") (100 . "blue")))
The gradient created (and inserted into the SVG object) can later be used by all
functions that create shapes.
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.
: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.
:clip-path
Identifier of a clip path.
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.
Chapter 40: Emacs Display 1118
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"
Chapter 40: Emacs Display 1120
:stroke-color "green")
(insert-image (svg-image svg)))
closepath [Command]
End the current subpath by connecting it back to its initial point. A line is drawn
along the connection.
(svg-path svg '((moveto ((200 . 100) (100 . 200) (0 . 100)))
(closepath)
(moveto ((75 . 125) (100 . 150) (125 . 125)))
(closepath))
:fill "red" :stroke "black")
a list of the form (x1 y1 x2 y2 x y), where (x, y) is the curve’s end point. (x1, y1)
and (x2, y2) are control points at the beginning and at the end, respectively.
(svg-path svg '((moveto ((100 . 100)))
(curveto ((200 100 100 200 200 200)
(300 200 0 100 100 100))))
:fill "transparent" :stroke "red")
:x-axis-rotation
The angle in degrees by which the x-axis of the ellipse is rotated relative
to the x-axis of the current coordinate system.
:large-arc
If set to t, draw an arc sweep greater than or equal to 180 degrees.
Otherwise, draw an arc sweep smaller than or equal to 180 degrees.
: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.
Chapter 40: Emacs Display 1123
: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.
The remaining image types that Emacs can support are:
GIF Image type gif. Supports the :index property. See Section 40.17.10 [Multi-
Frame Images], page 1127.
JPEG Image type jpeg.
PNG Image type png.
TIFF Image type tiff. Supports the :index property. See Section 40.17.10 [Multi-
Frame Images], page 1127.
"mh-e" "mh-logo.xpm"))
(image-load-path (cons (car load-path)
image-load-path)))
(mh-tool-bar-folder-buttons-init))
max-image-size [Variable]
This variable is used to define the maximum size of image that Emacs will load.
Emacs will refuse to load (and display) any image that is larger than this limit.
If the value is an integer, it directly specifies the maximum image height and width,
measured in pixels. If it is 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 40.17.11 [Image
Cache], page 1127).
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:
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.
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.
image-cache-size [Function]
This function returns the total size of the current image cache, in bytes. An image of
size 200x100 with 24 bits per color will have a cache size of 60000 bytes, for instance.
40.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
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.
keymap The button’s keymap, defining bindings active within the button region. By de-
fault this is the usual button region keymap, stored in the variable button-map,
which defines RET and mouse-2 to invoke the button.
type The button type. See Section 40.19.2 [Button Types], page 1131.
help-echo
A string displayed by the Emacs tooltip help system; by default, "mouse-2,
RET: Push this button". Alternatively, a function that returns, or a form that
evaluates to, a string to be displayed or nil. For details see [Text help-echo],
page 867.
The function is called with three arguments, window, object, and pos. The
second argument, object, is either the overlay that had the property (for over-
lay buttons), or the buffer containing the button (for text property buttons).
The other arguments have the same meaning as for the special text property
help-echo.
follow-link
The follow-link property, defining how a mouse-1 click behaves on this but-
ton, See Section 33.19.8 [Clickable Text], page 875.
button All buttons have a non-nil button property, which may be useful in finding
regions of text that comprise buttons (which is what the standard button func-
tions do).
There are other properties defined for the regions of text in a button, but these are not
generally interesting for typical uses.
button is governed by the face property; by default (via the face property inherited from
the button button-type) this is a simple underline, like a typical web-page link.
For convenience, there are two sorts of button-creation functions, those that add button
properties to an existing region of a buffer, called make-...button, and those that also
insert the button text, called insert-...button.
The button-creation functions all take the &rest argument properties, which should
be a sequence of property value pairs, specifying properties to add to the button; see
Section 40.19.1 [Button Properties], page 1130. In addition, the keyword argument
:type may be used to specify a button-type from which to inherit other properties; see
Section 40.19.2 [Button Types], page 1131. Any properties not explicitly specified during
creation will be inherited from the button’s type (if the type defines such a property).
The following functions add a button using an overlay (see Section 40.9 [Overlays],
page 1056) to hold the button properties:
The following functions are similar, but using text properties (see Section 33.19 [Text
Properties], page 858) 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.
the same effect: It’s a minor mode that does nothing else than install button-buffer-map
as a minor mode keymap.
If the button has a non-nil follow-link property, and mouse-1-click-follows-
link is set, a quick mouse-1 click will also activate the push-button command. See
Section 33.19.8 [Clickable Text], page 875.
An ewoc maintains its text in the buffer that is current when you create it, so switch
to the intended buffer before calling ewoc-create.
ewoc-buffer ewoc [Function]
This returns the buffer where ewoc maintains its text.
ewoc-get-hf ewoc [Function]
This returns a cons cell (header . footer) made from ewoc’s header and footer.
ewoc-set-hf ewoc header footer [Function]
This sets the header and footer of ewoc to the strings header and footer, respectively.
ewoc-enter-first ewoc data [Function]
ewoc-enter-last ewoc data [Function]
These add a new node encapsulating data, putting it, respectively, at the beginning
or end of ewoc’s chain of nodes.
ewoc-enter-before ewoc node data [Function]
ewoc-enter-after ewoc node data [Function]
These add a new node encapsulating data, adding it to ewoc before or after node,
respectively.
ewoc-prev ewoc node [Function]
ewoc-next ewoc node [Function]
These return, respectively, the previous node and the next node of node in ewoc.
ewoc-nth ewoc n [Function]
This returns the node in ewoc found at zero-based index n. A negative n means count
from the end. ewoc-nth returns nil if n is out of range.
ewoc-data node [Function]
This extracts the data encapsulated by node and returns it.
ewoc-set-data node data [Function]
This sets the data encapsulated by node to data.
ewoc-locate ewoc &optional pos guess [Function]
This determines the node in ewoc which contains point (or pos if specified), and
returns that node. If ewoc has no nodes, it returns nil. If pos is before the first
node, it returns the first node; if pos is after the last node, it returns the last node.
The optional third arg guess should be a node that is likely to be near pos; this
doesn’t alter the result, but makes the function run faster.
ewoc-location node [Function]
This returns the start position of node.
ewoc-goto-prev ewoc arg [Function]
ewoc-goto-next ewoc arg [Function]
These move point to the previous or next, respectively, argth node in ewoc.
ewoc-goto-prev does not move if it is already at the first node or if ewoc is empty,
whereas ewoc-goto-next moves past the last node, returning nil. Excepting this
special case, these functions return the node moved to.
Chapter 40: Emacs Display 1137
(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.
blink-matching-open [Command]
This function is the default value of blink-paren-function. It assumes that point
follows a character with close parenthesis syntax and applies the appropriate effect
momentarily to the matching opening character. If that character is not already
on the screen, it displays the character’s context in the echo area. To avoid long
delays, this function does not search farther than blink-matching-paren-distance
characters.
Here is an example of calling this function explicitly.
(defun interactive-blink-matching-open ()
"Indicate momentarily the start of parenthesized sexp before point."
(interactive)
(let ((blink-matching-paren-distance
(buffer-size))
(blink-matching-paren t))
(blink-matching-open)))
• Raw bytes are non-ASCII characters with codes 128 through 255 (see Section 34.1 [Text
Representations], page 900). 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 40.22.5 [Glyphless Chars], page 1144.
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 display 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 24.4 [Mode Line Format], page 515).
make-display-table [Function]
This creates and returns a display table. The table initially has nil in all elements.
The ordinary elements of the display table are indexed by character codes; the element
at index c says how to display the character code c. The value should be nil (which means
to display the character c according to the usual display conventions; see Section 40.22.1
[Usual Display], page 1140), or a vector of glyph codes (which means to display the character
c as those glyphs; see Section 40.22.4 [Glyphs], page 1143).
Chapter 40: Emacs Display 1142
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 40.22.4 [Glyphs], page 1143. 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 ‘\’).
4 A vector of glyphs for indicating the presence of invisible lines (the default is
‘...’). See Section 40.7 [Selective Display], page 1051.
5 The glyph used to draw the border between side-by-side windows (the default
is ‘|’). See Section 29.7 [Splitting Windows], page 662. 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 40.15 [Window Dividers],
page 1102), 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 40.22.4 [Glyphs], page 1143, 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 25.4 [Text Quoting Style], page 556.
The disp-table library defines several functions for changing the standard display table.
40.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 40.12 [Faces], page 1069). The main use of glyph codes
is as the entries of display tables (see Section 40.22.2 [Display Tables], page 1141). The
following functions are used to manipulate glyph codes:
Chapter 40: Emacs Display 1144
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 267), 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.
variation-selectors
Unicode VS-1 through VS-16 (U+FE00 through U+FE0F), which are used
to select between different glyphs for the same codepoints (typically emo-
jis).
no-font Characters for which there is no suitable font, or which cannot be en-
coded by the terminal’s coding system, or those for which the text-mode
terminal has no glyphs.
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.
40.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 174).
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.
Chapter 40: Emacs Display 1146
window-system [Variable]
This terminal-local variable tells Lisp programs what window system Emacs is using
for displaying the frame. The possible values are
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.)
40.25 Tooltips
Tooltips are special frames (see Chapter 30 [Frames], page 736) 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 33.19.4
[Special Properties], page 866) and about various UI elements, such as menu items
(see Section 23.17.1.2 [Extended Menu Items], page 477) and tool-bar buttons (see
Section 23.17.6 [Tool Bar], page 483).
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 30.4 [Frame Parameters], page 753). Unlike other frames,
the default parameters for tooltip frames are stored in a special variable.
tooltip-frame-parameters [User Option]
This customizable option holds the default frame parameters used for displaying
tooltips. Any font and color parameters are ignored, and the corresponding attributes
of the tooltip face are used instead. If left or top parameters are included, they
are used as absolute frame-relative coordinates where the tooltip should be shown.
(Mouse-relative position of the tooltip can be customized using the variables described
in Section “Tooltips” in The GNU Emacs Manual.) Note that the left and top pa-
rameters, if present, override the values of mouse-relative offsets.
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.
tooltip-event-buffer event [Function]
This function returns the buffer over which event occurred. Call it with the argument
of the function from tooltip-functions to obtain the buffer whose text triggered
Chapter 40: Emacs Display 1148
the tooltip. Note that the event might occur not over a buffer (e.g., over the tool
bar), in which case this function will return nil.
Other aspects of tooltip display are controlled by several customizable settings; see
Section “Tooltips” in The GNU Emacs Manual.
However, unibyte display and overlay strings are reordered if their parent buffer is re-
ordered. This is because plain-ascii strings are stored by Emacs as unibyte strings. If a
unibyte display or overlay string includes non-ascii characters, these characters are assumed
to have left-to-right direction.
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:
bidi-paragraph-direction [User Option]
If the value of this buffer-local variable is the symbol right-to-left or left-to-
right, all paragraphs in the buffer are assumed to have that specified direction. Any
Chapter 40: Emacs Display 1150
other value is equivalent to nil (the default), which means to determine the base
direction of each paragraph from its contents.
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 24.2.5 [Basic Major Modes], page 502).
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 40.16.2 [Specified Space], page 1104). Emacs treats this
Chapter 40: Emacs Display 1151
display specification as a paragraph separator, and reorders the text on either side
separately.
The reordering algorithm uses the bidirectional properties of the characters stored as
their bidi-class property (see Section 34.6 [Character Properties], page 905). Lisp pro-
grams can change these properties by calling the put-char-code-property function. How-
ever, doing this requires a thorough understanding of the UBA, and is therefore not recom-
mended. Any changes to the bidirectional properties of a character have global effect: they
affect all Emacs frames and windows.
Similarly, the mirroring property is used to display the appropriate mirrored character
in the reordered text. Lisp programs can affect the mirrored display by changing this
property. Again, any such changes affect all of Emacs display.
The bidirectional properties of characters can be overridden by inserting into the text
special directional control characters, LEFT-TO-RIGHT OVERRIDE (LRO) and RIGHT-
TO-LEFT OVERRIDE (RLO). Any characters between a RLO and the following newline
or POP DIRECTIONAL FORMATTING (PDF) control character, whichever comes first,
will be displayed as if they were strong right-to-left characters, i.e. they will be reversed
on display. Similarly, any characters between LRO and PDF or newline will display as if
they were strong left-to-right, and will not be reversed even if they are strong right-to-left
characters.
These overrides are useful when you want to make some text unaffected by the reordering
algorithm, and instead directly control the display order. But they can also be used for
malicious purposes, known as phishing. Specifically, a URL on a Web page or a link in an
email message can be manipulated to make its visual appearance unrecognizable, or similar
to some popular benign location, while the real location, interpreted by a browser in the
logical order, is very different.
Emacs provides a primitive that applications can use to detect instances of text whose
bidirectional properties were overridden so as to make a left-to-right character display as if
it were a right-to-left character, or vice versa.
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.
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
files are visited and the *Buffer List* buffer is displayed alongside initial-buffer-
choice.
26. It runs emacs-startup-hook.
27. It calls frame-notice-user-settings, which modifies the parameters of the selected
frame according to whatever the init files specify.
28. 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.
29. 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.
30. 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.
31. If started by the X session manager, it calls emacs-session-restore passing it as
argument the ID of the previous session. See Section 41.18 [Session Management],
page 1187.
The following options affect some aspects of the startup sequence.
easily inhibit the message for yourself if you wish, but thoughtless copying of your
init file will not inhibit the message for someone else.
initial-scratch-message [User Option]
This variable, if non-nil, should be a string, which is treated as documentation to be
inserted into the *scratch* buffer when Emacs starts up. If it is nil, the *scratch*
buffer is empty.
The following command-line options affect some aspects of the startup sequence. See Section
“Initial Options” in The GNU Emacs Manual.
--no-splash
Do not display a splash screen.
--batch Run without an interactive terminal. See Section 41.17 [Batch Mode],
page 1187.
--daemon
--bg-daemon
--fg-daemon
Do not initialize any display; just start a server. (A “background” daemon
automatically runs in the background.)
--no-init-file
-q Do not load either the init file, or the default library.
--no-site-file
Do not load the site-start library.
--quick
-Q Equivalent to ‘-q --no-site-file --no-splash’.
An Emacs installation may have a default init file, which is a Lisp library named
default.el. Emacs finds this file through the standard search path for libraries (see
Section 16.1 [How Programs Do Loading], page 284). The Emacs distribution does not
come with this file; it is intended for local customizations. If the default init file exists, it is
loaded whenever you start Emacs. But your own personal init file, if any, is loaded first; if
it sets inhibit-default-init to a non-nil value, then Emacs does not subsequently load
the default.el file. In batch mode, or if you specify ‘-q’ (or ‘-Q’), Emacs loads neither
your personal init file nor the default init file.
Another file for site-customization is site-start.el. Emacs loads this before the user’s
init file. You can inhibit the loading of this file with the option ‘--no-site-file’.
site-run-file [User Option]
This variable specifies the site-customization file to load before the user’s init file. Its
normal value is "site-start". The only way you can change it with real effect is to
do so before dumping Emacs.
See Section “Init File Examples” in The GNU Emacs Manual, for examples of how to
make various commonly desired customizations in your .emacs file.
inhibit-default-init [User Option]
If this variable is non-nil, it prevents Emacs from loading the default initialization
library file. The default value is nil.
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 41.1.1
[Startup Summary], page 1153.
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 default directory. It defaults to ${XDG_
CONFIG_HOME-'~/.config'}/emacs/ if that directory exists and ~/.emacs.d/ and
Chapter 41: Operating System Interface 1158
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 41.1.2 [Init File], page 1156.
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 1242), 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 (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.)
Note that the handling of command-switch-alist doesn’t treat equals signs in option
specially. That is, if there’s an option like --name=value on the command line,
then only a command-switch-alist member whose car is literally --name=value will
match this option. If you want to parse such options, you need to use command-line-
functions instead (see below).
Chapter 41: Operating System Interface 1160
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 41.17 [Batch Mode], page 1187).
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:
uses more than one terminal, you must delete the frames on all the other terminals
before suspending Emacs, or this function signals an error. See Section 30.2 [Multiple
Terminals], page 738.
If string is non-nil, its characters are sent to Emacs’s superior shell, to be read as
terminal input. The characters in string are not echoed by the superior shell; only
the results appear.
Before suspending, suspend-emacs runs the normal hook suspend-hook. After the
user resumes Emacs, suspend-emacs runs the normal hook suspend-resume-hook.
See Section 24.1 [Hooks], page 490.
The next redisplay after resumption will redraw the entire screen, unless the variable
no-redraw-on-reenter is non-nil. See Section 40.1 [Refresh Screen], page 1037.
Here is an example of how you could use these hooks:
(add-hook 'suspend-hook
(lambda () (or (y-or-n-p "Really suspend?")
(error "Suspend canceled"))))
(add-hook 'suspend-resume-hook (lambda () (message "Resumed!")
(sit-for 2)))
Here is what you would see upon evaluating (suspend-emacs "pwd"):
---------- Buffer: Minibuffer ----------
Really suspend? y
---------- Buffer: Minibuffer ----------
This function reopens the terminal device, re-initializes it, and redraws it with that
terminal’s selected frame. It then runs the hook resume-tty-functions, passing the
terminal object as an argument to each function.
If the same device is already used by another Emacs terminal, this function signals
an error. If tty is not suspended, this function does nothing.
controlling-tty-p &optional tty [Function]
This function returns non-nil if tty is the controlling terminal of the Emacs session;
tty can be a terminal object, a frame (meaning the terminal for that frame), or nil
(meaning the terminal for the selected frame).
suspend-frame [Command]
This command suspends a frame. For GUI frames, it calls iconify-frame (see
Section 30.11 [Visibility of Frames], page 778); 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.
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.
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"
...)
If process-environment contains multiple elements that specify the same environ-
ment variable, the first of these elements specifies the variable, and the others are
ignored.
initial-environment [Variable]
This variable holds the list of environment variables Emacs inherited from its parent
process when Emacs started.
path-separator [Variable]
This variable holds a string that says which character separates directories in a search
path (as found in an environment variable). Its value is ":" for Unix and GNU
systems, and ";" for MS systems.
path-separator [Function]
This function returns the connection-local value of variable path-separator. That
is ";" for MS systems and a local default-directory, and ":" for Unix and GNU
systems, or a remote default-directory.
invocation-name [Variable]
This variable holds the program name under which Emacs was invoked. The value is
a string, and does not include a directory name.
invocation-directory [Variable]
This variable holds the directory in which the Emacs executable was located when it
was run, or nil if that directory cannot be determined.
installation-directory [Variable]
If non-nil, this is a directory within which to look for the lib-src and etc sub-
directories. In an installed Emacs, it is normally nil. It is non-nil when Emacs
can’t find those directories in their standard installed locations, but can find them
in a directory related somehow to the one containing the Emacs executable (i.e.,
invocation-directory).
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.
null-device [Variable]
This variable holds the system null device. Its value is "/dev/null" for Unix and
GNU systems, and "NUL" for MS systems.
null-device [Function]
This function returns the connection-local value of variable null-device. That is
"NUL" for MS systems and a local default-directory, and "/dev/null" for Unix
and GNU systems, or a remote default-directory.
Chapter 41: Operating System Interface 1167
group-real-gid [Function]
This function returns the real GID of the Emacs process.
system-users [Function]
This function returns a list of strings, listing the user names on the system. If Emacs
cannot retrieve this information, the return value is a list containing just the value of
user-real-login-name.
system-groups [Function]
This function returns a list of strings, listing the names of user groups on the system.
If Emacs cannot retrieve this information, the return value is nil.
Time values can be converted to and from calendrical and other forms. Some of these
conversions rely on operating system functions that limit the range of possible time values,
and signal an error such as ‘"Specified time is not representable"’ if the limits are
exceeded. For instance, a system may not support years before 1970, or years before 1901,
or years far in the future. You can convert a time value into a human-readable string
using format-time-string, into a Lisp timestamp using time-convert, and into other
forms using decode-time and float-time. These functions are described in the following
sections.
current-time [Function]
This function returns the current time as a Lisp timestamp. Although the timestamp
takes the form (high low micro pico) in the current Emacs release, this is planned to
change in a future Emacs version. You can use the time-convert function to convert
a timestamp to some other form. See Section 41.7 [Time Conversion], page 1170.
The set of supported TZ strings is system-dependent. GNU and many other systems
support the tzdata database, e.g., ‘"America/New_York"’ specifies the time zone and day-
light saving time history for locations near New York City. GNU and most other systems
support POSIX-style TZ strings, e.g., ‘"EST+5EDT,M4.1.0/2,M10.5.0/2"’ specifies the rules
used in New York from 1987 through 2006. All systems support the string ‘"UTC0"’ meaning
Universal Time.
Functions that convert to and from local time accept an optional time zone rule argu-
ment, which specifies the conversion’s time zone and daylight saving time history. If the
time zone rule is omitted or nil, the conversion uses Emacs’s default time zone. If it is
t, the conversion uses Universal Time. If it is wall, the conversion uses the system wall
clock time. If it is a string, the conversion uses the time zone rule equivalent to setting
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.
make-decoded-time &key second minute hour day month year dst [Function]
zone
Return a decoded time structure with only the given keywords filled out, leaving the
rest nil. For instance, to get a structure that represents “two months”, you could
say:
(make-decoded-time :month 2)
The format of this list is the same as what decode-time accepts (see Section 41.7
[Time Conversion], page 1170), and is described in more detail there. Any dst element
that cannot be determined from the input is set to −1, and any other unknown element
is 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.
iso8601-parse string [Function]
For a more strict function (that will error out upon invalid input), this function can
be used instead. It can parse all variants of the ISO 8601 standard, so in addition to
the formats mentioned above, it also parses things like “1998W45-3” (week number)
and “1998-245” (ordinal day number). To parse durations, there’s iso8601-parse-
duration, and to parse intervals, there’s iso8601-parse-interval. All these func-
tions return decoded time structures, except the final one, which returns three of
them (the start, the end, and the duration).
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 41.6 [Time Zone Rules], page 1169.
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, which is like ‘%+4Y-%m-%d’
except that any flags or field width override the ‘+’ and (after subtracting
6) the ‘4’.
‘%g’ This stands for the year without century (00–99) corresponding to the
current ISO week number. ISO weeks start on Monday and end on Sun-
day. If an ISO week begins in one year and ends in another, the rules
regarding which year ‘%g’ will produce are complex and will not be de-
scribed here; however, in general, if most of the week’s days are in the
ending year, ‘%g’ will produce that year.
‘%G’ This stands for the year with century corresponding to the current ISO
week number.
Chapter 41: Operating System Interface 1175
‘%z’ This stands for the time zone numerical offset. The ‘z’ can be preceded
by one, two, or three colons; if plain ‘%z’ stands for ‘-0500’, then ‘%:z’
stands for ‘-05:00’, ‘%::z’ stands for ‘-05:00:00’, and ‘%:::z’ is like
‘%::z’ except it suppresses trailing instances of ‘:00’ so it stands for
‘-05’ in the same example.
‘%%’ This stands for a single ‘%’.
One or more flag characters can appear immediately after the ‘%’. ‘0’ pads with zeros,
‘+’ pads with zeros and also puts ‘+’ before nonnegative year numbers with more than
four digits, ‘_’ pads with blanks, ‘-’ suppresses padding, ‘^’ upper-cases letters, and
‘#’ reverses the case of letters.
You can also specify the field width and type of padding for any of these ‘%’-sequences.
This works as in printf: you write the field width as digits in a ‘%’-sequence, after
any flags. For example, ‘%S’ specifies the number of seconds since the minute; ‘%03S’
means to pad this with zeros to 3 positions, ‘%_3S’ to pad with spaces to 3 positions.
Plain ‘%3S’ pads with zeros, because that is how ‘%S’ normally pads to two positions.
The characters ‘E’ and ‘O’ act as modifiers when used 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 converts time and zone to internal form;
the operating system limits the range of time and zone values. This function also
encodes format-string using the coding system specified by locale-coding-system
(see Section 34.12 [Locales], page 928); after strftime returns the resulting string,
this function decodes the string using that same coding system.
‘%m’
‘%M’ The integer number of minutes.
‘%s’
‘%S’ The number of seconds. If the optional ‘,’ parameter is used, it’s a
floating point number, and the number after the ‘,’ specifies how many
decimals to be used. ‘%,2s’ means “use two decimals”.
‘%z’ Non-printing control flag. When it is used, other specifiers must be given
in the order of decreasing size, i.e., years before days, hours before min-
utes, etc. Nothing will be produced in the result string to the left of
‘%z’ until the first non-zero conversion is encountered. For example, the
default format used by emacs-uptime (see Section 41.9 [Processor Run
Time], page 1177) "%Y, %D, %H, %M, %z%S" means that the number of
seconds will always be produced, but years, days, hours, and minutes will
only be shown if they are non-zero.
‘%%’ Produces a literal ‘%’.
Upper-case format sequences produce the units in addition to the numbers, lower-case
formats produce only the numbers.
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".
time-less-p t1 t2 [Function]
This returns t if time value t1 is less than time value t2. The result is nil if either
argument is a NaN.
time-equal-p t1 t2 [Function]
This returns t if t1 and t2 are equal time values. The result is nil if either argument
is a NaN.
time-subtract t1 t2 [Function]
This returns the time difference t1 − t2 between two time values, as a Lisp time
value. The result is exact and its clock resolution is no worse than the worse of
its two arguments’ resolutions. The result is floating-point only if it is infinite or a
NaN. If you need the difference in units of elapsed seconds, you can convert it with
time-convert or float-time. See Section 41.7 [Time Conversion], page 1170.
time-add t1 t2 [Function]
This returns the sum of two time values, using the same conversion rules as
time-subtract. One argument should represent a time difference rather than a
point in time, as a time value that is often just a single number of elapsed seconds.
Here is how to add a number of seconds to a time value:
(time-add time seconds)
‘xxxx’, ‘x:xx’, or ‘xx:xx’ (military time), and ‘xxam’, ‘xxAM’, ‘xxpm’, ‘xxPM’, ‘xx:xxam’,
‘xx:xxAM’, ‘xx:xxpm’, or ‘xx:xxPM’. A period can be used instead of a colon to
separate the hour and minute parts.
To specify a relative time as a string, use numbers followed by units. For example:
‘1 min’ denotes 1 minute from now.
‘1 min 5 sec’
denotes 65 seconds from now.
‘1 min 2 sec 3 hour 4 day 5 week 6 fortnight 7 month 8 year’
denotes exactly 103 months, 123 days, and 10862 seconds from now.
For relative time values, Emacs considers a month to be exactly thirty days, and a
year to be exactly 365.25 days.
Not all convenient formats are strings. If time is a number (integer or floating point),
that specifies a relative time measured in seconds. The result of encode-time can
also be used to specify an absolute value for time.
In most cases, repeat has no effect on when first call takes place—time alone specifies
that. There is one exception: if time is t, then the timer runs whenever the time
is a multiple of repeat seconds after the epoch. This is useful for functions like
display-time.
If Emacs didn’t get any CPU time when the timer would have run (for example if
the system was busy running another process or if the computer was sleeping or in a
suspended state), the timer will run as soon as Emacs resumes and is idle.
The function run-at-time returns a timer value that identifies the particular sched-
uled future action. You can use this value to call cancel-timer (see below).
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 list-timers command lists all the currently active timers. The command c
(timer-list-cancel) will cancel the timer on the line under point. You can sort the
list by column using the command S (tabulated-list-sort).
Emacs becomes idle when it starts waiting for user input (unless it waits for input with
a timeout, see Section 22.8.2 [Reading One Event], page 434), and it remains idle until the
user provides some input. If a timer is set for five seconds of idleness, it runs approximately
five seconds after Emacs first becomes idle. Even if repeat is non-nil, this timer will not
run again as long as Emacs remains idle, because the duration of idleness will continue to
increase and will not go down to five seconds again.
Emacs can do various things while idle: garbage collect, autosave or handle data from a
subprocess. But these interludes during idleness do not interfere with idle timers, because
they do not reset the clock of idleness to zero. An idle timer set for 600 seconds will run
when ten minutes have elapsed since the last user command was finished, even if subprocess
Chapter 41: Operating System Interface 1182
output has been accepted thousands of times within those ten minutes, and even if there
have been garbage collections and autosaves.
When the user supplies input, Emacs becomes non-idle while executing the input. Then
it becomes idle again, and all the idle timers that are set up to repeat will subsequently run
another time, one by one.
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, using
the same format as current-time (see Section 41.5 [Time of Day], page 1168).
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))))
Chapter 41: Operating System Interface 1183
the terminal, encode it using one of the functions described in Section 34.10.7 [Explicit
Encoding], page 925.) This function operates only on text terminals. terminal may
be a terminal object, a frame, or nil for the selected frame’s terminal. In batch
mode, string is sent to stdout when terminal is nil.
One use of this function is to define function keys on terminals that have downloadable
function key definitions. For example, this is how (on certain terminals) to define
function key 4 to move forward four characters (by transmitting the characters C-u
C-f to the computer):
(send-string-to-terminal "\eF4\^U\^F")
⇒ nil
:volume volume
This specifies how loud to play the sound. It should be a number in the
range of 0 to 1. The default is to use whatever volume has been specified
before.
:device device
This specifies the system device on which to play the sound, as a string.
The default device is system-dependent.
Before actually playing the sound, play-sound calls the functions in the list
play-sound-functions. Each function is called with one argument, sound.
play-sound-file file &optional volume device [Command]
This function is an alternative interface to playing a sound file specifying an optional
volume and device.
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.
noninteractive [Variable]
This variable is non-nil when Emacs is running in batch mode.
If Emacs exits due to signaling an error in batch mode, the exit status of the Emacs
command is non-zero:
$ emacs -Q --batch --eval '(error "foo")'; echo $?
foo
255
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.
Chapter 41: Operating System Interface 1188
Subsequently, when the session manager restarts Emacs, it loads the session file au-
tomatically (see Chapter 16 [Loading], page 284). This is performed by a function
named emacs-session-restore, which is called during startup. See Section 41.1.1
[Startup Summary], page 1153.
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
(format "%S" '(with-current-buffer "*scratch*"
(insert "I am restored"))))
nil)
:app-icon icon-file
The file name of the notification icon. If set to nil, no icon is displayed.
The default is notifications-application-icon.
:actions (key title key title ...)
A list of actions to be applied. key and title are both strings. The default
action (usually invoked by clicking the notification) should have a key
named ‘"default"’. The title can be anything, though implementations
are free not to display it.
:timeout timeout
The timeout time in milliseconds since the display of the notification at
which the notification should automatically close. If −1, the notification’s
expiration time is dependent on the notification server’s settings, and
may vary for the type of notification. If 0, the notification never expires.
Default value is −1.
:urgency urgency
The urgency level. It can be low, normal, or critical.
: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 (https://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.
Chapter 41: Operating System Interface 1190
: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.
: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
Chapter 41: Operating System Interface 1191
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:
w32-notification-notify &rest params [Function]
This function displays an MS-Windows tray notification as specified by params. MS-
Windows tray notifications are displayed in a balloon from an icon in the notification
area of the taskbar.
Value is the integer unique ID of the notification that can be used to remove the
notification using w32-notification-close, described below. If the function fails,
the return value is nil.
The arguments params are specified as keyword/value pairs. All the parameters are
optional, but if no parameters are specified, the function will do nothing and return
nil.
The following parameters are supported:
:icon icon
Display icon in the system tray. If icon is a string, it should specify a
file name from which to load the icon; the specified file should be a .ico
Windows icon file. If icon is not a string, or if this parameter is not
specified, the standard Emacs icon will be used.
:tip tip Use tip as the tooltip for the notification. If tip is a string, this is the text
of a tooltip that will be shown when the mouse pointer hovers over the
tray icon added by the notification. If tip is not a string, or if this parame-
ter is not specified, the default tooltip text is ‘Emacs notification’. The
tooltip text can be up to 127 characters long (63 on Windows versions
before W2K). Longer strings will be truncated.
:level level
Notification severity level, one of info, warning, or error. If given, the
value determines the icon displayed to the left of the notification title,
but only if the :title parameter (see below) is also specified and is a
string.
:title title
The title of the notification. If title is a string, it is displayed in a larger
font immediately above the body text. The title text can be up to 63
characters long; longer text will be truncated.
:body body
The body of the notification. If body is a string, it specifies the text of
the notification message. Use embedded newlines to control how the text
is broken into lines. The body text can be up to 255 characters long, and
will be truncated if it’s longer. Unlike with D-Bus, the body text should
be plain text, with no markup.
Note that versions of Windows before W2K support only :icon and :tip. The other
parameters can be passed, but they will be ignored on those old systems.
There can be at most one active notification at any given time. An active notification
must be removed by calling w32-notification-close before a new one can be shown.
Chapter 41: Operating System Interface 1193
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.
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 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 reliably report file
attribute changes when watching a directory.
The stopped event means that watching the file has been discontinued. 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
which makes further watching impossible.
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.
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.
It is by no means complete; it is intended to give you an idea of the security issues involved,
rather than to be a security checklist.
File local variables
A file that Emacs visits can contain variable settings that affect the buffer
visiting that file; See Section 12.12 [File Local Variables], page 208. Similarly, a
directory can specify local variable values common to all files in that directory;
see Section 12.13 [Directory Local Variables], page 211. Although Emacs takes
some effort to protect against misuse of these variables, a security hole can be
created merely by a package setting safe-local-variable too optimistically,
a problem that is all too common. To disable this feature for both files and
directories, set enable-local-variables to nil.
Access control
Although Emacs normally respects access permissions of the underlying operat-
ing system, in some cases it handles accesses specially. For example, file names
can have handlers that treat the files specially, with their own access checking.
See Section 26.12 [Magic File Names], page 604. 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 28.7 [Read Only Buffers], page 635.
Authentication
Emacs has several functions that deal with passwords, e.g., read-passwd. See
Section 21.9 [Reading a Password], page 395. 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 57.
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 39.2
[Shell Arguments], page 989. Typically it is safer to use call-process than a
subshell. See Section 39.3 [Synchronous Processes], page 990. And it is safer
yet to use builtin Emacs functions; for example, use (rename-file "a" "b" t)
instead of invoking mv. See Section 26.7 [Changing Files], page 584.
Coding systems
Emacs attempts to infer the coding systems of the files and network connections
it accesses. See Section 34.10 [Coding Systems], page 913. If Emacs infers
incorrectly, or if the other parties to the network connection disagree with
Chapter 41: Operating System Interface 1198
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.
Environment and configuration variables
POSIX specifies several environment variables that can affect how Emacs
behaves. Any environment variable whose name consists entirely of uppercase
ASCII letters, digits, and the underscore may affect the internal behavior
of Emacs. Emacs uses several such variables, e.g., EMACSLOADPATH. See
Section 16.3 [Library Search], page 287. On some platforms some environment
variables (e.g., PATH, POSIXLY_CORRECT, SHELL, TMPDIR) need to have
properly-configured values in order to get standard behavior for any utility
Emacs might invoke. Even seemingly-benign variables like TZ may have
security implications. See Section 41.3 [System Environment], page 1163.
Emacs has customization and other variables with similar considerations. For
example, if the variable shell-file-name specifies a shell with nonstandard
behavior, an Emacs-based application may misbehave.
Installation
When Emacs is installed, if the installation directory hierarchy can be modified
by untrusted users, the application cannot be trusted. This applies also to the
directory hierarchies of the programs that Emacs uses, and of the files that
Emacs reads and writes.
Network access
Emacs often accesses the network, and you may want to configure it to avoid
network accesses that it would normally do. For example, unless you set
tramp-mode to nil, file names using a certain syntax are interpreted as being
network files, and are retrieved across the network. See The Tramp Manual.
Race conditions
Emacs applications have the same sort of race-condition issues that other ap-
plications do. For example, even when (file-readable-p "foo.txt") returns
t, it could be that foo.txt is unreadable because some other program changed
the file’s permissions between the call to file-readable-p and now. See
Section 26.6.1 [Testing Accessibility], page 575.
Resource limits
When Emacs exhausts memory or other operating system resources, its behav-
ior can be less reliable, in that computations that ordinarily run to completion
may abort back to the top level. This may cause Emacs to neglect operations
that it normally would have done.
1199
call this the package’s content directory. It is where Emacs puts the package’s contents (the
single Lisp file for a simple package, or the files extracted from a multi-file package).
Emacs then searches every Lisp file in the content directory for autoload magic comments
(see Section 16.5 [Autoload], page 290). 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 24.2.2 [Auto Major Mode],
page 497). 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-activate-all
to make installed packages available to the current session. This is done after loading the
early init file, but before loading the regular init file (see Section 41.1.1 [Startup Sum-
mary], page 1153). Packages are not automatically made available if the user option
package-enable-at-startup is set to nil in the early init file.
package-activate-all [Function]
This function makes the packages available to the current session. The user option
package-load-list specifies which packages to make available; by default, all in-
stalled packages are made available. See Section “Package Installation” in The GNU
Emacs Manual.
In most cases, you should not need to call package-activate-all, as this is done
automatically during startup. Simply make sure to put any code that should run
before package-activate-all in the early init file, and any code that should run
after it in the primary init file (see Section “Init File” in The GNU Emacs Manual).
...
;;; 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 1238, 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 42.1 [Packaging Basics], page 1199. In the above example, a magic comment
autoloads superfrobnicator-mode.
See Section 42.4 [Package Archives], page 1202, for an explanation of how to add a
single-file package to a package archive.
is the version number. Its contents, once extracted, must all appear in a directory named
name-version, the content directory (see Section 42.1 [Packaging Basics], page 1199). Files
may also extract into subdirectories of the content directory.
One of the files in the content directory must be named name-pkg.el. It must contain
a single Lisp form, consisting of a call to the function define-package, described below.
This defines the package’s attributes: version, brief description, and requirements.
For example, if we distribute version 1.3 of the superfrobnicator as a multi-file
package, the tar file would be superfrobnicator-1.3.tar. Its contents would
extract into the directory superfrobnicator-1.3, and one of these would be the file
superfrobnicator-pkg.el.
If the content directory contains a file named README, this file is used as the long de-
scription (overriding any ‘;;; Commentary:’ section).
If the content directory contains a file named dir, this is assumed to be an Info directory
file made with install-info. See Section “Invoking install-info” in Texinfo. The relevant
Info files should also be present in the content directory. In this case, Emacs will automat-
ically add the content directory to Info-directory-list when the package is activated.
Do not include any .elc files in the package. Those are created when the package is
installed. Note that there is no way to control the order in which files are byte-compiled.
Do not include any file named name-autoloads.el. This file is reserved for the pack-
age’s autoload definitions (see Section 42.1 [Packaging Basics], page 1199). It is created
automatically when the package is installed, by searching all the Lisp files in the package
for autoload magic comments.
If the multi-file package contains auxiliary data files (such as images), the package’s Lisp
code can refer to these files via the variable load-file-name (see Chapter 16 [Loading],
page 284). Here is an example:
(defconst superfrobnicator-base (file-name-directory load-file-name))
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; See Section 42.5 [Archive Web Server], page 1204.
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 pack-
age 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 https://
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.
Chapter 42: Preparing Lisp code for distribution 1204
• The optional count argument of the directory-files function has been removed.
Extracting the first n members from the full list is trivial, so this is a significant
simplification for an insignificant cost.
• Functions that create sub-processes and network connections no longer accept the
:coding argument; use set-process-coding-system or bind coding-system-for-
read/write instead: again, a significant reduction in Emacs complexity for little or no
cost.
• We deleted from the macros define-derived-mode and define-minor-mode the code
which allowed using the :interactive argument. The possibility of marking a mode
non-interactive makes very little sense,
• The possibility of having links to man pages in doc strings has been removed. Use
plain text instead, if you need such references.
• Temporary buffers are no longer exempt from running any buffer-related hooks. Pro-
grams that don’t want such hooks in some buffer can always disable it locally, whereas
making that simpler complicates Emacs for no good reason.
• Several features that complicated the byte compiler have been removed:
− The checks for missing declarations of dynamic variables. This will continue mak-
ing less and less sense as we move away of lexical-binding support.
− The ability of compiling symlinked *.el files, which is really gross: copy the files
instead.
− The warnings about too-wide doc strings—that is just a nuisance, as the program-
mers should be trusted to know what they are doing.
• We deleted several features of the pcase macro, in accordance with our general plan
to remove pcase from Emacs:
− The cl-type pattern.
− the pcase-setq macro.
− The pcase-compile-patterns function.
• Some of the keywords used in Edebug specification lists were deemed to be of little use,
and were therefore removed: &interpose, &error, and &name. The long-term plane
is for Emacs to drop Edebug entirely, leaving only the trusted Lisp debugger, and we
continue working according to that plan.
• The function object-intervals was dropped, as a Lisp program can easily collect the
intervals of a buffer or a string by iterating through them one by one.
• We decided that the require-theme function is an unnecessary complication, so we
deleted it. Lisp programs can easily search along custom-theme-load-path instead.
• The convenience functions length<, length>, and length= were removed, as using
length followed by a comparison should be good enough for everyone, especially con-
sidering that the typical length of a list keeps going down as you move back through
time.
• The variable current-minibuffer-command is no longer available, as we found little
justification for keeping it.
• As part of the ongoing quest for simplicity, many other functions and variables have
been eliminated. Other functions and variables, that were declared obsolete since
Appendix A: Emacs 27 Antinews 1207
Emacs 23, have been added back, in preparation for releasing Emacs 23 in some distant
past.
1208
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 1210
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 1211
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 1212
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 1213
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 1217
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 1219
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 1220
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 1221
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 1222
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 1223
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 1224
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 1225
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 1226
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 pro-
prietary 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.
1227
If one prefix is insufficient, your package can use two or three alternative common
prefixes, so long as they make sense.
• We recommend enabling lexical-binding in new code, and converting existing Emacs
Lisp code to enable lexical-binding if it doesn’t already. See Section 12.10.4 [Using
Lexical Binding], page 199.
• Put a call to provide at the end of each separate Lisp file. See Section 16.7 [Named
Features], page 294.
• 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 294.
• 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 257.
• 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 library is deprecated and will be removed in a future version of
Emacs.
• When defining a major mode, please follow the major mode conventions. See
Section 24.2.1 [Major Mode Conventions], page 494.
• When defining a minor mode, please follow the minor mode conventions. See
Section 24.3.1 [Minor Mode Conventions], page 510.
• 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. We recommend to avoid using this -p suffix in boolean variable
names, unless the variable is bound to a predicate function; instead, use a -flag suffix
or names like is-foo.
• 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 24.1 [Hooks],
page 490.
• Using unload-feature will undo the changes usually done by loading a feature (like
adding functions to hooks). However, if loading feature does something unusual and
more complex, you can define a function named feature-unload-function, and make
Appendix D: Tips and Conventions 1229
it undo any such special changes. unload-feature will then automatically run this
function if it exists. See Section 16.9 [Unloading], page 298.
• 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 240).
• Avoid using eval-after-load and with-eval-after-load in libraries and packages
(see Section 16.10 [Hooks for Loading], page 299). 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 34.1
[Text Representations], page 900). 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 1238.
Appendix D: Tips and Conventions 1230
• 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 32.7 [The Mark],
page 815.
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 40.4 [The Echo Area], page 1039.
• 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 175.
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
or other punctuation.
It is occasionally useful to tell the user where an error originated, even if debug-on-
error is nil. In such cases, a lower-case Lisp symbol can be prepended to the error
message. For example, the error message “Invalid input” could be extended to say
“some-function: Invalid input”.
• 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))
...)
Appendix D: Tips and Conventions 1232
making a function inline reduces the flexibility of changing the program, don’t do it
unless it gives a noticeable speedup in something slow enough that users care about
the speed. See Section 13.13 [Inline Functions], page 248.
sometimes make a documentation string much more readable by adjusting its line
breaks with care. Use blank lines between sections if the documentation string is long.
• The first line of the documentation string should consist of one or two complete sen-
tences that stand on their own as a summary. M-x apropos displays just the first line,
and if that line’s contents don’t stand on their own, the result looks bad. In particular,
start the first line with a capital letter and end it with a period.
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!
Appendix D: Tips and Conventions 1235
To link to a customization group, write the single-quoted name of the group, preceded
by ‘customization group’ (the first character in each word is case-insensitive). For
example,
See the customization group `whitespace' for details.
Finally, to create a hyperlink to URLs, write the single-quoted URL, preceded by ‘URL’.
For example,
The GNU project wesite 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 25.3 [Keys
in Documentation], page 554.
• In documentation strings for a major mode, you will want to refer to the key bindings of
that mode’s local map, rather than global ones. Therefore, use the construct ‘\\<...>’
once in the documentation string to specify which key map to use. Do this before the
first use of ‘\\[...]’. The text inside the ‘\\<...>’ should be the name of the variable
containing the local keymap for the major mode.
Each use of ‘\\[...]’ slows the display of the documentation string by a tiny amount.
If you use a lot of them, these tiny slowdowns will add up, and might become tangible,
especially on slow systems. So our recommendation is not to over-use them; e.g., try
to avoid using more than one reference to the same command in the same doc string.
• 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.
• 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.
• Try to avoid using abbreviations such as “e.g.” (for “for example”), “i.e.” (for “that
is”), “no.” (for “number”), “cf.” (for “compare”/“see also”) and “w.r.t.” (for “with
respect to”) as much as possible. It is almost always clearer and easier to read the
expanded version.2
2
We do use these occasionally, but try not to overdo it.
Appendix D: Tips and Conventions 1237
‘;;’ 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 (or more) semicolons, ‘;;;’, should start at the
left margin. We use them for comments that should be considered a heading
Appendix D: Tips and Conventions 1238
‘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 header, the person(s) in the Author header is/are pre-
sumed to be the maintainer(s). Some files in Emacs use ‘emacs-devel@gnu.org’
for the maintainer, which means the 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 1240
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.
‘URL’
‘Homepage’
These lines state the website 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 42.1 [Packaging Basics], page 1199.
‘Package-Requires’
If this exists, it names packages on which the current package depends for
proper operation. See Section 42.1 [Packaging Basics], page 1199. 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 parsed 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.
Appendix D: Tips and Conventions 1241
The dumped emacs executable (also called a pure Emacs) is the one which is installed.
If the portable dumper was used to build Emacs, the emacs executable is actually an exact
copy of temacs, and the corresponding emacs.pdmp file is installed as well. The variable
preloaded-file-list stores a list of the preloaded Lisp files recorded in the dump file or
in the dumped Emacs executable. If you port Emacs to a new operating system, and are
not able to implement dumping of any kind, then Emacs must load loadup.el each time
it starts.
By default the dumped emacs executable records details such as the build time and host
name. Use the --disable-build-details option of configure to suppress these details,
so that building and installing Emacs twice from the same sources is more likely to result
in identical copies of Emacs.
You can specify additional files to preload by writing a library named site-load.el
that loads them. You may need to rebuild Emacs with an added definition
#define SITELOAD_PURESIZE_EXTRA n
to make n added bytes of pure space to hold the additional files; see src/puresize.h. (Try
adding increments of 20000 until it is big enough.) However, the advantage of preloading
additional files decreases as machines get faster. On modern machines, it is usually not
advisable.
After loadup.el reads site-load.el, it finds the documentation strings for primitive
and preloaded functions (and variables) in the file etc/DOC where they are stored, by calling
Snarf-documentation (see [Accessing Documentation], page 554).
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 41.1.1 [Startup Summary], page 1153. 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 287. 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
Appendix E: GNU Emacs Internals 1244
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 41.1.1
[Startup Summary], page 1153).
dump-emacs-portable to-file &optional track-referrers [Function]
This function dumps the current state of Emacs into a dump file to-file, using the
pdump method. Normally, the dump file is called emacs-name.dmp, where emacs-name
is the name of the Emacs executable file. The optional argument track-referrers, if
non-nil, causes the portable dumper to keep additional information to help track
down the provenance of object types that are not yet supported by the pdump method.
Although the portable dumper code can run on many platforms, the dump files that
it produces are not portable—they can be loaded only by the Emacs executable that
dumped them.
If you want to use this function in an Emacs that was already dumped, you must run
Emacs with the ‘-batch’ option.
dump-emacs to-file from-file [Function]
This function dumps the current state of Emacs into an executable file to-file, using
the unexec method. It takes symbols from from-file (this is normally the executable
file temacs).
This function cannot be used in an Emacs that was already dumped. This function
is deprecated, and by default Emacs is built without unexec support so this function
is not available.
pdumper-stats [Function]
If the current Emacs session restored its state from a dump file, this function returns
information about the dump file and the time it took to restore the Emacs state. The
value is an alist ((dumped-with-pdumper . t) (load-time . time) (dump-file-name . file)),
where file is the name of the dump file, and time is the time in seconds it took to
restore the state from the dump file. If the current session was not restored from a
dump file, the value is nil.
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 machine 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. If Emacs will be dumped using the pdump method (see Section E.1
[Building Emacs], page 1242), the pure-space overflow is of no special importance (it just
means some of the preloaded stuff cannot be shared with other Emacs jobs). However, if
Emacs will be dumped using the now obsolete unexec method, the resulting image will
work, but garbage collection (see Section E.3 [Garbage Collection], page 1245) 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 it was dumped using unexec. If this
happens, you should increase the compilation parameter SYSTEM_PURESIZE_EXTRA in the
file src/puresize.h and rebuild Emacs.
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.
are allocated in individual blocks, one per object; small strings are packed into blocks of 8k
bytes, and small vectors are packed into blocks of 4k bytes).
Beyond the basic vector, a lot of objects like markers, overlays and buffers 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, in essence, 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, but this calculation is done “conservatively”, so
it may slightly overestimate how many objects that are 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. (But since the marking was
done “conservatively”, not all unused objects are guaranteed to be garbage-collected by any
one sweep.)
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
Appendix E: GNU Emacs Internals 1247
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)
(strings string-size used-strings free-strings)
(string-bytes byte-size used-bytes)
(vectors vector-size used-vectors)
(vector-slots slot-size used-slots free-slots)
(floats float-size used-floats free-floats)
(intervals interval-size used-intervals free-intervals)
(buffers buffer-size used-buffers)
(heap unit-size total-size free-size))
Here is an example:
(garbage-collect)
⇒ ((conses 16 49126 8058) (symbols 48 14607 0)
(strings 32 2942 2607)
(string-bytes 1 78607) (vectors 16 7247)
(vector-slots 8 341609 29474) (floats 8 71 102)
(intervals 56 27 26) (buffers 944 8)
(heap 1024 11715 2678))
Below is a table explaining each element. Note that last heap entry is optional and
present only if an underlying malloc implementation provides mallinfo function.
cons-size Internal size of a cons cell, i.e., sizeof (struct Lisp_Cons).
used-conses
The number of cons cells in use.
free-conses
The number of cons cells for which space has been obtained from the
operating system, but that are not currently being used.
symbol-size
Internal size of a symbol, i.e., sizeof (struct Lisp_Symbol).
used-symbols
The number of symbols in use.
free-symbols
The number of symbols for which space has been obtained from the op-
erating system, but that are not currently being used.
string-size Internal size of a string header, i.e., sizeof (struct Lisp_String).
used-strings
The number of string headers in use.
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).
Appendix E: GNU Emacs Internals 1248
memory-limit [Function]
This function returns an estimate of the total amount of bytes of virtual memory that
Emacs is currently using, divided by 1024. 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.
Appendix E: GNU Emacs Internals 1250
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.
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.
memory-report [Function]
It can sometimes be useful to see where Emacs is using memory (in various vari-
ables, buffers, and caches). This command will open a new buffer (called ‘"*Memory
Report*"’) that will give an overview, in addition to listing the “largest” buffers and
variables.
All the data here is approximate, because there’s really no consistent way to compute
the size of a variable. For instance, two variables may share parts of a data structure,
and this will be counted twice, but this command may still give a useful high-level
overview of which parts of Emacs are using memory.
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.
This includes vector-like objects such as markers and overlays, plus certain objects
not visible to users.
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.
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)
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 22.2.1 [Using Interactive],
page 402). 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-
Appendix E: GNU Emacs Internals 1253
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.
Some primitives have multiple definitions, one per platform (e.g., x-create-
frame). In such cases, rather than writing the same documentation string in
each definition, only one definition has the actual documentation. The others
have placeholders beginning with ‘SKIP’, which are ignored by the function that
parses the DOC file.
All the usual rules for documentation strings in Lisp code (see Section D.6
[Documentation Tips], page 1233) 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:
DEFUN ("bar", Fbar, Sbar, 0, UNEVALLED, 0
doc: /* ... */
attributes: attr1 attr2 ...)
You can specify more than a single attribute, one after the other. Currently,
only the following attributes are recognized:
noreturn Declares the C function as one that never returns. This
corresponds to the C11 keyword _Noreturn and to
__attribute__ ((__noreturn__)) attribute of GCC (see Section
“Function Attributes” in Using the GNU Compiler Collection).
const Declares that the function does not examine any values except its
arguments, and has no effects except the return value. This corre-
sponds to __attribute__ ((__const__)) attribute of GCC.
noinline This corresponds to __attribute__ ((__noinline__)) attribute
of GCC, which prevents the function from being considered for
inlining. This might be needed, e.g., to countermand effects of
link-time optimizations on stack-based variables.
After the call to the DEFUN macro, you must write the argument list for the C function,
including the types for the arguments. If the primitive accepts a fixed maximum number
of Lisp arguments, there must be one C argument for each Lisp argument, and each ar-
gument must be of type Lisp_Object. (Various macros and functions for creating values
of type Lisp_Object are declared in the file lisp.h.) If the primitive is a special form, it
must accept a Lisp list containing its unevaluated Lisp arguments as a single argument of
type Lisp_Object. If the primitive has no upper limit on the number of evaluated Lisp
arguments, it must have exactly two C arguments: the first is the number of Lisp argu-
ments, and the second is the address of a block containing their values. These have types
ptrdiff_t and Lisp_Object *, respectively. Since Lisp_Object can hold any Lisp object
of any data type, you can determine the actual data type only at run time; so if you want
Appendix E: GNU Emacs Internals 1254
a primitive to accept only a certain type of argument, you must check the type explicitly
using a suitable predicate (see Section 2.7 [Type Predicates], page 30).
Within the function For itself, the local variable args refers to objects controlled by
Emacs’s stack-marking garbage collector. Although the garbage collector does not reclaim
objects reachable from C Lisp_Object stack variables, it may move some of the components
of an object, such as the contents of a string or the text of a buffer. Therefore, functions
that access these components must take care to refetch their addresses after performing Lisp
evaluation. This means that instead of keeping C pointers to string contents or buffer text,
the code should keep the buffer or string position, and recompute the C pointer from the
position after performing Lisp evaluation. Lisp evaluation can occur via calls to eval_sub
or Feval, either directly or indirectly.
Note the call to maybe_quit inside the loop: this function checks whether the user
pressed C-g, and if so, aborts the processing. You should do that in any loop that can
potentially require a large number of iterations; in this case, the list of arguments could be
very long. This increases Emacs responsiveness and improves user experience.
You must not use C initializers for static or global variables unless the variables are never
written once Emacs is dumped. These variables with initializers are allocated in an area
of memory that becomes read-only (on certain operating systems) as a result of dumping
Emacs. See Section E.2 [Pure Storage], page 1244.
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.
These macros all expect three arguments:
lname The name of the variable to be used by Lisp programs.
vname The name of the variable in the C sources.
doc The documentation for the variable, as a C comment. See Section 25.1 [Docu-
mentation Basics], page 551, for more details.
By convention, when defining variables of a “native” type (int and bool), the name of
the C variable is the name of the Lisp variable with - replaced by _. When the variable has
type Lisp_Object, the convention is to also prefix the C variable name with V. i.e.
DEFVAR_INT ("my-int-variable", my_int_variable,
Appendix E: GNU Emacs Internals 1255
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 1256
...
...
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 136).
Once your module is written, compile it to produce a shared library, according to the
conventions of the underlying platform. Then place the shared library in a directory men-
tioned in load-path (see Section 16.3 [Library Search], page 287), 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 22.11 [Quitting],
page 443). (If needed, you can catch user quitting inside the initialization function,
see [should quit], page 1270.)
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 *runtime)
{
if (runtime->size < sizeof (*runtime))
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
Appendix E: GNU Emacs Internals 1258
(later) than the one which attempts to load it, i.e. the module might be
incompatible with the Emacs binary.
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 = runtime->get_environment (runtime);
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 = runtime->get_environment (runtime);
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.
emacs-module.h defines a preprocessor macro EMACS_MAJOR_VERSION. It
expands to an integer literal which is the latest major version of Emacs
supported by the header. See Section 1.4 [Version Info], page 6. Note
that the value of EMACS_MAJOR_VERSION is a compile-time constant and
does not represent the version of Emacs that is currently running and
has loaded your module. If you want your module to be compatible with
various versions of emacs-module.h as well as various versions of Emacs,
you can use conditional compilation based on EMACS_MAJOR_VERSION.
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.
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 1257), after verifying the API compatibility.
The argument docstring specifies the documentation string for the function. It should
be either an ASCII string, or a UTF-8 encoded non-ASCII string, or a NULL pointer;
in the latter case the function will have no documentation. The documentation string
can end with a line that specifies the advertised calling convention, see Section 13.2.4
[Function Documentation], page 226.
Since every module function must accept the pointer to the environment as its first
argument, the call to make_function could be made from any module function, but
you will normally want to do that from the module initialization function, so that all
the module functions are known to Emacs once the module is loaded.
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 1269)
whose pointer is also provided in the environment that module functions can access.
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 = runtime->get_environment (runtime);
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 227.
Module functions including the emacs_module_init function (see [module initialization
function], page 1257) may only interact with Emacs by calling environment functions from
some live emacs_env pointer while being called directly or indirectly from Emacs. In other
words, if a module function wants to call Lisp functions or Emacs primitives, convert emacs_
value objects to and from C datatypes (see Section E.8.3 [Module Values], page 1262), or
interact with Emacs in any other way, some call from Emacs to emacs_module_init or
to a module function must be in the call stack. Module functions may not interact with
Emacs while garbage collection is running; see Section E.3 [Garbage Collection], page 1245.
They may only interact with Emacs from Lisp interpreter threads (including the main
thread) created by Emacs; see Chapter 38 [Threads], page 982. The --module-assertions
command-line option can detect some violations of the above requirements. See Section
“Initial Options” in The GNU Emacs Manual.
Using the module API, it is possible to define more complex function and data types:
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 a macro module-macro based on it is with the following
simple Lisp wrapper:
Appendix E: GNU Emacs Internals 1261
function, that is, an object returned by make_function. fin can either be NULL to
clear arg’s function finalizer, or a pointer to a function to be called when the object
represented by arg is garbage-collected. At most one function finalizer can be set per
function; if arg already has a finalizer, it is replaced by fin.
bool extract_big_integer (emacs env *env, emacs value arg, int [Function]
*sign, ptrdiff t *count, emacs limb t *magnitude)
This function, which is available since Emacs 27, extracts the integer value of arg.
The value of arg must be an integer (fixnum or bignum). If sign is not NULL, it stores
the sign of arg (-1, 0, or +1) into *sign. The magnitude is stored into magnitude as
follows. If count and magnitude are both non-NULL, then magnitude must point to
an array of at least *count unsigned long elements. If magnitude is large enough to
Appendix E: GNU Emacs Internals 1263
hold the magnitude of arg, then this function writes the magnitude into the magnitude
array in little-endian form, stores the number of array elements written into *count,
and returns true. If magnitude is not large enough, it stores the required array size
into *count, signals an error, and returns false. If count is not NULL and magnitude
is NULL, then the function stores the required array size into *count and returns true.
Emacs guarantees that the maximum required value of *count never exceeds min
(PTRDIFF_MAX, SIZE_MAX) / sizeof (emacs_limb_t), so you can use malloc
(*count * sizeof *magnitude) to allocate the magnitude array without worrying
about integer overflow in the size calculation.
emacs_limb_t [Type alias]
This is an unsigned integer type, used as the element type for the magnitude arrays
for the big integer conversion functions. The type is guaranteed to have unique object
representations, i.e., no padding bits.
EMACS_LIMB_MAX [Macro]
This macro expands to a constant expression specifying the maximum possible value
for an emacs_limb_t object. The expression is suitable for use in #if.
double extract_float (emacs env *env, emacs value arg) [Function]
This function returns the value of a Lisp float specified by arg, as a C double value.
struct timespec extract_time (emacs env *env, emacs value arg) [Function]
This function, which is available since Emacs 27, interprets arg as an Emacs Lisp
time value and returns the corresponding struct timespec. See Section 41.5 [Time
of Day], page 1168. struct timespec represents a timestamp with nanosecond pre-
cision. It has the following members:
time_t tv_sec
Whole number of seconds.
long tv_nsec
Fractional seconds as a number of nanoseconds. For timestamps returned
by extract_time, this is always nonnegative and less than one billion.
(Although POSIX requires the type of tv_nsec to be long, the type is
long long on some nonstandard platforms.)
See Section “Elapsed Time” in libc.
If time has higher precision than nanoseconds, then this function truncates it to
nanosecond precision towards negative infinity. This function signals an error if time
(truncated to nanoseconds) cannot be represented by struct timespec. For example,
if time_t is a 32-bit integer type, then a time value of ten billion seconds would signal
an error, but a time value of 600 picoseconds would get truncated to zero.
If you need to deal with time values that are not representable by struct timespec,
or if you want higher precision, call the Lisp function encode-time and work with its
return value. See Section 41.7 [Time Conversion], page 1170.
bool copy_string_contents (emacs env *env, emacs value arg, [Function]
char *buf, ptrdiff t *len)
This function stores the UTF-8 encoded text of a Lisp string specified by arg in the
array of char pointed by buf, which should have enough space to hold at least *len
Appendix E: GNU Emacs Internals 1264
bytes, including the terminating null byte. The argument len must not be a NULL
pointer, and, when the function is called, it should point to a value that specifies the
size of buf in bytes.
If the buffer size specified by *len is large enough to hold the string’s text, the function
stores in *len the actual number of bytes copied to buf, including the terminating null
byte, and returns true. If the buffer is too small, the function raises the args-out-
of-range error condition, stores the required number of bytes in *len, and returns
false. See Section E.8.5 [Module Nonlocal], page 1270, for how to handle pending
error conditions.
The argument buf can be a NULL pointer, in which case the function stores in *len
the number of bytes required for storing the contents of arg, and returns true. This
is how you can determine the size of buf needed to store a particular string: first
call copy_string_contents with NULL as buf, then allocate enough memory to hold
the number of bytes stored by the function in *len, and call the function again with
non-NULL buf to actually perform the text copying.
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 following example uses the GNU Multiprecision Library (GMP) to calculate the
next probable prime after a given integer. See gmp, for a general overview of GMP, and see
Section “Integer Import and Export” in gmp for how to convert the magnitude array to and
from GMP mpz_t values.
#include <emacs-module.h>
int plugin_is_GPL_compatible;
#include <assert.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
static void
memory_full (emacs_env *env)
{
static const char message[] = "Memory exhausted";
emacs_value data = env->make_string (env, message,
strlen (message));
env->non_local_exit_signal
(env, env->intern (env, "error"),
env->funcall (env, env->intern (env, "list"), 1, &data));
}
enum
{
order = -1, endian = 0, nails = 0,
limb_size = sizeof (emacs_limb_t),
max_nlimbs = ((SIZE_MAX < PTRDIFF_MAX ? SIZE_MAX : PTRDIFF_MAX)
/ limb_size)
};
static bool
extract_big_integer (emacs_env *env, emacs_value arg, mpz_t result)
{
ptrdiff_t nlimbs;
bool ok = env->extract_big_integer (env, arg, NULL, &nlimbs, NULL);
if (!ok)
return false;
assert (0 < nlimbs && nlimbs <= max_nlimbs);
emacs_limb_t *magnitude = malloc (nlimbs * limb_size);
if (magnitude == NULL)
{
memory_full (env);
Appendix E: GNU Emacs Internals 1266
return false;
}
int sign;
ok = env->extract_big_integer (env, arg, &sign, &nlimbs, magnitude);
assert (ok);
mpz_import (result, nlimbs, order, limb_size, endian, nails, magnitude);
free (magnitude);
if (sign < 0)
mpz_neg (result, result);
return true;
}
static emacs_value
make_big_integer (emacs_env *env, const mpz_t value)
{
size_t nbits = mpz_sizeinbase (value, 2);
int bitsperlimb = CHAR_BIT * limb_size - nails;
size_t nlimbs = nbits / bitsperlimb + (nbits % bitsperlimb != 0);
emacs_limb_t *magnitude
= nlimbs <= max_nlimbs ? malloc (nlimbs * limb_size) : NULL;
if (magnitude == NULL)
{
memory_full (env);
return NULL;
}
size_t written;
mpz_export (magnitude, &written, order, limb_size, endian, nails, value);
assert (written == nlimbs);
assert (nlimbs <= PTRDIFF_MAX);
emacs_value result = env->make_big_integer (env, mpz_sgn (value),
nlimbs, magnitude);
free (magnitude);
return result;
}
static emacs_value
next_prime (emacs_env *env, ptrdiff_t nargs, emacs_value *args,
void *data)
{
assert (nargs == 1);
mpz_t p;
mpz_init (p);
extract_big_integer (env, args[0], p);
mpz_nextprime (p, p);
emacs_value result = make_big_integer (env, p);
mpz_clear (p);
return result;
Appendix E: GNU Emacs Internals 1267
int
emacs_module_init (struct emacs_runtime *runtime)
{
emacs_env *env = runtime->get_environment (runtime);
emacs_value symbol = env->intern (env, "next-prime");
emacs_value func
= env->make_function (env, 1, 1, next_prime, NULL, NULL);
emacs_value args[] = {symbol, func};
env->funcall (env, env->intern (env, "defalias"), 2, args);
return 0;
}
emacs_value make_float (emacs env *env, double d) [Function]
This function takes a double argument d and returns the corresponding Emacs
floating-point value.
emacs_value make_time (emacs env *env, struct timespec time) [Function]
This function, which is available since Emacs 27, takes a struct timespec argument
time and returns the corresponding Emacs timestamp as a pair (ticks . hz). See
Section 41.5 [Time of Day], page 1168. The return value represents exactly the same
timestamp as time: all input values are representable, and there is never a loss of
precision. time.tv_sec and time.tv_nsec can be arbitrary values. In particular,
there’s no requirement that time be normalized. This means that time.tv_nsec can
be negative or larger than 999,999,999.
emacs_value make_string (emacs env *env, const char *str, [Function]
ptrdiff t len)
This function creates an Emacs string from C text string pointed by str whose length
in bytes, not including the terminating null byte, is len. The original string in str
can be either an ASCII string or a UTF-8 encoded non-ASCII string; it can include
embedded null bytes, and doesn’t have to end in a terminating null byte at str[len].
The function raises the overflow-error error condition if len is negative or exceeds
the maximum length of an Emacs string. If len is zero, then str can be NULL, otherwise
it must point to valid memory. For nonzero len, make_string returns unique mutable
string objects.
emacs_value make_unibyte_string (emacs env *env, const char [Function]
*str, ptrdiff t len)
This function is like make_string, but has no restrictions on the values of the bytes
in the C string, and can be used to pass binary data to Emacs in the form of a unibyte
string.
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 79), extract list
members with car and cdr (see Section 5.3 [List Elements], page 76), create vectors with
vector (see Section 6.5 [Vector Functions], page 114), etc. For these, use intern and
funcall, described in the next subsection, to call the corresponding Lisp functions.
Appendix E: GNU Emacs Internals 1268
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 arg, void *ptr) [Function]
This function sets the C pointer embedded in the user-ptr object represented by
arg to ptr.
Note that the emacs_finalizer type works for both user pointer an module function
finalizers. See [Module Function Finalizers], page 1261.
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 22.11
[Quitting], page 443). The following function, which is available since Emacs 26.1, is pro-
vided for that purpose.
To process input events in addition to checking whether the user wants to quit, use the
following function, which is available since Emacs 27.1.
When some Lisp code called by a module function signals an error or throws, the nonlocal
exit is trapped, and the pending exit and its associated data are stored in the environment.
Whenever a nonlocal exit is pending in the environment, any module API function called
with a pointer to that environment will return immediately without any processing (the
functions non_local_exit_check, non_local_exit_get, and non_local_exit_clear are
exceptions from this rule). If your module function then does nothing and returns to
Emacs, a pending nonlocal exit will cause Emacs to act on it: signal an error or throw to
the corresponding catch.
So the simplest “handling” of nonlocal exits in module functions is to do nothing special
and let the rest of your code to run as if nothing happened. However, this can cause two
classes of problems:
− Your module function might use uninitialized or undefined values, since API functions
return immediately without producing the expected results.
− Your module might leak resources, because it might not have the opportunity to release
them.
Therefore, we recommend that your module functions check for nonlocal exit conditions
and recover from them, using the functions described below.
enum emacs_funcall_exit non_local_exit_check (emacs env [Function]
*env)
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.
enum emacs_funcall_exit non_local_exit_get (emacs env *env, [Function]
emacs value *symbol, emacs value *data)
This function returns the kind of nonlocal exit condition stored in env, like non_
local_exit_check does, but it also returns the full information about the nonlocal
exit, if any. If the return value is emacs_funcall_exit_signal, the function stores
the error symbol in *symbol and the error data in *data (see Section 11.7.3.1 [Sig-
naling Errors], page 175). If the return value is emacs_funcall_exit_throw, the
function stores the catch tag symbol in *symbol and the throw value in *data. The
function doesn’t store anything in memory pointed by these arguments when the
return value is emacs_funcall_exit_return.
You should check nonlocal exit conditions where it matters: before you allocated some
resource or after you allocated a resource that might need freeing, or where a failure means
further processing is impossible or infeasible.
Once your module function detected that a nonlocal exit is pending, it can either return
to Emacs (after performing the necessary local cleanup), or it can attempt to recover from
the nonlocal exit. The following API functions will help with these tasks.
Appendix E: GNU Emacs Internals 1272
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.
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 Lisp_Vectorlike. Vector subtypes are enu-
merated by enum pvec_type, and nearly all complex objects like windows, buffers, frames,
and processes fall into this category.
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.
beg_unchanged
end_unchanged
The number of characters at the start and end of the text that are known to
be unchanged since the last complete redisplay.
unchanged_modified
overlay_unchanged_modified
The values of modiff and overlay_modiff, respectively, after the last complete
redisplay. If their current values match modiff or overlay_modiff, that means
beg_unchanged and end_unchanged contain no useful information.
markers The markers that refer to this buffer. This is actually a single marker, and
successive elements in its marker chain (a linked list) are the other markers
referring to this buffer text.
intervals
The interval tree which records the text properties of this buffer.
Some of the fields of struct buffer are:
header A header of type union vectorlike_header is common to all vectorlike objects.
own_text A struct buffer_text structure that ordinarily holds the buffer contents. In
indirect buffers, this field is not used.
text A pointer to the buffer_text structure for this buffer. In an ordinary buffer,
this is the own_text field above. In an indirect buffer, this is the own_text field
of the base buffer.
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.)
Appendix E: GNU Emacs Internals 1275
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 28.5 [Buffer
Modification], page 632.
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 31.4
[Narrowing], page 808.
prevent_redisplay_optimizations_p
This flag indicates that redisplay optimizations should not be used to display
this buffer.
inhibit_buffer_hooks
This flag indicates that the buffer should not run the hooks kill-buffer-hook,
kill-buffer-query-functions (see Section 28.10 [Killing Buffers], page 639),
and buffer-list-update-hook (see Section 28.8 [Buffer List], page 636). It
is set at buffer creation (see Section 28.9 [Creating Buffers], page 638), and
avoids slowing down internal or temporary buffers, such as those created by
with-temp-buffer (see [Current Buffer], page 628).
overlay_center
This field holds the current overlay center position. See Section 40.9.1 [Manag-
ing Overlays], page 1056.
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.
See Section 40.9.1 [Managing Overlays], page 1056. overlays_before is sorted
in order of decreasing end position, and overlays_after is sorted in order of
increasing beginning position.
name A Lisp string that names the buffer. It is guaranteed to be unique. See
Section 28.3 [Buffer Names], page 629. This and the following fields have their
names in the C struct definition end in a _ to indicate that they should not be
accessed directly, but via the BVAR macro, like this:
Lisp_Object buf_name = BVAR (buffer, name);
save_length
The length of the file this buffer is visiting, when last read or saved. It can
have 2 special values: −1 means auto-saving was turned off in this buffer, and
−2 means don’t turn off auto-saving if buffer text shrinks a lot. This and other
fields concerned with saving are not kept in the buffer_text structure because
indirect buffers are never saved.
Appendix E: GNU Emacs Internals 1276
directory
The directory for expanding relative file names. This is the value of the buffer-
local variable default-directory (see Section 26.9.4 [File Name Expansion],
page 594).
filename The name of the file visited in this buffer, or nil. This is the value of the
buffer-local variable buffer-file-name (see Section 28.4 [Buffer File Name],
page 630).
undo_list
backed_up
auto_save_file_name
auto_save_file_format
read_only
file_format
file_truename
invisibility_spec
display_count
display_time
These fields store the values of Lisp variables that are automatically buffer-local
(see Section 12.11 [Buffer-Local Variables], page 201), whose corresponding vari-
able names have the additional prefix buffer- and have underscores replaced
with dashes. For instance, undo_list stores the value of buffer-undo-list.
mark The mark for the buffer. The mark is a marker, hence it is also included on the
list markers. See Section 32.7 [The Mark], page 815.
local_var_alist
The association list describing the buffer-local variable bindings of this buffer,
not including the built-in buffer-local bindings that have special slots in the
buffer object. (Those slots are omitted from this table.) See Section 12.11
[Buffer-Local Variables], page 201.
major_mode
Symbol naming the major mode of this buffer, e.g., lisp-mode.
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 23 [Keymaps],
page 451), abbrev table (see Section 37.1 [Abbrev Tables], page 975),
syntax table (see Chapter 36 [Syntax Tables], page 958), category table (see
Section 36.8 [Categories], page 972), and display table (see Section 40.22.2
[Display Tables], page 1141).
Appendix E: GNU Emacs Internals 1277
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.10 [Case
Tables], page 72.
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 1278
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 201), 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 win-
dow 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 the tab bar or a win-
dow 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 1280
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 40.26 [Bidirectional Display], page 1148) 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 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 1281
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 1282
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 29.23 [Horizontal Scrolling], page 719). 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 1283
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 intmax_t for representing values that might be any signed integer value. A
printf-family function can print such a value via a format like "%"PRIdMAX.
• 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.
1286
cl-assertion-failed
The message is ‘Assertion failed’. This happens when the cl-assert macro
fails a test. See Section “Assertions” in Common Lisp Extensions.
coding-system-error
The message is ‘Invalid coding system’. See Section 34.10.3 [Lisp and Coding
Systems], page 916.
cyclic-function-indirection
The message is ‘Symbol's chain of function indirections contains a
loop’. See Section 10.1.4 [Function Indirection], page 143.
cyclic-variable-indirection
The message is ‘Symbol's chain of variable indirections contains a
loop’. See Section 12.15 [Variable Aliases], page 215.
dbus-error
The message is ‘D-Bus error’. See Section “Errors and Events” in D-Bus inte-
gration in Emacs.
end-of-buffer
The message is ‘End of buffer’. See Section 31.2.1 [Character Motion],
page 798.
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 20.3 [Input Functions], page 355.
file-already-exists
This is a subcategory of file-error. See Section 26.4 [Writing to Files],
page 571.
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 26.7 [Changing
Files], page 584.
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 26 [Files],
page 564.
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 26.7 [Changing Files], page 584.
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 284.
Appendix F: Standard Errors 1288
file-locked
This is a subcategory of file-error. See Section 26.5 [File Locks], page 573.
file-supersession
This is a subcategory of file-error. See Section 28.6 [Modification Time],
page 633.
file-notify-error
This is a subcategory of file-error. It happens, when a file could not be
watched for changes. See Section 41.20 [File Notifications], page 1193.
remote-file-error
This is a subcategory of file-error, which results from problems in accessing a
remote file. See Section “Remote Files” in The GNU Emacs Manual. Often, this
error appears when timers, process filters, process sentinels or special events in
general try to access a remote file, and collide with another remote file operation.
In general it is a good idea to write a bug report. See Section “Bugs” in The
GNU Emacs Manual.
ftp-error
This is a subcategory of remote-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 143.
invalid-read-syntax
The message is usually ‘Invalid read syntax’. See Section 2.1 [Printed
Representation], page 8. This error can also be raised by commands like
eval-expression when there’s text following an expression. In that case, the
message is ‘Trailing garbage following expression’.
invalid-regexp
The message is ‘Invalid regexp’. See Section 35.3 [Regular Expressions],
page 933.
mark-inactive
The message is ‘The mark is not active now’. See Section 32.7 [The Mark],
page 815.
no-catch The message is ‘No catch for tag’. See Section 11.7.1 [Catch and Throw],
page 172.
range-error
The message is Arithmetic range error.
overflow-error
The message is ‘Arithmetic overflow error’. This is a subcategory of
range-error. This can happen with integers exceeding the integer-width
limit. See Section 3.1 [Integer Basics], page 37.
Appendix F: Standard Errors 1289
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 31.2.6 [List
Motion], page 805, and see Section 36.6 [Parsing Expressions], page 966.
search-failed
The message is ‘Search failed’. See Chapter 35 [Searching and Matching],
page 930.
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 184.
text-read-only
The message is ‘Text is read-only’. This is a subcategory of buffer-read-
only. See Section 33.19.4 [Special Properties], page 866.
undefined-color
The message is ‘Undefined color’. See Section 30.22 [Color Names], page 790.
user-error
The message is the empty string. See Section 11.7.3.1 [Signaling Errors],
page 175.
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 175, and see
Chapter 35 [Searching and Matching], page 930. 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 238.
void-variable
The message is ‘Symbol's value as variable is void’. See Section 12.7 [Ac-
cessing Variables], page 193.
wrong-number-of-arguments
The message is ‘Wrong number of arguments’. See Section 13.2.3 [Argument
List], page 224.
wrong-type-argument
The message is ‘Wrong type argument’. See Section 2.7 [Type Predicates],
page 30.
Appendix F: Standard Errors 1290
unknown-image-type
The message is ‘Cannot determine image type’. See Section 40.17 [Images],
page 1109.
inhibited-interaction
The message is ‘User interaction while inhibited’. This error is signalled
when inhibit-interaction is non-nil and a user interaction function (like
read-from-minibuffer) is called.
1291
input-decode-map
The keymap for translating keypad and function keys.
If there are none, then it contains an empty sparse keymap. See Section 23.14
[Translation Keymaps], page 470.
key-translation-map
A keymap for translating keys. This one overrides ordinary key bindings, unlike
local-function-key-map. See Section 23.14 [Translation Keymaps], page 470.
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 23.14
[Translation Keymaps], page 470.
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 23.17.5 [Menu Bar], page 482.
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 24.4 [Mode Line Format], page 515.
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.
narrow-map
A sparse keymap for subcommands of the prefix C-x n.
Appendix G: Standard Keymaps 1293
prog-mode-map
The keymap used by Prog mode.
See Section 24.2.5 [Basic Major Modes], page 502.
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 35.7 [Search and Replace], page 953.
search-map
A sparse keymap that provides global bindings for search-related commands.
special-mode-map
The keymap used by Special mode.
See Section 24.2.5 [Basic Major Modes], page 502.
tab-prefix-map
The global keymap used for the C-x t prefix key for tab-bar related commands.
See Section “Tab Bars” in The GNU Emacs Manual.
tab-bar-map
The keymap defining the contents of the tab bar.
See Section “Tab Bars” in The GNU Emacs Manual.
tool-bar-map
The keymap defining the contents of the tool bar.
See Section 23.17.6 [Tool Bar], page 483.
universal-argument-map
A sparse keymap used while processing C-u.
See Section 22.12 [Prefix Command Arguments], page 444.
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.
1294
after-save-hook
before-save-hook
write-contents-functions
write-file-functions
See Section 26.2 [Saving Buffers], page 568.
after-setting-font-hook
Hook run after a frame’s font changes.
auto-save-hook
See Section 27.2 [Auto-Saving], page 619.
before-hack-local-variables-hook
hack-local-variables-hook
See Section 12.12 [File Local Variables], page 208.
buffer-access-fontify-functions
See Section 33.19.7 [Lazy Properties], page 874.
buffer-list-update-hook
Hook run when the buffer list changes (see Section 28.8 [Buffer List], page 636).
buffer-quit-function
Function to call to quit the current buffer.
change-major-mode-hook
See Section 12.11.2 [Creating Buffer-Local], page 203.
comint-password-function
This abnormal hook permits a derived mode to supply a password for the
underlying command interpreter without prompting the user.
command-line-functions
See Section 41.1.4 [Command-Line Arguments], page 1159.
delayed-warnings-hook
The command loop runs this soon after post-command-hook (q.v.).
focus-in-hook
focus-out-hook
See Section 30.10 [Input Focus], page 774.
delete-frame-functions
after-delete-frame-functions
See Section 30.7 [Deleting Frames], page 772.
delete-terminal-functions
See Section 30.2 [Multiple Terminals], page 738.
pop-up-frame-function
split-window-preferred-function
See Section 29.13.4 [Choosing Window Options], page 687.
echo-area-clear-hook
See Section 40.4.4 [Echo Area Customization], page 1045.
Appendix H: Standard Hooks 1296
find-file-hook
find-file-not-found-functions
See Section 26.1.1 [Visiting Functions], page 564.
font-lock-extend-after-change-region-function
See Section 24.6.9.2 [Region to Refontify], page 540.
font-lock-extend-region-functions
See Section 24.6.9 [Multiline Font Lock], page 538.
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 24.6.4 [Other Font Lock Variables], page 534.
fontification-functions
See Section 40.12.7 [Automatic Face Assignment], page 1082.
frame-auto-hide-function
See Section 29.16 [Quitting Windows], page 701.
quit-window-hook
See Section 29.16 [Quitting Windows], page 701.
kill-buffer-hook
kill-buffer-query-functions
See Section 28.10 [Killing Buffers], page 639.
kill-emacs-hook
kill-emacs-query-functions
See Section 41.2.1 [Killing Emacs], page 1160.
menu-bar-update-hook
See Section 23.17.5 [Menu Bar], page 482.
minibuffer-setup-hook
minibuffer-exit-hook
See Section 21.15 [Minibuffer Misc], page 399.
mouse-leave-buffer-hook
Hook run when the user mouse-clicks in a window.
mouse-position-function
See Section 30.16 [Mouse Position], page 785.
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 22.12 [Prefix Command Arguments], page 444.
Appendix H: Standard Hooks 1297
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 40.2 [Forcing
Redisplay], page 1037.
post-command-hook
pre-command-hook
See Section 22.1 [Command Overview], page 401.
post-gc-hook
See Section E.3 [Garbage Collection], page 1245.
post-self-insert-hook
See Section 24.3.2 [Keymaps and Minor Modes], page 512.
suspend-hook
suspend-resume-hook
suspend-tty-functions
resume-tty-functions
See Section 41.2.2 [Suspending Emacs], page 1161.
syntax-begin-function
syntax-propertize-extend-region-functions
syntax-propertize-function
font-lock-syntactic-face-function
See Section 24.6.8 [Syntactic Font Lock], page 537. See Section 36.4 [Syntax
Properties], page 965.
temp-buffer-setup-hook
temp-buffer-show-function
temp-buffer-show-hook
See Section 40.8 [Temporary Displays], page 1053.
tty-setup-hook
See Section 41.1.3 [Terminal-Specific], page 1158.
window-configuration-change-hook
window-scroll-functions
window-size-change-functions
See Section 29.28 [Window Hooks], page 731.
1298
Index
" +
‘"’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
‘"’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 ‘+’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934
# ,
‘##’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 , (with backquote). . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
‘#$’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 ,@ (with backquote) . . . . . . . . . . . . . . . . . . . . . . . . . . 148
‘#'’ syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
‘#(’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
‘#:’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
–
‘#^’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
‘#@count’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 --disable-build-details
‘#n#’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 option to configure . . . . . . . . . . . . . . . . . . . . . . . 1243
‘#n=’ read syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 --enable-locallisppath option
to configure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1243
--temacs option, and dumping method . . . . . . 1242
$
‘$’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1038
‘$’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936
.
‘.’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
‘.’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 933
% .#, lock file names . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
.emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1156
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
‘%’ in format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
/
& / . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
/= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
‘&’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949 /dev/tty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030
&optional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
&rest. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
:
’ :deferred, JSONRPC keyword . . . . . . . . . . . . . . . 896
:notification-dispatcher . . . . . . . . . . . . . . . . . . . 893
‘'’ for quoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
:request-dispatcher . . . . . . . . . . . . . . . . . . . . . . . . 893
( ;
‘(’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939 ‘;’ for commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
‘(...)’ in lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
‘(?:’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939
(emacs_env . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1268 <
< . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
<= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
)
‘)’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939
=
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
*
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
‘*’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
>
‘*’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 933 > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
*scratch* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 >= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Index 1299
] 1
‘]’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934 1+ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
^
‘^’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
‘^’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
2
2C-mode-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
2D box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1071
‘
` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 3
‘ (list substitution) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
3D box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1071
@ A
‘@’ in interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 abbrev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
abbrev properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 980
abbrev table properties . . . . . . . . . . . . . . . . . . . . . . . 981
\ abbrev tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
‘\’ in character constant . . . . . . . . . . . . . . . . . . . . . . . 12 abbrev tables in modes . . . . . . . . . . . . . . . . . . . . . . . 495
‘\’ in display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1038 abbrev-all-caps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 979
‘\’ in printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 abbrev-expand-function . . . . . . . . . . . . . . . . . . . . . 979
‘\’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936 abbrev-expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
‘\’ in replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949 abbrev-file-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977
‘\’ in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 abbrev-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 980
‘\’ in symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 abbrev-insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
‘\'’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1291
\( in strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806 abbrev-minor-mode-table-alist . . . . . . . . . . . . . 980
‘\<’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-prefix-mark . . . . . . . . . . . . . . . . . . . . . . . . . . 978
‘\=’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 980
‘\>’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-start-location . . . . . . . . . . . . . . . . . . . . . . 979
‘\_<’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-start-location-buffer . . . . . . . . . . . . . . 979
‘\_>’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
‘\`’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-table-get . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981
‘\a’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abbrev-table-name-list . . . . . . . . . . . . . . . . . . . . . 976
‘\b’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abbrev-table-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
‘\b’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbrev-table-put . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981
‘\B’ in regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 abbreviate-file-name . . . . . . . . . . . . . . . . . . . . . . . 594
‘\e’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abbreviated file names . . . . . . . . . . . . . . . . . . . . . . . . 594
‘\f’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abbrevs, looking up and expanding . . . . . . . . . . . . 978
‘\n’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abbrevs-changed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977
‘\n’ in print. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 abnormal hook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
‘\n’ in replacement. . . . . . . . . . . . . . . . . . . . . . . . . . . . 949 abort-recursive-edit . . . . . . . . . . . . . . . . . . . . . . . 448
‘\r’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 aborting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
‘\s’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Index 1300
H Helper-help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
hack-connection-local-variables . . . . . . . . . . . 214 Helper-help-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
hack-connection-local-variables-apply . . . . 215 hex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
hack-dir-local-variables . . . . . . . . . . . . . . . . . . . 212 hidden buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
hack-dir-local-variables- history list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
non-file-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 history of commands . . . . . . . . . . . . . . . . . . . . . . . . . . 449
hack-local-variables . . . . . . . . . . . . . . . . . . . . . . . 209 history-add-new-input . . . . . . . . . . . . . . . . . . . . . . 372
hack-local-variables-hook. . . . . . . . . . . . . . . . . . 210 history-delete-duplicates. . . . . . . . . . . . . . . . . . 372
Hamming weight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 history-length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
handle Lisp errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 HOME environment variable . . . . . . . . . . . . . . . . . . . . 987
handle-focus-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776 hook variables, list of . . . . . . . . . . . . . . . . . . . . . . . . 1294
handle-shift-selection . . . . . . . . . . . . . . . . . . . . . 818 hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
handle-switch-frame . . . . . . . . . . . . . . . . . . . . . . . . 776 hooks for changing a character . . . . . . . . . . . . . . . . 870
handling errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 hooks for loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
hardening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196 hooks for motion of point . . . . . . . . . . . . . . . . . . . . . 871
hash code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 hooks for text changes . . . . . . . . . . . . . . . . . . . . . . . . 897
hash notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 hooks for window operations . . . . . . . . . . . . . . . . . . 731
hash table access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 horizontal combination . . . . . . . . . . . . . . . . . . . . . . . . 647
hash tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 horizontal position . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851
hash, cryptographic . . . . . . . . . . . . . . . . . . . . . . 885, 886 horizontal scrolling. . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
hash-table-count . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 horizontal-lineto . . . . . . . . . . . . . . . . . . . . . . . . . . 1120
hash-table-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 horizontal-scroll-bar . . . . . . . . . . . . . . . . . . . . . 1101
hash-table-rehash-size . . . . . . . . . . . . . . . . . . . . . 129 horizontal-scroll-bar, prefix key . . . . . . . . . . . 434
hash-table-rehash-threshold . . . . . . . . . . . . . . . 129 horizontal-scroll-bar-mode . . . . . . . . . . . . . . . 1102
hash-table-size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 horizontal-scroll-bars, a
hash-table-test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 frame parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
hash-table-weakness . . . . . . . . . . . . . . . . . . . . . . . . 129 horizontal-scroll-bars-available-p . . . . . . 1099
hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 how to visit files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
header comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1238 HTML DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889
header line (of a window) . . . . . . . . . . . . . . . . . . . . . 524 hyper characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
header-line, prefix key . . . . . . . . . . . . . . . . . . . . . . . 434 hyperlinks in documentation strings . . . . . . . . . . 1235
header-line-format . . . . . . . . . . . . . . . . . . . . . . . . . . 524
header-line-format, a window parameter . . . . 730
height of a line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1067 I
height of a window . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653 icon-left, a frame parameter . . . . . . . . . . . . . . . . 757
height spec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1068 icon-name, a frame parameter . . . . . . . . . . . . . . . . 765
height, a frame parameter . . . . . . . . . . . . . . . . . . . . 759 icon-title-format . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
help for major mode . . . . . . . . . . . . . . . . . . . . . . . . . . 500 icon-top, a frame parameter . . . . . . . . . . . . . . . . . 757
help functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 icon-type, a frame parameter . . . . . . . . . . . . . . . . 765
help-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560 iconified frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
help-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 iconify-child-frame . . . . . . . . . . . . . . . . . . . . . . . . 784
help-command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 iconify-frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
help-echo (button property) . . . . . . . . . . . . . . . . 1131 iconify-frame event . . . . . . . . . . . . . . . . . . . . . . . . . 424
help-echo (overlay property) . . . . . . . . . . . . . . . . 1061 identical-contents objects, and byte-compiler . . . 34
help-echo (text property) . . . . . . . . . . . . . . . . . . . . 867 identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
help-echo event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 idle timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1181
help-echo text, avoid idleness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1181
command-key substitution . . . . . . . . . . . . . . . . . . 867 IEEE floating point . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
help-echo, customization keyword . . . . . . . . . . . . 279 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
help-echo-inhibit-substitution ignore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
(text property) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867 ignore-error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
help-event-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 ignore-errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
help-form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 ignore-window-parameters . . . . . . . . . . . . . . . . . . . 729
help-key-binding (face) . . . . . . . . . . . . . . . . . . . . . . 555 ignored-local-variable-values . . . . . . . . . . . . . 210
help-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 ignored-local-variables . . . . . . . . . . . . . . . . . . . . 211
help-setup-xref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560 image animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1127
help-window-select . . . . . . . . . . . . . . . . . . . . . . . . . . 560 image cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1127
Helper-describe-bindings . . . . . . . . . . . . . . . . . . . 559 image descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1109
Index 1321
U unsafep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
UBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148 unsplittable, a frame parameter . . . . . . . . . . . . . 762
UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019 unused lexical variable . . . . . . . . . . . . . . . . . . . . . . . . 200
UID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167 unwind-protect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
umask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 unwinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
unassigned character codepoints . . . . . . . . . . . . . . . 906 up-list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
unbalanced parentheses . . . . . . . . . . . . . . . . . . . . . . . 349 upcase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
unbinding keys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 upcase-initials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
unbury-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638 upcase-region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
undecided coding system . . . . . . . . . . . . . . . . . . . . . 914 upcase-word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
undecided coding-system, when decoding . . . . . . 926 update-file-autoloads . . . . . . . . . . . . . . . . . . . . . . 291
undecided coding-system, when encoding . . . . . 925 upper case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
undecorated, a frame parameter . . . . . . . . . . . . . . 766 upper case key sequence . . . . . . . . . . . . . . . . . . . . . . 434
undefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 uptime of Emacs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1177
undefined in keymap . . . . . . . . . . . . . . . . . . . . . . . . . 464 use time of window . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
undefined key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 use-empty-active-region . . . . . . . . . . . . . . . . . . . . 819
underline-minimum-offset . . . . . . . . . . . . . . . . . . 1073 use-global-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
underlined text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1070 use-hard-newlines . . . . . . . . . . . . . . . . . . . . . . . . . . . 844
undo avoidance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880 use-local-map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
undo in temporary buffers . . . . . . . . . . . . . . . . . . . . 628 use-region-p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
undo-amalgamate-change-group . . . . . . . . . . . . . . 897 user errors, signaling . . . . . . . . . . . . . . . . . . . . . . . . . . 176
undo-ask-before-discard . . . . . . . . . . . . . . . . . . . . 841 user groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1168
undo-auto-amalgamate . . . . . . . . . . . . . . . . . . . . . . . 839 user identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
undo-auto-current-boundary-timer . . . . . . . . . 839 user options, how to define . . . . . . . . . . . . . . . . . . . . 267
undo-boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 838 user pointer object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
undo-in-progress . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839 user pointer, using in module functions . . . . . . . 1268
undo-limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840 user signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
undo-outer-limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841 user-defined error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
undo-strong-limit . . . . . . . . . . . . . . . . . . . . . . . . . . . 840 user-emacs-directory . . . . . . . . . . . . . . . . . . . . . . 1157
unexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1242, 1244 user-error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
unhandled-file-name-directory . . . . . . . . . . . . . 608 user-full-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
unibyte buffers, and bidi reordering . . . . . . . . . . 1148 user-init-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1157
unibyte text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 user-login-name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
unibyte-char-to-multibyte. . . . . . . . . . . . . . . . . . 903 user-mail-address . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
unibyte-string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902 user-position, a frame parameter . . . . . . . . . . . . 757
Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 user-ptr object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
unicode bidirectional algorithm . . . . . . . . . . . . . . 1148 user-ptrp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
unicode character escape . . . . . . . . . . . . . . . . . . . . . . . 12 user-real-login-name . . . . . . . . . . . . . . . . . . . . . . 1167
unicode general category . . . . . . . . . . . . . . . . . . . . . . 906 user-real-uid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
unicode, a charset . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910 user-size, a frame parameter . . . . . . . . . . . . . . . . 759
unicode-category-table . . . . . . . . . . . . . . . . . . . . . 909 user-uid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
unintern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 utf-8-emacs coding system . . . . . . . . . . . . . . . . . . . 914
uninterned symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
uninterned symbol, and generating Lisp code . . 133
union of sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 V
unique file names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 valid windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
universal-argument . . . . . . . . . . . . . . . . . . . . . . . . . . 446 validity of coding system . . . . . . . . . . . . . . . . . . . . . . 917
universal-argument-map . . . . . . . . . . . . . . . . . . . . 1293 value cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
unless . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 value of expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
unload-feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 value of function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
unload-feature-special-hooks . . . . . . . . . . . . . . 298 values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
unloading packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
unloading packages, preparing for . . . . . . . . . . . . 1228 variable aliases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
unlock-buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 variable definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
unmapped frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778 variable descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
unnumbered group . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939 variable limit error . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
unpacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1032 variable watchpoints . . . . . . . . . . . . . . . . . . . . . . . . . . 195
unread-command-events . . . . . . . . . . . . . . . . . . . . . . 440 variable with constant value . . . . . . . . . . . . . . . . . . . 184
Index 1347