Merge from trunk; up to 2014-02-23T23:41:17Z!lekktu@gmail.com.
[bpt/emacs.git] / doc / lispref / os.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2014 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node System Interface
7 @chapter Operating System Interface
8
9 This chapter is about starting and getting out of Emacs, access to
10 values in the operating system environment, and terminal input, output.
11
12 @xref{Building Emacs}, for related information. @xref{Display}, for
13 additional operating system status information pertaining to the
14 terminal and the screen.
15
16 @menu
17 * Starting Up:: Customizing Emacs startup processing.
18 * Getting Out:: How exiting works (permanent or temporary).
19 * System Environment:: Distinguish the name and kind of system.
20 * User Identification:: Finding the name and user id of the user.
21 * Time of Day:: Getting the current time.
22 * Time Conversion:: Converting a time from numeric form to
23 calendrical data and vice versa.
24 * Time Parsing:: Converting a time from numeric form to text
25 and vice versa.
26 * Processor Run Time:: Getting the run time used by Emacs.
27 * Time Calculations:: Adding, subtracting, comparing times, etc.
28 * Timers:: Setting a timer to call a function at a certain time.
29 * Idle Timers:: Setting a timer to call a function when Emacs has
30 been idle for a certain length of time.
31 * Terminal Input:: Accessing and recording terminal input.
32 * Terminal Output:: Controlling and recording terminal output.
33 * Sound Output:: Playing sounds on the computer's speaker.
34 * X11 Keysyms:: Operating on key symbols for X Windows.
35 * Batch Mode:: Running Emacs without terminal interaction.
36 * Session Management:: Saving and restoring state with X Session Management.
37 * Desktop Notifications:: Desktop notifications.
38 * File Notifications:: File notifications.
39 * Dynamic Libraries:: On-demand loading of support libraries.
40 @end menu
41
42 @node Starting Up
43 @section Starting Up Emacs
44
45 This section describes what Emacs does when it is started, and how you
46 can customize these actions.
47
48 @menu
49 * Startup Summary:: Sequence of actions Emacs performs at startup.
50 * Init File:: Details on reading the init file.
51 * Terminal-Specific:: How the terminal-specific Lisp file is read.
52 * Command-Line Arguments:: How command-line arguments are processed,
53 and how you can customize them.
54 @end menu
55
56 @node Startup Summary
57 @subsection Summary: Sequence of Actions at Startup
58 @cindex initialization of Emacs
59 @cindex startup of Emacs
60 @cindex @file{startup.el}
61
62 When Emacs is started up, it performs the following operations
63 (see @code{normal-top-level} in @file{startup.el}):
64
65 @enumerate
66 @item
67 It adds subdirectories to @code{load-path}, by running the file named
68 @file{subdirs.el} in each directory in the list. Normally, this file
69 adds the directory's subdirectories to the list, and those are scanned
70 in their turn. The files @file{subdirs.el} are normally generated
71 automatically when Emacs is installed.
72
73 @item
74 It loads any @file{leim-list.el} that it finds in the @code{load-path}
75 directories. This file is intended for registering input methods.
76 The search is only for any personal @file{leim-list.el} files that you
77 may have created; it skips the directories containing the standard Emacs
78 libraries (these should contain only a single @file{leim-list.el} file,
79 which is compiled into the Emacs executable).
80
81 @vindex before-init-time
82 @item
83 It sets the variable @code{before-init-time} to the value of
84 @code{current-time} (@pxref{Time of Day}). It also sets
85 @code{after-init-time} to @code{nil}, which signals to Lisp programs
86 that Emacs is being initialized.
87
88 @c set-locale-environment
89 @item
90 It sets the language environment and the terminal coding system,
91 if requested by environment variables such as @env{LANG}.
92
93 @item
94 It does some basic parsing of the command-line arguments.
95
96 @vindex initial-window-system@r{, and startup}
97 @vindex window-system-initialization-alist
98 @item
99 If not running in batch mode, it initializes the window system that
100 the variable @code{initial-window-system} specifies (@pxref{Window
101 Systems, initial-window-system}). The initialization function for
102 each supported window system is specified by
103 @code{window-system-initialization-alist}. If the value
104 of @code{initial-window-system} is @var{windowsystem}, then the
105 appropriate initialization function is defined in the file
106 @file{term/@var{windowsystem}-win.el}. This file should have been
107 compiled into the Emacs executable when it was built.
108
109 @item
110 It runs the normal hook @code{before-init-hook}.
111
112 @item
113 If appropriate, it creates a graphical frame. This is not done if the
114 options @samp{--batch} or @samp{--daemon} were specified.
115
116 @item
117 It initializes the initial frame's faces, and sets up the menu bar
118 and tool bar if needed. If graphical frames are supported, it sets up
119 the tool bar even if the current frame is not a graphical one, since a
120 graphical frame may be created later on.
121
122 @item
123 It use @code{custom-reevaluate-setting} to re-initialize the members
124 of the list @code{custom-delayed-init-variables}. These are any
125 pre-loaded user options whose default value depends on the run-time,
126 rather than build-time, context.
127 @xref{Building Emacs, custom-initialize-delay}.
128
129 @c @item
130 @c It registers the colors available for tty frames.
131
132 @item
133 It loads the library @file{site-start}, if it exists. This is not
134 done if the options @samp{-Q} or @samp{--no-site-file} were specified.
135 @cindex @file{site-start.el}
136
137 @item
138 It loads your init file (@pxref{Init File}). This is not done if the
139 options @samp{-q}, @samp{-Q}, or @samp{--batch} were specified. If
140 the @samp{-u} option was specified, Emacs looks for the init file in
141 that user's home directory instead.
142
143 @item
144 It loads the library @file{default}, if it exists. This is not done
145 if @code{inhibit-default-init} is non-@code{nil}, nor if the options
146 @samp{-q}, @samp{-Q}, or @samp{--batch} were specified.
147 @cindex @file{default.el}
148
149 @item
150 It loads your abbrevs from the file specified by
151 @code{abbrev-file-name}, if that file exists and can be read
152 (@pxref{Abbrev Files, abbrev-file-name}). This is not done if the
153 option @samp{--batch} was specified.
154
155 @item
156 If @code{package-enable-at-startup} is non-@code{nil}, it calls the
157 function @code{package-initialize} to activate any optional Emacs Lisp
158 package that has been installed. @xref{Packaging Basics}.
159
160 @vindex after-init-time
161 @item
162 It sets the variable @code{after-init-time} to the value of
163 @code{current-time}. This variable was set to @code{nil} earlier;
164 setting it to the current time signals that the initialization phase
165 is over, and, together with @code{before-init-time}, provides the
166 measurement of how long it took.
167
168 @item
169 It runs the normal hook @code{after-init-hook}.
170
171 @item
172 If the buffer @file{*scratch*} exists and is still in Fundamental mode
173 (as it should be by default), it sets its major mode according to
174 @code{initial-major-mode}.
175
176 @item
177 If started on a text terminal, it loads the terminal-specific
178 Lisp library, which is specified by the variable
179 @code{term-file-prefix} (@pxref{Terminal-Specific}). This is not done
180 in @code{--batch} mode, nor if @code{term-file-prefix} is @code{nil}.
181
182 @c Now command-line calls command-line-1.
183
184 @item
185 It displays the initial echo area message, unless you have suppressed
186 that with @code{inhibit-startup-echo-area-message}.
187
188 @item
189 It processes any command-line options that were not handled earlier.
190
191 @c This next one is back in command-line, but the remaining bits of
192 @c command-line-1 are not done if noninteractive.
193 @item
194 It now exits if the option @code{--batch} was specified.
195
196 @item
197 If @code{initial-buffer-choice} is a string, it visits the file with
198 that name. If it is a function, it calls the function and selects the
199 buffer returned by the function. It it is @code{t}, it selects the
200 @file{*scratch*} buffer. If the @file{*scratch*} buffer exists and is
201 empty, it inserts @code{initial-scratch-message} into that buffer.
202
203 @c To make things nice and confusing, the next three items can be
204 @c called from two places. If displaying a startup screen, they are
205 @c called in command-line-1 before the startup screen is shown.
206 @c inhibit-startup-hooks is then set and window-setup-hook set to nil.
207 @c If not displaying a startup screen, they are are called in
208 @c normal-top-level.
209 @c FIXME? So it seems they can be called before or after the
210 @c daemon/session restore step?
211
212 @item
213 It runs @code{emacs-startup-hook} and then @code{term-setup-hook}.
214
215 @item
216 It calls @code{frame-notice-user-settings}, which modifies the
217 parameters of the selected frame according to whatever the init files
218 specify.
219
220 @item
221 It runs @code{window-setup-hook}. @xref{Window Systems}.
222
223 @item
224 @cindex startup screen
225 It displays the @dfn{startup screen}, which is a special buffer that
226 contains information about copyleft and basic Emacs usage. This is
227 not done if @code{inhibit-startup-screen} or @code{initial-buffer-choice}
228 are non-@code{nil}, or if the @samp{--no-splash} or @samp{-Q} command-line
229 options were specified.
230
231 @c End of command-line-1.
232
233 @c Back to command-line from command-line-1.
234
235 @c This is the point at which we actually exit in batch mode, but the
236 @c last few bits of command-line-1 are not done in batch mode.
237
238 @item
239 If the option @code{--daemon} was specified, it calls
240 @code{server-start} and detaches from the controlling terminal.
241 @xref{Emacs Server,,, emacs, The GNU Emacs Manual}.
242
243 @item
244 If started by the X session manager, it calls
245 @code{emacs-session-restore} passing it as argument the ID of the
246 previous session. @xref{Session Management}.
247
248 @c End of command-line.
249
250 @c Back to normal-top-level from command-line.
251
252 @end enumerate
253
254 @noindent
255 The following options affect some aspects of the startup sequence.
256
257 @defopt inhibit-startup-screen
258 This variable, if non-@code{nil}, inhibits the startup screen. In
259 that case, Emacs typically displays the @file{*scratch*} buffer; but
260 see @code{initial-buffer-choice}, below.
261
262 Do not set this variable in the init file of a new user, or in a way
263 that affects more than one user, as that would prevent new users from
264 receiving information about copyleft and basic Emacs usage.
265
266 @vindex inhibit-startup-message
267 @vindex inhibit-splash-screen
268 @code{inhibit-startup-message} and @code{inhibit-splash-screen} are
269 aliases for this variable.
270 @end defopt
271
272 @defopt initial-buffer-choice
273 If non-@code{nil}, this variable is a string that specifies a file or
274 directory for Emacs to display after starting up, instead of the
275 startup screen.
276 If its value is a function, Emacs calls that function which must
277 return a buffer which is then displayed.
278 If its value is @code{t}, Emacs displays the @file{*scratch*} buffer.
279 @end defopt
280
281 @defopt inhibit-startup-echo-area-message
282 This variable controls the display of the startup echo area message.
283 You can suppress the startup echo area message by adding text with this
284 form to your init file:
285
286 @example
287 (setq inhibit-startup-echo-area-message
288 "@var{your-login-name}")
289 @end example
290
291 Emacs explicitly checks for an expression as shown above in your init
292 file; your login name must appear in the expression as a Lisp string
293 constant. You can also use the Customize interface. Other methods of
294 setting @code{inhibit-startup-echo-area-message} to the same value do
295 not inhibit the startup message. This way, you can easily inhibit the
296 message for yourself if you wish, but thoughtless copying of your init
297 file will not inhibit the message for someone else.
298 @end defopt
299
300 @defopt initial-scratch-message
301 This variable, if non-@code{nil}, should be a string, which is
302 inserted into the @file{*scratch*} buffer when Emacs starts up. If it
303 is @code{nil}, the @file{*scratch*} buffer is empty.
304 @end defopt
305
306 @noindent
307 The following command-line options affect some aspects of the startup
308 sequence. @xref{Initial Options,,, emacs, The GNU Emacs Manual}.
309
310 @table @code
311 @item --no-splash
312 Do not display a splash screen.
313
314 @item --batch
315 Run without an interactive terminal. @xref{Batch Mode}.
316
317 @item --daemon
318 Do not initialize any display; just start a server in the background.
319
320 @item --no-init-file
321 @itemx -q
322 Do not load either the init file, or the @file{default} library.
323
324 @item --no-site-file
325 Do not load the @file{site-start} library.
326
327 @item --quick
328 @itemx -Q
329 Equivalent to @samp{-q --no-site-file --no-splash}.
330 @c and --no-site-lisp, but let's not mention that here.
331 @end table
332
333
334 @node Init File
335 @subsection The Init File
336 @cindex init file
337 @cindex @file{.emacs}
338 @cindex @file{init.el}
339
340 When you start Emacs, it normally attempts to load your @dfn{init
341 file}. This is either a file named @file{.emacs} or @file{.emacs.el}
342 in your home directory, or a file named @file{init.el} in a
343 subdirectory named @file{.emacs.d} in your home directory.
344 @ignore
345 Whichever place you use, you can also compile the file (@pxref{Byte
346 Compilation}); then the actual file loaded will be @file{.emacs.elc}
347 or @file{init.elc}.
348 @end ignore
349
350 The command-line switches @samp{-q}, @samp{-Q}, and @samp{-u}
351 control whether and where to find the init file; @samp{-q} (and the
352 stronger @samp{-Q}) says not to load an init file, while @samp{-u
353 @var{user}} says to load @var{user}'s init file instead of yours.
354 @xref{Entering Emacs,,, emacs, The GNU Emacs Manual}. If neither
355 option is specified, Emacs uses the @env{LOGNAME} environment
356 variable, or the @env{USER} (most systems) or @env{USERNAME} (MS
357 systems) variable, to find your home directory and thus your init
358 file; this way, even if you have su'd, Emacs still loads your own init
359 file. If those environment variables are absent, though, Emacs uses
360 your user-id to find your home directory.
361
362 @cindex default init file
363 An Emacs installation may have a @dfn{default init file}, which is a
364 Lisp library named @file{default.el}. Emacs finds this file through
365 the standard search path for libraries (@pxref{How Programs Do
366 Loading}). The Emacs distribution does not come with this file; it is
367 intended for local customizations. If the default init file exists,
368 it is loaded whenever you start Emacs. But your own personal init
369 file, if any, is loaded first; if it sets @code{inhibit-default-init}
370 to a non-@code{nil} value, then Emacs does not subsequently load the
371 @file{default.el} file. In batch mode, or if you specify @samp{-q}
372 (or @samp{-Q}), Emacs loads neither your personal init file nor
373 the default init file.
374
375 Another file for site-customization is @file{site-start.el}. Emacs
376 loads this @emph{before} the user's init file. You can inhibit the
377 loading of this file with the option @samp{--no-site-file}.
378
379 @defopt site-run-file
380 This variable specifies the site-customization file to load before the
381 user's init file. Its normal value is @code{"site-start"}. The only
382 way you can change it with real effect is to do so before dumping
383 Emacs.
384 @c So why even mention it here. I imagine it is almost never changed.
385 @end defopt
386
387 @xref{Init Examples,, Init File Examples, emacs, The GNU Emacs Manual}, for
388 examples of how to make various commonly desired customizations in your
389 @file{.emacs} file.
390
391 @defopt inhibit-default-init
392 If this variable is non-@code{nil}, it prevents Emacs from loading the
393 default initialization library file. The default value is @code{nil}.
394 @end defopt
395
396 @defvar before-init-hook
397 This normal hook is run, once, just before loading all the init files
398 (@file{site-start.el}, your init file, and @file{default.el}).
399 (The only way to change it with real effect is before dumping Emacs.)
400 @end defvar
401
402 @defvar after-init-hook
403 This normal hook is run, once, just after loading all the init files
404 (@file{site-start.el}, your init file, and @file{default.el}),
405 before loading the terminal-specific library (if started on a text
406 terminal) and processing the command-line action arguments.
407 @end defvar
408
409 @defvar emacs-startup-hook
410 This normal hook is run, once, just after handling the command line
411 arguments, just before @code{term-setup-hook}. In batch mode, Emacs
412 does not run either of these hooks.
413 @end defvar
414
415 @defvar user-init-file
416 This variable holds the absolute file name of the user's init file. If the
417 actual init file loaded is a compiled file, such as @file{.emacs.elc},
418 the value refers to the corresponding source file.
419 @end defvar
420
421 @defvar user-emacs-directory
422 This variable holds the name of the @file{.emacs.d} directory. It is
423 @file{~/.emacs.d} on all platforms but MS-DOS.
424 @end defvar
425
426 @node Terminal-Specific
427 @subsection Terminal-Specific Initialization
428 @cindex terminal-specific initialization
429
430 Each terminal type can have its own Lisp library that Emacs loads when
431 run on that type of terminal. The library's name is constructed by
432 concatenating the value of the variable @code{term-file-prefix} and the
433 terminal type (specified by the environment variable @env{TERM}).
434 Normally, @code{term-file-prefix} has the value
435 @code{"term/"}; changing this is not recommended. Emacs finds the file
436 in the normal manner, by searching the @code{load-path} directories, and
437 trying the @samp{.elc} and @samp{.el} suffixes.
438
439 @cindex Termcap
440 The usual role of a terminal-specific library is to enable special
441 keys to send sequences that Emacs can recognize. It may also need to
442 set or add to @code{input-decode-map} if the Termcap or Terminfo entry
443 does not specify all the terminal's function keys. @xref{Terminal
444 Input}.
445
446 When the name of the terminal type contains a hyphen or underscore, and no library
447 is found whose name is identical to the terminal's name, Emacs strips
448 from the terminal's name the last hyphen or underscore and everything that follows
449 it, and tries again. This process is repeated until Emacs finds a
450 matching library, or until there are no more hyphens or underscores in the name
451 (i.e., there is no terminal-specific library). For example, if the
452 terminal name is @samp{xterm-256color} and there is no
453 @file{term/xterm-256color.el} library, Emacs tries to load
454 @file{term/xterm.el}. If necessary, the terminal library can evaluate
455 @code{(getenv "TERM")} to find the full name of the terminal type.
456
457 Your init file can prevent the loading of the
458 terminal-specific library by setting the variable
459 @code{term-file-prefix} to @code{nil}. This feature is useful when
460 experimenting with your own peculiar customizations.
461
462 You can also arrange to override some of the actions of the
463 terminal-specific library by setting the variable
464 @code{term-setup-hook}. This is a normal hook that Emacs runs
465 at the end of its initialization, after loading both
466 your init file and any terminal-specific libraries. You could
467 use this hook to define initializations for terminals that do not
468 have their own libraries. @xref{Hooks}.
469
470 @defvar term-file-prefix
471 @cindex @env{TERM} environment variable
472 If the value of this variable is non-@code{nil}, Emacs loads a
473 terminal-specific initialization file as follows:
474
475 @example
476 (load (concat term-file-prefix (getenv "TERM")))
477 @end example
478
479 @noindent
480 You may set the @code{term-file-prefix} variable to @code{nil} in your
481 init file if you do not wish to load the
482 terminal-initialization file.
483
484 On MS-DOS, Emacs sets the @env{TERM} environment variable to @samp{internal}.
485 @end defvar
486
487 @defvar term-setup-hook
488 This variable is a normal hook that Emacs runs after loading your
489 init file, the default initialization file (if any) and the
490 terminal-specific Lisp file.
491
492 You can use @code{term-setup-hook} to override the definitions made by a
493 terminal-specific file.
494
495 For a related feature, @pxref{Window Systems, window-setup-hook}.
496 @end defvar
497
498 @node Command-Line Arguments
499 @subsection Command-Line Arguments
500 @cindex command-line arguments
501
502 You can use command-line arguments to request various actions when
503 you start Emacs. Note that the recommended way of using Emacs is to
504 start it just once, after logging in, and then do all editing in the same
505 Emacs session (@pxref{Entering Emacs,,, emacs, The GNU Emacs Manual}).
506 For this reason, you might not use command-line arguments very often;
507 nonetheless, they can be useful when invoking Emacs from session
508 scripts or debugging Emacs. This section describes how Emacs
509 processes command-line arguments.
510
511 @defun command-line
512 This function parses the command line that Emacs was called with,
513 processes it, and (amongst other things) loads the user's init file and
514 displays the startup messages.
515 @end defun
516
517 @defvar command-line-processed
518 The value of this variable is @code{t} once the command line has been
519 processed.
520
521 If you redump Emacs by calling @code{dump-emacs} (@pxref{Building
522 Emacs}), you may wish to set this variable to @code{nil} first in
523 order to cause the new dumped Emacs to process its new command-line
524 arguments.
525 @end defvar
526
527 @defvar command-switch-alist
528 @cindex switches on command line
529 @cindex options on command line
530 @cindex command-line options
531 This variable is an alist of user-defined command-line options and
532 associated handler functions. By default it is empty, but you can
533 add elements if you wish.
534
535 A @dfn{command-line option} is an argument on the command line, which
536 has the form:
537
538 @example
539 -@var{option}
540 @end example
541
542 The elements of the @code{command-switch-alist} look like this:
543
544 @example
545 (@var{option} . @var{handler-function})
546 @end example
547
548 The @sc{car}, @var{option}, is a string, the name of a command-line
549 option (not including the initial hyphen). The @var{handler-function}
550 is called to handle @var{option}, and receives the option name as its
551 sole argument.
552
553 In some cases, the option is followed in the command line by an
554 argument. In these cases, the @var{handler-function} can find all the
555 remaining command-line arguments in the variable
556 @code{command-line-args-left} (see below). (The entire list of
557 command-line arguments is in @code{command-line-args}.)
558
559 The command-line arguments are parsed by the @code{command-line-1}
560 function in the @file{startup.el} file. See also @ref{Emacs
561 Invocation, , Command Line Arguments for Emacs Invocation, emacs, The
562 GNU Emacs Manual}.
563 @end defvar
564
565 @defvar command-line-args
566 The value of this variable is the list of command-line arguments passed
567 to Emacs.
568 @end defvar
569
570 @defvar command-line-args-left
571 @vindex argv
572 The value of this variable is the list of command-line arguments that
573 have not yet been processed.
574 @c Don't mention this, since it is a "bad name for a dynamically bound variable"
575 @c @code{argv} is an alias for this.
576 @end defvar
577
578 @defvar command-line-functions
579 This variable's value is a list of functions for handling an
580 unrecognized command-line argument. Each time the next argument to be
581 processed has no special meaning, the functions in this list are called,
582 in order of appearance, until one of them returns a non-@code{nil}
583 value.
584
585 These functions are called with no arguments. They can access the
586 command-line argument under consideration through the variable
587 @code{argi}, which is bound temporarily at this point. The remaining
588 arguments (not including the current one) are in the variable
589 @code{command-line-args-left}.
590
591 When a function recognizes and processes the argument in @code{argi}, it
592 should return a non-@code{nil} value to say it has dealt with that
593 argument. If it has also dealt with some of the following arguments, it
594 can indicate that by deleting them from @code{command-line-args-left}.
595
596 If all of these functions return @code{nil}, then the argument is treated
597 as a file name to visit.
598 @end defvar
599
600 @node Getting Out
601 @section Getting Out of Emacs
602 @cindex exiting Emacs
603
604 There are two ways to get out of Emacs: you can kill the Emacs job,
605 which exits permanently, or you can suspend it, which permits you to
606 reenter the Emacs process later. (In a graphical environment, you can
607 of course simply switch to another application without doing anything
608 special to Emacs, then switch back to Emacs when you want.)
609
610 @menu
611 * Killing Emacs:: Exiting Emacs irreversibly.
612 * Suspending Emacs:: Exiting Emacs reversibly.
613 @end menu
614
615 @node Killing Emacs
616 @subsection Killing Emacs
617 @cindex killing Emacs
618
619 Killing Emacs means ending the execution of the Emacs process.
620 If you started Emacs from a terminal, the parent process normally
621 resumes control. The low-level primitive for killing Emacs is
622 @code{kill-emacs}.
623
624 @deffn Command kill-emacs &optional exit-data
625 This command calls the hook @code{kill-emacs-hook}, then exits the
626 Emacs process and kills it.
627
628 If @var{exit-data} is an integer, that is used as the exit status of
629 the Emacs process. (This is useful primarily in batch operation; see
630 @ref{Batch Mode}.)
631
632 If @var{exit-data} is a string, its contents are stuffed into the
633 terminal input buffer so that the shell (or whatever program next reads
634 input) can read them.
635 @end deffn
636
637 @cindex SIGTERM
638 @cindex SIGHUP
639 @cindex SIGINT
640 @cindex operating system signal
641 The @code{kill-emacs} function is normally called via the
642 higher-level command @kbd{C-x C-c}
643 (@code{save-buffers-kill-terminal}). @xref{Exiting,,, emacs, The GNU
644 Emacs Manual}. It is also called automatically if Emacs receives a
645 @code{SIGTERM} or @code{SIGHUP} operating system signal (e.g., when the
646 controlling terminal is disconnected), or if it receives a
647 @code{SIGINT} signal while running in batch mode (@pxref{Batch Mode}).
648
649 @defvar kill-emacs-hook
650 This normal hook is run by @code{kill-emacs}, before it kills Emacs.
651
652 Because @code{kill-emacs} can be called in situations where user
653 interaction is impossible (e.g., when the terminal is disconnected),
654 functions on this hook should not attempt to interact with the user.
655 If you want to interact with the user when Emacs is shutting down, use
656 @code{kill-emacs-query-functions}, described below.
657 @end defvar
658
659 When Emacs is killed, all the information in the Emacs process,
660 aside from files that have been saved, is lost. Because killing Emacs
661 inadvertently can lose a lot of work, the
662 @code{save-buffers-kill-terminal} command queries for confirmation if
663 you have buffers that need saving or subprocesses that are running.
664 It also runs the abnormal hook @code{kill-emacs-query-functions}:
665
666 @defvar kill-emacs-query-functions
667 When @code{save-buffers-kill-terminal} is killing Emacs, it calls the
668 functions in this hook, after asking the standard questions and before
669 calling @code{kill-emacs}. The functions are called in order of
670 appearance, with no arguments. Each function can ask for additional
671 confirmation from the user. If any of them returns @code{nil},
672 @code{save-buffers-kill-emacs} does not kill Emacs, and does not run
673 the remaining functions in this hook. Calling @code{kill-emacs}
674 directly does not run this hook.
675 @end defvar
676
677 @node Suspending Emacs
678 @subsection Suspending Emacs
679 @cindex suspending Emacs
680
681 On text terminals, it is possible to @dfn{suspend Emacs}, which
682 means stopping Emacs temporarily and returning control to its superior
683 process, which is usually the shell. This allows you to resume
684 editing later in the same Emacs process, with the same buffers, the
685 same kill ring, the same undo history, and so on. To resume Emacs,
686 use the appropriate command in the parent shell---most likely
687 @code{fg}.
688
689 @cindex controlling terminal
690 Suspending works only on a terminal device from which the Emacs
691 session was started. We call that device the @dfn{controlling
692 terminal} of the session. Suspending is not allowed if the
693 controlling terminal is a graphical terminal. Suspending is usually
694 not relevant in graphical environments, since you can simply switch to
695 another application without doing anything special to Emacs.
696
697 @c FIXME? Are there any systems Emacs still supports that do not
698 @c have SIGTSTP?
699 @cindex SIGTSTP
700 Some operating systems (those without @code{SIGTSTP}, or MS-DOS) do
701 not support suspension of jobs; on these systems, ``suspension''
702 actually creates a new shell temporarily as a subprocess of Emacs.
703 Then you would exit the shell to return to Emacs.
704
705 @deffn Command suspend-emacs &optional string
706 This function stops Emacs and returns control to the superior process.
707 If and when the superior process resumes Emacs, @code{suspend-emacs}
708 returns @code{nil} to its caller in Lisp.
709
710 This function works only on the controlling terminal of the Emacs
711 session; to relinquish control of other tty devices, use
712 @code{suspend-tty} (see below). If the Emacs session uses more than
713 one terminal, you must delete the frames on all the other terminals
714 before suspending Emacs, or this function signals an error.
715 @xref{Multiple Terminals}.
716
717 If @var{string} is non-@code{nil}, its characters are sent to Emacs's
718 superior shell, to be read as terminal input.
719 @c FIXME? It seems to me that shell does echo STRING.
720 The characters in @var{string} are not echoed by the superior shell;
721 only the results appear.
722
723 Before suspending, @code{suspend-emacs} runs the normal hook
724 @code{suspend-hook}. After the user resumes Emacs,
725 @code{suspend-emacs} runs the normal hook @code{suspend-resume-hook}.
726 @xref{Hooks}.
727
728 The next redisplay after resumption will redraw the entire screen,
729 unless the variable @code{no-redraw-on-reenter} is non-@code{nil}.
730 @xref{Refresh Screen}.
731
732 Here is an example of how you could use these hooks:
733
734 @smallexample
735 @group
736 (add-hook 'suspend-hook
737 (lambda () (or (y-or-n-p "Really suspend? ")
738 (error "Suspend canceled"))))
739 @end group
740 (add-hook 'suspend-resume-hook (lambda () (message "Resumed!")
741 (sit-for 2)))
742 @end smallexample
743 @c The sit-for prevents the ``nil'' that suspend-emacs returns
744 @c hiding the message.
745
746 Here is what you would see upon evaluating @code{(suspend-emacs "pwd")}:
747
748 @smallexample
749 @group
750 ---------- Buffer: Minibuffer ----------
751 Really suspend? @kbd{y}
752 ---------- Buffer: Minibuffer ----------
753 @end group
754
755 @group
756 ---------- Parent Shell ----------
757 bash$ /home/username
758 bash$ fg
759 @end group
760
761 @group
762 ---------- Echo Area ----------
763 Resumed!
764 @end group
765 @end smallexample
766
767 @c FIXME? AFAICS, it is echoed.
768 Note that @samp{pwd} is not echoed after Emacs is suspended. But it
769 is read and executed by the shell.
770 @end deffn
771
772 @defvar suspend-hook
773 This variable is a normal hook that Emacs runs before suspending.
774 @end defvar
775
776 @defvar suspend-resume-hook
777 This variable is a normal hook that Emacs runs on resuming
778 after a suspension.
779 @end defvar
780
781 @defun suspend-tty &optional tty
782 If @var{tty} specifies a terminal device used by Emacs, this function
783 relinquishes the device and restores it to its prior state. Frames
784 that used the device continue to exist, but are not updated and Emacs
785 doesn't read input from them. @var{tty} can be a terminal object, a
786 frame (meaning the terminal for that frame), or @code{nil} (meaning
787 the terminal for the selected frame). @xref{Multiple Terminals}.
788
789 If @var{tty} is already suspended, this function does nothing.
790
791 @vindex suspend-tty-functions
792 This function runs the hook @code{suspend-tty-functions}, passing the
793 terminal object as an argument to each function.
794 @end defun
795
796 @defun resume-tty &optional tty
797 This function resumes the previously suspended terminal device
798 @var{tty}; where @var{tty} has the same possible values as it does
799 for @code{suspend-tty}.
800
801 @vindex resume-tty-functions
802 This function reopens the terminal device, re-initializes it, and
803 redraws it with that terminal's selected frame. It then runs the
804 hook @code{resume-tty-functions}, passing the terminal object as an
805 argument to each function.
806
807 If the same device is already used by another Emacs terminal, this
808 function signals an error. If @var{tty} is not suspended, this
809 function does nothing.
810 @end defun
811
812 @defun controlling-tty-p &optional tty
813 This function returns non-@code{nil} if @var{tty} is the
814 controlling terminal of the Emacs session; @var{tty} can be a
815 terminal object, a frame (meaning the terminal for that frame), or
816 @code{nil} (meaning the terminal for the selected frame).
817 @end defun
818
819 @deffn Command suspend-frame
820 This command @dfn{suspends} a frame. For GUI frames, it calls
821 @code{iconify-frame} (@pxref{Visibility of Frames}); for frames on
822 text terminals, it calls either @code{suspend-emacs} or
823 @code{suspend-tty}, depending on whether the frame is displayed on the
824 controlling terminal device or not.
825 @end deffn
826
827 @node System Environment
828 @section Operating System Environment
829 @cindex operating system environment
830
831 Emacs provides access to variables in the operating system environment
832 through various functions. These variables include the name of the
833 system, the user's @acronym{UID}, and so on.
834
835 @defvar system-configuration
836 This variable holds the standard GNU configuration name for the
837 hardware/software configuration of your system, as a string. For
838 example, a typical value for a 64-bit GNU/Linux system is
839 @samp{"x86_64-unknown-linux-gnu"}.
840 @end defvar
841
842 @cindex system type and name
843 @defvar system-type
844 The value of this variable is a symbol indicating the type of operating
845 system Emacs is running on. The possible values are:
846
847 @table @code
848 @item aix
849 IBM's AIX.
850
851 @item berkeley-unix
852 Berkeley BSD and its variants.
853
854 @item cygwin
855 Cygwin, a Posix layer on top of MS-Windows.
856
857 @item darwin
858 Darwin (Mac OS X).
859
860 @item gnu
861 The GNU system (using the GNU kernel, which consists of the HURD and Mach).
862
863 @item gnu/linux
864 A GNU/Linux system---that is, a variant GNU system, using the Linux
865 kernel. (These systems are the ones people often call ``Linux'', but
866 actually Linux is just the kernel, not the whole system.)
867
868 @item gnu/kfreebsd
869 A GNU (glibc-based) system with a FreeBSD kernel.
870
871 @item hpux
872 Hewlett-Packard HPUX operating system.
873
874 @item irix
875 Silicon Graphics Irix system.
876
877 @item ms-dos
878 Microsoft's DOS@. Emacs compiled with DJGPP for MS-DOS binds
879 @code{system-type} to @code{ms-dos} even when you run it on MS-Windows.
880
881 @item usg-unix-v
882 AT&T Unix System V.
883
884 @item windows-nt
885 Microsoft Windows NT, 9X and later. The value of @code{system-type}
886 is always @code{windows-nt}, e.g., even on Windows 7.
887
888 @end table
889
890 We do not wish to add new symbols to make finer distinctions unless it
891 is absolutely necessary! In fact, we hope to eliminate some of these
892 alternatives in the future. If you need to make a finer distinction
893 than @code{system-type} allows for, you can test
894 @code{system-configuration}, e.g., against a regexp.
895 @end defvar
896
897 @defun system-name
898 This function returns the name of the machine you are running on, as a
899 string.
900 @end defun
901
902 The symbol @code{system-name} is a variable as well as a function. In
903 fact, the function returns whatever value the variable
904 @code{system-name} currently holds. Thus, you can set the variable
905 @code{system-name} in case Emacs is confused about the name of your
906 system. The variable is also useful for constructing frame titles
907 (@pxref{Frame Titles}).
908
909 @c FIXME seems like this section is not the best place for this option?
910 @defopt mail-host-address
911 If this variable is non-@code{nil}, it is used instead of
912 @code{system-name} for purposes of generating email addresses. For
913 example, it is used when constructing the default value of
914 @code{user-mail-address}. @xref{User Identification}. (Since this is
915 done when Emacs starts up, the value actually used is the one saved when
916 Emacs was dumped. @xref{Building Emacs}.)
917 @c FIXME sounds like should probably give this a :set-after and some
918 @c custom-initialize-delay voodoo.
919 @end defopt
920
921 @deffn Command getenv var &optional frame
922 @cindex environment variable access
923 This function returns the value of the environment variable @var{var},
924 as a string. @var{var} should be a string. If @var{var} is undefined
925 in the environment, @code{getenv} returns @code{nil}. It returns
926 @samp{""} if @var{var} is set but null. Within Emacs, a list of environment
927 variables and their values is kept in the variable @code{process-environment}.
928
929 @example
930 @group
931 (getenv "USER")
932 @result{} "lewis"
933 @end group
934 @end example
935
936 The shell command @code{printenv} prints all or part of the environment:
937
938 @example
939 @group
940 bash$ printenv
941 PATH=/usr/local/bin:/usr/bin:/bin
942 USER=lewis
943 @end group
944 @group
945 TERM=xterm
946 SHELL=/bin/bash
947 HOME=/home/lewis
948 @end group
949 @dots{}
950 @end example
951 @end deffn
952
953 @deffn Command setenv variable &optional value substitute
954 This command sets the value of the environment variable named
955 @var{variable} to @var{value}. @var{variable} should be a string.
956 Internally, Emacs Lisp can handle any string. However, normally
957 @var{variable} should be a valid shell identifier, that is, a sequence
958 of letters, digits and underscores, starting with a letter or
959 underscore. Otherwise, errors may occur if subprocesses of Emacs try
960 to access the value of @var{variable}. If @var{value} is omitted or
961 @code{nil} (or, interactively, with a prefix argument), @code{setenv}
962 removes @var{variable} from the environment. Otherwise, @var{value}
963 should be a string.
964
965 @c FIXME: Document `substitute-env-vars'? --xfq
966 If the optional argument @var{substitute} is non-@code{nil}, Emacs
967 calls the function @code{substitute-env-vars} to expand any
968 environment variables in @var{value}.
969
970 @code{setenv} works by modifying @code{process-environment}; binding
971 that variable with @code{let} is also reasonable practice.
972
973 @code{setenv} returns the new value of @var{variable}, or @code{nil}
974 if it removed @var{variable} from the environment.
975 @end deffn
976
977 @defvar process-environment
978 This variable is a list of strings, each describing one environment
979 variable. The functions @code{getenv} and @code{setenv} work by means
980 of this variable.
981
982 @smallexample
983 @group
984 process-environment
985 @result{} ("PATH=/usr/local/bin:/usr/bin:/bin"
986 "USER=lewis"
987 @end group
988 @group
989 "TERM=xterm"
990 "SHELL=/bin/bash"
991 "HOME=/home/lewis"
992 @dots{})
993 @end group
994 @end smallexample
995
996 If @code{process-environment} contains ``duplicate'' elements that
997 specify the same environment variable, the first of these elements
998 specifies the variable, and the other ``duplicates'' are ignored.
999 @end defvar
1000
1001 @defvar initial-environment
1002 This variable holds the list of environment variables Emacs inherited
1003 from its parent process when Emacs started.
1004 @end defvar
1005
1006 @defvar path-separator
1007 This variable holds a string that says which character separates
1008 directories in a search path (as found in an environment variable). Its
1009 value is @code{":"} for Unix and GNU systems, and @code{";"} for MS systems.
1010 @end defvar
1011
1012 @defun parse-colon-path path
1013 This function takes a search path string such as the value of
1014 the @env{PATH} environment variable, and splits it at the separators,
1015 returning a list of directory names. @code{nil} in this list means
1016 the current directory. Although the function's name says
1017 ``colon'', it actually uses the value of @code{path-separator}.
1018
1019 @example
1020 (parse-colon-path ":/foo:/bar")
1021 @result{} (nil "/foo/" "/bar/")
1022 @end example
1023 @end defun
1024
1025 @defvar invocation-name
1026 This variable holds the program name under which Emacs was invoked. The
1027 value is a string, and does not include a directory name.
1028 @end defvar
1029
1030 @defvar invocation-directory
1031 This variable holds the directory from which the Emacs executable was
1032 invoked, or @code{nil} if that directory cannot be determined.
1033 @end defvar
1034
1035 @defvar installation-directory
1036 If non-@code{nil}, this is a directory within which to look for the
1037 @file{lib-src} and @file{etc} subdirectories. In an installed Emacs,
1038 it is normally @code{nil}. It is non-@code{nil}
1039 when Emacs can't find those directories in their standard installed
1040 locations, but can find them in a directory related somehow to the one
1041 containing the Emacs executable (i.e., @code{invocation-directory}).
1042 @end defvar
1043
1044 @defun load-average &optional use-float
1045 This function returns the current 1-minute, 5-minute, and 15-minute
1046 system load averages, in a list. The load average indicates the
1047 number of processes trying to run on the system.
1048
1049 By default, the values are integers that are 100 times the system load
1050 averages, but if @var{use-float} is non-@code{nil}, then they are
1051 returned as floating point numbers without multiplying by 100.
1052
1053 If it is impossible to obtain the load average, this function signals
1054 an error. On some platforms, access to load averages requires
1055 installing Emacs as setuid or setgid so that it can read kernel
1056 information, and that usually isn't advisable.
1057 @c FIXME which platforms are these? Are they still relevant?
1058
1059 If the 1-minute load average is available, but the 5- or 15-minute
1060 averages are not, this function returns a shortened list containing
1061 the available averages.
1062
1063 @example
1064 @group
1065 (load-average)
1066 @result{} (169 48 36)
1067 @end group
1068 @group
1069 (load-average t)
1070 @result{} (1.69 0.48 0.36)
1071 @end group
1072 @end example
1073
1074 The shell command @code{uptime} returns similar information.
1075 @end defun
1076
1077 @defun emacs-pid
1078 This function returns the process @acronym{ID} of the Emacs process,
1079 as an integer.
1080 @end defun
1081
1082 @defvar tty-erase-char
1083 This variable holds the erase character that was selected
1084 in the system's terminal driver, before Emacs was started.
1085 @c FIXME? Seems untrue since 23.1. For me, it is 0.
1086 @c The value is @code{nil} if Emacs is running under a window system.
1087 @end defvar
1088
1089 @node User Identification
1090 @section User Identification
1091 @cindex user identification
1092
1093 @defvar init-file-user
1094 This variable says which user's init files should be used by
1095 Emacs---or @code{nil} if none. @code{""} stands for the user who
1096 originally logged in. The value reflects command-line options such as
1097 @samp{-q} or @samp{-u @var{user}}.
1098
1099 Lisp packages that load files of customizations, or any other sort of
1100 user profile, should obey this variable in deciding where to find it.
1101 They should load the profile of the user name found in this variable.
1102 If @code{init-file-user} is @code{nil}, meaning that the @samp{-q},
1103 @samp{-Q}, or @samp{-batch} option was used, then Lisp packages should
1104 not load any customization files or user profile.
1105 @end defvar
1106
1107 @defopt user-mail-address
1108 This holds the nominal email address of the user who is using Emacs.
1109 Emacs normally sets this variable to a default value after reading your
1110 init files, but not if you have already set it. So you can set the
1111 variable to some other value in your init file if you do not
1112 want to use the default value.
1113 @end defopt
1114
1115 @defun user-login-name &optional uid
1116 This function returns the name under which the user is logged in.
1117 It uses the environment variables @env{LOGNAME} or @env{USER} if
1118 either is set. Otherwise, the value is based on the effective
1119 @acronym{UID}, not the real @acronym{UID}.
1120
1121 If you specify @var{uid} (a number), the result is the user name that
1122 corresponds to @var{uid}, or @code{nil} if there is no such user.
1123 @end defun
1124
1125 @defun user-real-login-name
1126 This function returns the user name corresponding to Emacs's real
1127 @acronym{UID}. This ignores the effective @acronym{UID}, and the
1128 environment variables @env{LOGNAME} and @env{USER}.
1129 @end defun
1130
1131 @defun user-full-name &optional uid
1132 This function returns the full name of the logged-in user---or the value
1133 of the environment variable @env{NAME}, if that is set.
1134
1135 If the Emacs process's user-id does not correspond to any known user (and
1136 provided @code{NAME} is not set), the result is @code{"unknown"}.
1137
1138 If @var{uid} is non-@code{nil}, then it should be a number (a user-id)
1139 or a string (a login name). Then @code{user-full-name} returns the full
1140 name corresponding to that user-id or login name. If you specify a
1141 user-id or login name that isn't defined, it returns @code{nil}.
1142 @end defun
1143
1144 @vindex user-full-name
1145 @vindex user-real-login-name
1146 @vindex user-login-name
1147 The symbols @code{user-login-name}, @code{user-real-login-name} and
1148 @code{user-full-name} are variables as well as functions. The functions
1149 return the same values that the variables hold. These variables allow
1150 you to ``fake out'' Emacs by telling the functions what to return. The
1151 variables are also useful for constructing frame titles (@pxref{Frame
1152 Titles}).
1153
1154 @cindex UID
1155 @defun user-real-uid
1156 This function returns the real @acronym{UID} of the user.
1157 The value may be a floating point number, in the (unlikely) event that
1158 the UID is too large to fit in a Lisp integer.
1159 @end defun
1160
1161 @defun user-uid
1162 This function returns the effective @acronym{UID} of the user.
1163 The value may be a floating point number.
1164 @end defun
1165
1166 @cindex GID
1167 @defun group-gid
1168 This function returns the effective @acronym{GID} of the Emacs process.
1169 The value may be a floating point number.
1170 @end defun
1171
1172 @defun group-real-gid
1173 This function returns the real @acronym{GID} of the Emacs process.
1174 The value may be a floating point number.
1175 @end defun
1176
1177 @defun system-users
1178 This function returns a list of strings, listing the user names on the
1179 system. If Emacs cannot retrieve this information, the return value
1180 is a list containing just the value of @code{user-real-login-name}.
1181 @end defun
1182
1183 @cindex user groups
1184 @defun system-groups
1185 This function returns a list of strings, listing the names of user
1186 groups on the system. If Emacs cannot retrieve this information, the
1187 return value is @code{nil}.
1188 @end defun
1189
1190
1191 @node Time of Day
1192 @section Time of Day
1193
1194 This section explains how to determine the current time and time
1195 zone.
1196
1197 @cindex epoch
1198 Most of these functions represent time as a list of either four
1199 integers, @code{(@var{sec-high} @var{sec-low} @var{microsec}
1200 @var{picosec})}, or of three
1201 integers, @code{(@var{sec-high} @var{sec-low} @var{microsec})}, or of
1202 two integers, @code{(@var{sec-high} @var{sec-low})}. The integers
1203 @var{sec-high} and @var{sec-low} give the high and low bits of an
1204 integer number of seconds. This integer number,
1205 @ifnottex
1206 @var{high} * 2**16 + @var{low},
1207 @end ifnottex
1208 @tex
1209 $high*2^{16}+low$,
1210 @end tex
1211 is the number of seconds from the @dfn{epoch} (0:00 January 1, 1970
1212 UTC) to the specified time. The third list element @var{microsec}, if
1213 present, gives the number of microseconds from the start of that
1214 second to the specified time.
1215 Similarly, the fourth list element @var{picosec}, if present, gives
1216 the number of picoseconds from the start of that microsecond to the
1217 specified time.
1218
1219 The return value of @code{current-time} represents time using four
1220 integers, as do the timestamps in the return value of
1221 @code{file-attributes} (@pxref{Definition of
1222 file-attributes}). In function arguments, e.g., the @var{time-value}
1223 argument to @code{current-time-string}, two-, three-, and four-integer
1224 lists are accepted. You can convert times from the list
1225 representation into standard human-readable strings using
1226 @code{current-time-string}, or to other forms using the
1227 @code{decode-time} and @code{format-time-string} functions documented
1228 in the following sections.
1229
1230 @defun current-time-string &optional time-value
1231 This function returns the current time and date as a human-readable
1232 string. The format does not vary for the initial part of the string,
1233 which contains the day of week, month, day of month, and time of day
1234 in that order: the number of characters used for these fields is
1235 always the same, so you can reliably
1236 use @code{substring} to extract them. You should count
1237 characters from the beginning of the string rather than from the end,
1238 as the year might not have exactly four digits, and additional
1239 information may some day be added at the end.
1240
1241 The argument @var{time-value}, if given, specifies a time to format
1242 (represented as a list of integers), instead of the current time.
1243
1244 @example
1245 @group
1246 (current-time-string)
1247 @result{} "Wed Oct 14 22:21:05 1987"
1248 @end group
1249 @end example
1250 @end defun
1251
1252 @defun current-time
1253 This function returns the current time, represented as a list of four
1254 integers @code{(@var{sec-high} @var{sec-low} @var{microsec} @var{picosec})}.
1255 These integers have trailing zeros on systems that return time with
1256 lower resolutions. On all current machines @var{picosec} is a
1257 multiple of 1000, but this may change as higher-resolution clocks
1258 become available.
1259 @end defun
1260
1261 @defun float-time &optional time-value
1262 This function returns the current time as a floating-point number of
1263 seconds since the epoch. The optional argument @var{time-value}, if
1264 given, specifies a time (represented as a list of integers) to convert
1265 instead of the current time.
1266
1267 @emph{Warning}: Since the result is floating point, it may not be
1268 exact. Do not use this function if precise time stamps are required.
1269 @end defun
1270
1271 @defun current-time-zone &optional time-value
1272 @cindex time zone, current
1273 This function returns a list describing the time zone that the user is
1274 in.
1275
1276 The value has the form @code{(@var{offset} @var{name})}. Here
1277 @var{offset} is an integer giving the number of seconds ahead of UTC
1278 (east of Greenwich). A negative value means west of Greenwich. The
1279 second element, @var{name}, is a string giving the name of the time
1280 zone. Both elements change when daylight saving time begins or ends;
1281 if the user has specified a time zone that does not use a seasonal time
1282 adjustment, then the value is constant through time.
1283
1284 If the operating system doesn't supply all the information necessary to
1285 compute the value, the unknown elements of the list are @code{nil}.
1286
1287 The argument @var{time-value}, if given, specifies a time (represented
1288 as a list of integers) to analyze instead of the current time.
1289 @end defun
1290
1291 The current time zone is determined by the @env{TZ} environment
1292 variable. @xref{System Environment}. For example, you can tell Emacs
1293 to use universal time with @code{(setenv "TZ" "UTC0")}. If @env{TZ}
1294 is not in the environment, Emacs uses a platform-dependent default
1295 time zone.
1296
1297 @node Time Conversion
1298 @section Time Conversion
1299 @cindex calendrical information
1300
1301 These functions convert time values (lists of two to four integers,
1302 as explained in the previous section) into calendrical information and
1303 vice versa.
1304
1305 Many 32-bit operating systems are limited to time values containing
1306 32 bits of information; these systems typically handle only the times
1307 from 1901-12-13 20:45:52 UTC through 2038-01-19 03:14:07 UTC@.
1308 However, 64-bit and some 32-bit operating systems have larger time
1309 values, and can represent times far in the past or future.
1310
1311 Time conversion functions always use the Gregorian calendar, even
1312 for dates before the Gregorian calendar was introduced. Year numbers
1313 count the number of years since the year 1 B.C., and do not skip zero
1314 as traditional Gregorian years do; for example, the year number
1315 @minus{}37 represents the Gregorian year 38 B.C@.
1316
1317 @defun decode-time &optional time
1318 This function converts a time value into calendrical information. If
1319 you don't specify @var{time}, it decodes the current time. The return
1320 value is a list of nine elements, as follows:
1321
1322 @example
1323 (@var{seconds} @var{minutes} @var{hour} @var{day} @var{month} @var{year} @var{dow} @var{dst} @var{zone})
1324 @end example
1325
1326 Here is what the elements mean:
1327
1328 @table @var
1329 @item seconds
1330 The number of seconds past the minute, as an integer between 0 and 59.
1331 On some operating systems, this is 60 for leap seconds.
1332 @item minutes
1333 The number of minutes past the hour, as an integer between 0 and 59.
1334 @item hour
1335 The hour of the day, as an integer between 0 and 23.
1336 @item day
1337 The day of the month, as an integer between 1 and 31.
1338 @item month
1339 The month of the year, as an integer between 1 and 12.
1340 @item year
1341 The year, an integer typically greater than 1900.
1342 @item dow
1343 The day of week, as an integer between 0 and 6, where 0 stands for
1344 Sunday.
1345 @item dst
1346 @code{t} if daylight saving time is effect, otherwise @code{nil}.
1347 @item zone
1348 An integer indicating the time zone, as the number of seconds east of
1349 Greenwich.
1350 @end table
1351
1352 @strong{Common Lisp Note:} Common Lisp has different meanings for
1353 @var{dow} and @var{zone}.
1354 @end defun
1355
1356 @defun encode-time seconds minutes hour day month year &optional zone
1357 This function is the inverse of @code{decode-time}. It converts seven
1358 items of calendrical data into a time value. For the meanings of the
1359 arguments, see the table above under @code{decode-time}.
1360
1361 Year numbers less than 100 are not treated specially. If you want them
1362 to stand for years above 1900, or years above 2000, you must alter them
1363 yourself before you call @code{encode-time}.
1364
1365 The optional argument @var{zone} defaults to the current time zone and
1366 its daylight saving time rules. If specified, it can be either a list
1367 (as you would get from @code{current-time-zone}), a string as in the
1368 @env{TZ} environment variable, @code{t} for Universal Time, or an
1369 integer (as you would get from @code{decode-time}). The specified
1370 zone is used without any further alteration for daylight saving time.
1371
1372 If you pass more than seven arguments to @code{encode-time}, the first
1373 six are used as @var{seconds} through @var{year}, the last argument is
1374 used as @var{zone}, and the arguments in between are ignored. This
1375 feature makes it possible to use the elements of a list returned by
1376 @code{decode-time} as the arguments to @code{encode-time}, like this:
1377
1378 @example
1379 (apply 'encode-time (decode-time @dots{}))
1380 @end example
1381
1382 You can perform simple date arithmetic by using out-of-range values for
1383 the @var{seconds}, @var{minutes}, @var{hour}, @var{day}, and @var{month}
1384 arguments; for example, day 0 means the day preceding the given month.
1385
1386 The operating system puts limits on the range of possible time values;
1387 if you try to encode a time that is out of range, an error results.
1388 For instance, years before 1970 do not work on some systems;
1389 on others, years as early as 1901 do work.
1390 @end defun
1391
1392 @node Time Parsing
1393 @section Parsing and Formatting Times
1394
1395 These functions convert time values to text in a string, and vice versa.
1396 Time values are lists of two to four integers (@pxref{Time of Day}).
1397
1398 @defun date-to-time string
1399 This function parses the time-string @var{string} and returns the
1400 corresponding time value.
1401 @end defun
1402
1403 @defun format-time-string format-string &optional time universal
1404 This function converts @var{time} (or the current time, if @var{time} is
1405 omitted) to a string according to @var{format-string}. The argument
1406 @var{format-string} may contain @samp{%}-sequences which say to
1407 substitute parts of the time. Here is a table of what the
1408 @samp{%}-sequences mean:
1409
1410 @table @samp
1411 @item %a
1412 This stands for the abbreviated name of the day of week.
1413 @item %A
1414 This stands for the full name of the day of week.
1415 @item %b
1416 This stands for the abbreviated name of the month.
1417 @item %B
1418 This stands for the full name of the month.
1419 @item %c
1420 This is a synonym for @samp{%x %X}.
1421 @item %C
1422 This has a locale-specific meaning. In the default locale (named C), it
1423 is equivalent to @samp{%A, %B %e, %Y}.
1424 @item %d
1425 This stands for the day of month, zero-padded.
1426 @item %D
1427 This is a synonym for @samp{%m/%d/%y}.
1428 @item %e
1429 This stands for the day of month, blank-padded.
1430 @item %h
1431 This is a synonym for @samp{%b}.
1432 @item %H
1433 This stands for the hour (00--23).
1434 @item %I
1435 This stands for the hour (01--12).
1436 @item %j
1437 This stands for the day of the year (001--366).
1438 @item %k
1439 This stands for the hour (0--23), blank padded.
1440 @item %l
1441 This stands for the hour (1--12), blank padded.
1442 @item %m
1443 This stands for the month (01--12).
1444 @item %M
1445 This stands for the minute (00--59).
1446 @item %n
1447 This stands for a newline.
1448 @item %N
1449 This stands for the nanoseconds (000000000--999999999). To ask for
1450 fewer digits, use @samp{%3N} for milliseconds, @samp{%6N} for
1451 microseconds, etc. Any excess digits are discarded, without rounding.
1452 @item %p
1453 This stands for @samp{AM} or @samp{PM}, as appropriate.
1454 @item %r
1455 This is a synonym for @samp{%I:%M:%S %p}.
1456 @item %R
1457 This is a synonym for @samp{%H:%M}.
1458 @item %S
1459 This stands for the seconds (00--59).
1460 @item %t
1461 This stands for a tab character.
1462 @item %T
1463 This is a synonym for @samp{%H:%M:%S}.
1464 @item %U
1465 This stands for the week of the year (01--52), assuming that weeks
1466 start on Sunday.
1467 @item %w
1468 This stands for the numeric day of week (0--6). Sunday is day 0.
1469 @item %W
1470 This stands for the week of the year (01--52), assuming that weeks
1471 start on Monday.
1472 @item %x
1473 This has a locale-specific meaning. In the default locale (named
1474 @samp{C}), it is equivalent to @samp{%D}.
1475 @item %X
1476 This has a locale-specific meaning. In the default locale (named
1477 @samp{C}), it is equivalent to @samp{%T}.
1478 @item %y
1479 This stands for the year without century (00--99).
1480 @item %Y
1481 This stands for the year with century.
1482 @item %Z
1483 This stands for the time zone abbreviation (e.g., @samp{EST}).
1484 @item %z
1485 This stands for the time zone numerical offset (e.g., @samp{-0500}).
1486 @end table
1487
1488 You can also specify the field width and type of padding for any of
1489 these @samp{%}-sequences. This works as in @code{printf}: you write
1490 the field width as digits in the middle of a @samp{%}-sequences. If you
1491 start the field width with @samp{0}, it means to pad with zeros. If you
1492 start the field width with @samp{_}, it means to pad with spaces.
1493
1494 For example, @samp{%S} specifies the number of seconds since the minute;
1495 @samp{%03S} means to pad this with zeros to 3 positions, @samp{%_3S} to
1496 pad with spaces to 3 positions. Plain @samp{%3S} pads with zeros,
1497 because that is how @samp{%S} normally pads to two positions.
1498
1499 The characters @samp{E} and @samp{O} act as modifiers when used between
1500 @samp{%} and one of the letters in the table above. @samp{E} specifies
1501 using the current locale's ``alternative'' version of the date and time.
1502 In a Japanese locale, for example, @code{%Ex} might yield a date format
1503 based on the Japanese Emperors' reigns. @samp{E} is allowed in
1504 @samp{%Ec}, @samp{%EC}, @samp{%Ex}, @samp{%EX}, @samp{%Ey}, and
1505 @samp{%EY}.
1506
1507 @samp{O} means to use the current locale's ``alternative''
1508 representation of numbers, instead of the ordinary decimal digits. This
1509 is allowed with most letters, all the ones that output numbers.
1510
1511 If @var{universal} is non-@code{nil}, that means to describe the time as
1512 Universal Time; @code{nil} means describe it using what Emacs believes
1513 is the local time zone (see @code{current-time-zone}).
1514
1515 This function uses the C library function @code{strftime}
1516 (@pxref{Formatting Calendar Time,,, libc, The GNU C Library Reference
1517 Manual}) to do most of the work. In order to communicate with that
1518 function, it first encodes its argument using the coding system
1519 specified by @code{locale-coding-system} (@pxref{Locales}); after
1520 @code{strftime} returns the resulting string,
1521 @code{format-time-string} decodes the string using that same coding
1522 system.
1523 @end defun
1524
1525 @defun seconds-to-time seconds
1526 This function converts @var{seconds}, a floating point number of
1527 seconds since the epoch, to a time value and returns that. To perform
1528 the inverse conversion, use @code{float-time} (@pxref{Time of Day}).
1529 @end defun
1530
1531 @defun format-seconds format-string seconds
1532 This function converts its argument @var{seconds} into a string of
1533 years, days, hours, etc., according to @var{format-string}. The
1534 argument @var{format-string} may contain @samp{%}-sequences which
1535 control the conversion. Here is a table of what the
1536 @samp{%}-sequences mean:
1537
1538 @table @samp
1539 @item %y
1540 @itemx %Y
1541 The integer number of 365-day years.
1542 @item %d
1543 @itemx %D
1544 The integer number of days.
1545 @item %h
1546 @itemx %H
1547 The integer number of hours.
1548 @item %m
1549 @itemx %M
1550 The integer number of minutes.
1551 @item %s
1552 @itemx %S
1553 The integer number of seconds.
1554 @item %z
1555 Non-printing control flag. When it is used, other specifiers must be
1556 given in the order of decreasing size, i.e., years before days, hours
1557 before minutes, etc. Nothing will be produced in the result string to
1558 the left of @samp{%z} until the first non-zero conversion is
1559 encountered. For example, the default format used by
1560 @code{emacs-uptime} (@pxref{Processor Run Time, emacs-uptime})
1561 @w{@code{"%Y, %D, %H, %M, %z%S"}} means that the number of seconds
1562 will always be produced, but years, days, hours, and minutes will only
1563 be shown if they are non-zero.
1564 @item %%
1565 Produces a literal @samp{%}.
1566 @end table
1567
1568 Upper-case format sequences produce the units in addition to the
1569 numbers, lower-case formats produce only the numbers.
1570
1571 You can also specify the field width by following the @samp{%} with a
1572 number; shorter numbers will be padded with blanks. An optional
1573 period before the width requests zero-padding instead. For example,
1574 @code{"%.3Y"} might produce @code{"004 years"}.
1575
1576 @emph{Warning:} This function works only with values of @var{seconds}
1577 that don't exceed @code{most-positive-fixnum} (@pxref{Integer Basics,
1578 most-positive-fixnum}).
1579 @end defun
1580
1581 @node Processor Run Time
1582 @section Processor Run time
1583 @cindex processor run time
1584 @cindex Emacs process run time
1585
1586 Emacs provides several functions and primitives that return time,
1587 both elapsed and processor time, used by the Emacs process.
1588
1589 @deffn Command emacs-uptime &optional format
1590 @cindex uptime of Emacs
1591 This function returns a string representing the Emacs
1592 @dfn{uptime}---the elapsed wall-clock time this instance of Emacs is
1593 running. The string is formatted by @code{format-seconds} according
1594 to the optional argument @var{format}. For the available format
1595 descriptors, see @ref{Time Parsing, format-seconds}. If @var{format}
1596 is @code{nil} or omitted, it defaults to @code{"%Y, %D, %H, %M,
1597 %z%S"}.
1598
1599 When called interactively, it prints the uptime in the echo area.
1600 @end deffn
1601
1602 @defun get-internal-run-time
1603 This function returns the processor run time used by Emacs as a list
1604 of four integers: @code{(@var{high} @var{low} @var{microsec}
1605 @var{picosec})}, using the same format as @code{current-time}
1606 (@pxref{Time of Day}).
1607
1608 Note that the time returned by this function excludes the time Emacs
1609 was not using the processor, and if the Emacs process has several
1610 threads, the returned value is the sum of the processor times used up
1611 by all Emacs threads.
1612
1613 If the system doesn't provide a way to determine the processor run
1614 time, @code{get-internal-run-time} returns the same time as
1615 @code{current-time}.
1616 @end defun
1617
1618 @deffn Command emacs-init-time
1619 This function returns the duration of the Emacs initialization
1620 (@pxref{Startup Summary}) in seconds, as a string. When called
1621 interactively, it prints the duration in the echo area.
1622 @end deffn
1623
1624 @node Time Calculations
1625 @section Time Calculations
1626
1627 These functions perform calendrical computations using time values
1628 (the kind of list that @code{current-time} returns).
1629
1630 @defun time-less-p t1 t2
1631 This returns @code{t} if time value @var{t1} is less than time value
1632 @var{t2}.
1633 @end defun
1634
1635 @defun time-subtract t1 t2
1636 This returns the time difference @var{t1} @minus{} @var{t2} between
1637 two time values, in the same format as a time value.
1638 @end defun
1639
1640 @defun time-add t1 t2
1641 This returns the sum of two time values, one of which ought to
1642 represent a time difference rather than a point in time.
1643 Here is how to add a number of seconds to a time value:
1644
1645 @example
1646 (time-add @var{time} (seconds-to-time @var{seconds}))
1647 @end example
1648 @end defun
1649
1650 @defun time-to-days time
1651 This function returns the number of days between the beginning of year
1652 1 and @var{time}.
1653 @end defun
1654
1655 @defun time-to-day-in-year time
1656 This returns the day number within the year corresponding to @var{time}.
1657 @end defun
1658
1659 @defun date-leap-year-p year
1660 This function returns @code{t} if @var{year} is a leap year.
1661 @end defun
1662
1663 @node Timers
1664 @section Timers for Delayed Execution
1665 @cindex timer
1666
1667 You can set up a @dfn{timer} to call a function at a specified
1668 future time or after a certain length of idleness.
1669
1670 Emacs cannot run timers at any arbitrary point in a Lisp program; it
1671 can run them only when Emacs could accept output from a subprocess:
1672 namely, while waiting or inside certain primitive functions such as
1673 @code{sit-for} or @code{read-event} which @emph{can} wait. Therefore, a
1674 timer's execution may be delayed if Emacs is busy. However, the time of
1675 execution is very precise if Emacs is idle.
1676
1677 Emacs binds @code{inhibit-quit} to @code{t} before calling the timer
1678 function, because quitting out of many timer functions can leave
1679 things in an inconsistent state. This is normally unproblematical
1680 because most timer functions don't do a lot of work. Indeed, for a
1681 timer to call a function that takes substantial time to run is likely
1682 to be annoying. If a timer function needs to allow quitting, it
1683 should use @code{with-local-quit} (@pxref{Quitting}). For example, if
1684 a timer function calls @code{accept-process-output} to receive output
1685 from an external process, that call should be wrapped inside
1686 @code{with-local-quit}, to ensure that @kbd{C-g} works if the external
1687 process hangs.
1688
1689 It is usually a bad idea for timer functions to alter buffer
1690 contents. When they do, they usually should call @code{undo-boundary}
1691 both before and after changing the buffer, to separate the timer's
1692 changes from user commands' changes and prevent a single undo entry
1693 from growing to be quite large.
1694
1695 Timer functions should also avoid calling functions that cause Emacs
1696 to wait, such as @code{sit-for} (@pxref{Waiting}). This can lead to
1697 unpredictable effects, since other timers (or even the same timer) can
1698 run while waiting. If a timer function needs to perform an action
1699 after a certain time has elapsed, it can do this by scheduling a new
1700 timer.
1701
1702 If a timer function calls functions that can change the match data,
1703 it should save and restore the match data. @xref{Saving Match Data}.
1704
1705 @deffn Command run-at-time time repeat function &rest args
1706 This sets up a timer that calls the function @var{function} with
1707 arguments @var{args} at time @var{time}. If @var{repeat} is a number
1708 (integer or floating point), the timer is scheduled to run again every
1709 @var{repeat} seconds after @var{time}. If @var{repeat} is @code{nil},
1710 the timer runs only once.
1711
1712 @var{time} may specify an absolute or a relative time.
1713
1714 Absolute times may be specified using a string with a limited variety
1715 of formats, and are taken to be times @emph{today}, even if already in
1716 the past. The recognized forms are @samp{@var{xxxx}},
1717 @samp{@var{x}:@var{xx}}, or @samp{@var{xx}:@var{xx}} (military time),
1718 and @samp{@var{xx}am}, @samp{@var{xx}AM}, @samp{@var{xx}pm},
1719 @samp{@var{xx}PM}, @samp{@var{xx}:@var{xx}am},
1720 @samp{@var{xx}:@var{xx}AM}, @samp{@var{xx}:@var{xx}pm}, or
1721 @samp{@var{xx}:@var{xx}PM}. A period can be used instead of a colon
1722 to separate the hour and minute parts.
1723
1724 To specify a relative time as a string, use numbers followed by units.
1725 For example:
1726
1727 @table @samp
1728 @item 1 min
1729 denotes 1 minute from now.
1730 @item 1 min 5 sec
1731 denotes 65 seconds from now.
1732 @item 1 min 2 sec 3 hour 4 day 5 week 6 fortnight 7 month 8 year
1733 denotes exactly 103 months, 123 days, and 10862 seconds from now.
1734 @end table
1735
1736 For relative time values, Emacs considers a month to be exactly thirty
1737 days, and a year to be exactly 365.25 days.
1738
1739 Not all convenient formats are strings. If @var{time} is a number
1740 (integer or floating point), that specifies a relative time measured in
1741 seconds. The result of @code{encode-time} can also be used to specify
1742 an absolute value for @var{time}.
1743
1744 In most cases, @var{repeat} has no effect on when @emph{first} call
1745 takes place---@var{time} alone specifies that. There is one exception:
1746 if @var{time} is @code{t}, then the timer runs whenever the time is a
1747 multiple of @var{repeat} seconds after the epoch. This is useful for
1748 functions like @code{display-time}.
1749
1750 The function @code{run-at-time} returns a timer value that identifies
1751 the particular scheduled future action. You can use this value to call
1752 @code{cancel-timer} (see below).
1753 @end deffn
1754
1755 A repeating timer nominally ought to run every @var{repeat} seconds,
1756 but remember that any invocation of a timer can be late. Lateness of
1757 one repetition has no effect on the scheduled time of the next
1758 repetition. For instance, if Emacs is busy computing for long enough
1759 to cover three scheduled repetitions of the timer, and then starts to
1760 wait, it will immediately call the timer function three times in
1761 immediate succession (presuming no other timers trigger before or
1762 between them). If you want a timer to run again no less than @var{n}
1763 seconds after the last invocation, don't use the @var{repeat} argument.
1764 Instead, the timer function should explicitly reschedule the timer.
1765
1766 @defopt timer-max-repeats
1767 This variable's value specifies the maximum number of times to repeat
1768 calling a timer function in a row, when many previously scheduled
1769 calls were unavoidably delayed.
1770 @end defopt
1771
1772 @defmac with-timeout (seconds timeout-forms@dots{}) body@dots{}
1773 Execute @var{body}, but give up after @var{seconds} seconds. If
1774 @var{body} finishes before the time is up, @code{with-timeout} returns
1775 the value of the last form in @var{body}. If, however, the execution of
1776 @var{body} is cut short by the timeout, then @code{with-timeout}
1777 executes all the @var{timeout-forms} and returns the value of the last
1778 of them.
1779
1780 This macro works by setting a timer to run after @var{seconds} seconds. If
1781 @var{body} finishes before that time, it cancels the timer. If the
1782 timer actually runs, it terminates execution of @var{body}, then
1783 executes @var{timeout-forms}.
1784
1785 Since timers can run within a Lisp program only when the program calls a
1786 primitive that can wait, @code{with-timeout} cannot stop executing
1787 @var{body} while it is in the midst of a computation---only when it
1788 calls one of those primitives. So use @code{with-timeout} only with a
1789 @var{body} that waits for input, not one that does a long computation.
1790 @end defmac
1791
1792 The function @code{y-or-n-p-with-timeout} provides a simple way to use
1793 a timer to avoid waiting too long for an answer. @xref{Yes-or-No
1794 Queries}.
1795
1796 @defun cancel-timer timer
1797 This cancels the requested action for @var{timer}, which should be a
1798 timer---usually, one previously returned by @code{run-at-time} or
1799 @code{run-with-idle-timer}. This cancels the effect of that call to
1800 one of these functions; the arrival of the specified time will not
1801 cause anything special to happen.
1802 @end defun
1803
1804 @node Idle Timers
1805 @section Idle Timers
1806
1807 Here is how to set up a timer that runs when Emacs is idle for a
1808 certain length of time. Aside from how to set them up, idle timers
1809 work just like ordinary timers.
1810
1811 @deffn Command run-with-idle-timer secs repeat function &rest args
1812 Set up a timer which runs the next time Emacs is idle for @var{secs}
1813 seconds. The value of @var{secs} may be an integer or a floating
1814 point number; a value of the type returned by @code{current-idle-time}
1815 is also allowed.
1816
1817 If @var{repeat} is @code{nil}, the timer runs just once, the first time
1818 Emacs remains idle for a long enough time. More often @var{repeat} is
1819 non-@code{nil}, which means to run the timer @emph{each time} Emacs
1820 remains idle for @var{secs} seconds.
1821
1822 The function @code{run-with-idle-timer} returns a timer value which you
1823 can use in calling @code{cancel-timer} (@pxref{Timers}).
1824 @end deffn
1825
1826 @cindex idleness
1827 Emacs becomes @dfn{idle} when it starts waiting for user input, and
1828 it remains idle until the user provides some input. If a timer is set
1829 for five seconds of idleness, it runs approximately five seconds after
1830 Emacs first becomes idle. Even if @var{repeat} is non-@code{nil},
1831 this timer will not run again as long as Emacs remains idle, because
1832 the duration of idleness will continue to increase and will not go
1833 down to five seconds again.
1834
1835 Emacs can do various things while idle: garbage collect, autosave or
1836 handle data from a subprocess. But these interludes during idleness do
1837 not interfere with idle timers, because they do not reset the clock of
1838 idleness to zero. An idle timer set for 600 seconds will run when ten
1839 minutes have elapsed since the last user command was finished, even if
1840 subprocess output has been accepted thousands of times within those ten
1841 minutes, and even if there have been garbage collections and autosaves.
1842
1843 When the user supplies input, Emacs becomes non-idle while executing the
1844 input. Then it becomes idle again, and all the idle timers that are
1845 set up to repeat will subsequently run another time, one by one.
1846
1847 Do not write an idle timer function containing a loop which does a
1848 certain amount of processing each time around, and exits when
1849 @code{(input-pending-p)} is non-@code{nil}. This approach seems very
1850 natural but has two problems:
1851
1852 @itemize
1853 @item
1854 It blocks out all process output (since Emacs accepts process output
1855 only while waiting).
1856
1857 @item
1858 It blocks out any idle timers that ought to run during that time.
1859 @end itemize
1860
1861 @noindent
1862 Similarly, do not write an idle timer function that sets up another
1863 idle timer (including the same idle timer) with @var{secs} argument
1864 less than or equal to the current idleness time. Such a timer will
1865 run almost immediately, and continue running again and again, instead
1866 of waiting for the next time Emacs becomes idle. The correct approach
1867 is to reschedule with an appropriate increment of the current value of
1868 the idleness time, as described below.
1869
1870 @defun current-idle-time
1871 If Emacs is idle, this function returns the length of time Emacs has
1872 been idle, as a list of four integers: @code{(@var{sec-high}
1873 @var{sec-low} @var{microsec} @var{picosec})}, using the same format as
1874 @code{current-time} (@pxref{Time of Day}).
1875
1876 When Emacs is not idle, @code{current-idle-time} returns @code{nil}.
1877 This is a convenient way to test whether Emacs is idle.
1878 @end defun
1879
1880 The main use of @code{current-idle-time} is when an idle timer
1881 function wants to ``take a break'' for a while. It can set up another
1882 idle timer to call the same function again, after a few seconds more
1883 idleness. Here's an example:
1884
1885 @example
1886 (defvar my-resume-timer nil
1887 "Timer for `my-timer-function' to reschedule itself, or nil.")
1888
1889 (defun my-timer-function ()
1890 ;; @r{If the user types a command while @code{my-resume-timer}}
1891 ;; @r{is active, the next time this function is called from}
1892 ;; @r{its main idle timer, deactivate @code{my-resume-timer}.}
1893 (when my-resume-timer
1894 (cancel-timer my-resume-timer))
1895 ...@var{do the work for a while}...
1896 (when @var{taking-a-break}
1897 (setq my-resume-timer
1898 (run-with-idle-timer
1899 ;; Compute an idle time @var{break-length}
1900 ;; more than the current value.
1901 (time-add (current-idle-time)
1902 (seconds-to-time @var{break-length}))
1903 nil
1904 'my-timer-function))))
1905 @end example
1906
1907 @node Terminal Input
1908 @section Terminal Input
1909 @cindex terminal input
1910
1911 This section describes functions and variables for recording or
1912 manipulating terminal input. See @ref{Display}, for related
1913 functions.
1914
1915 @menu
1916 * Input Modes:: Options for how input is processed.
1917 * Recording Input:: Saving histories of recent or all input events.
1918 @end menu
1919
1920 @node Input Modes
1921 @subsection Input Modes
1922 @cindex input modes
1923 @cindex terminal input modes
1924
1925 @defun set-input-mode interrupt flow meta &optional quit-char
1926 This function sets the mode for reading keyboard input. If
1927 @var{interrupt} is non-@code{nil}, then Emacs uses input interrupts.
1928 If it is @code{nil}, then it uses @sc{cbreak} mode. The default
1929 setting is system-dependent. Some systems always use @sc{cbreak} mode
1930 regardless of what is specified.
1931
1932 When Emacs communicates directly with X, it ignores this argument and
1933 uses interrupts if that is the way it knows how to communicate.
1934
1935 If @var{flow} is non-@code{nil}, then Emacs uses @sc{xon/xoff}
1936 (@kbd{C-q}, @kbd{C-s}) flow control for output to the terminal. This
1937 has no effect except in @sc{cbreak} mode.
1938
1939 The argument @var{meta} controls support for input character codes
1940 above 127. If @var{meta} is @code{t}, Emacs converts characters with
1941 the 8th bit set into Meta characters. If @var{meta} is @code{nil},
1942 Emacs disregards the 8th bit; this is necessary when the terminal uses
1943 it as a parity bit. If @var{meta} is neither @code{t} nor @code{nil},
1944 Emacs uses all 8 bits of input unchanged. This is good for terminals
1945 that use 8-bit character sets.
1946
1947 If @var{quit-char} is non-@code{nil}, it specifies the character to
1948 use for quitting. Normally this character is @kbd{C-g}.
1949 @xref{Quitting}.
1950 @end defun
1951
1952 The @code{current-input-mode} function returns the input mode settings
1953 Emacs is currently using.
1954
1955 @defun current-input-mode
1956 This function returns the current mode for reading keyboard input. It
1957 returns a list, corresponding to the arguments of @code{set-input-mode},
1958 of the form @code{(@var{interrupt} @var{flow} @var{meta} @var{quit})} in
1959 which:
1960 @table @var
1961 @item interrupt
1962 is non-@code{nil} when Emacs is using interrupt-driven input. If
1963 @code{nil}, Emacs is using @sc{cbreak} mode.
1964 @item flow
1965 is non-@code{nil} if Emacs uses @sc{xon/xoff} (@kbd{C-q}, @kbd{C-s})
1966 flow control for output to the terminal. This value is meaningful only
1967 when @var{interrupt} is @code{nil}.
1968 @item meta
1969 is @code{t} if Emacs treats the eighth bit of input characters as
1970 the meta bit; @code{nil} means Emacs clears the eighth bit of every
1971 input character; any other value means Emacs uses all eight bits as the
1972 basic character code.
1973 @item quit
1974 is the character Emacs currently uses for quitting, usually @kbd{C-g}.
1975 @end table
1976 @end defun
1977
1978 @node Recording Input
1979 @subsection Recording Input
1980 @cindex recording input
1981
1982 @defun recent-keys
1983 This function returns a vector containing the last 300 input events from
1984 the keyboard or mouse. All input events are included, whether or not
1985 they were used as parts of key sequences. Thus, you always get the last
1986 300 input events, not counting events generated by keyboard macros.
1987 (These are excluded because they are less interesting for debugging; it
1988 should be enough to see the events that invoked the macros.)
1989
1990 A call to @code{clear-this-command-keys} (@pxref{Command Loop Info})
1991 causes this function to return an empty vector immediately afterward.
1992 @end defun
1993
1994 @deffn Command open-dribble-file filename
1995 @cindex dribble file
1996 This function opens a @dfn{dribble file} named @var{filename}. When a
1997 dribble file is open, each input event from the keyboard or mouse (but
1998 not those from keyboard macros) is written in that file. A
1999 non-character event is expressed using its printed representation
2000 surrounded by @samp{<@dots{}>}.
2001
2002 You close the dribble file by calling this function with an argument
2003 of @code{nil}.
2004
2005 This function is normally used to record the input necessary to
2006 trigger an Emacs bug, for the sake of a bug report.
2007
2008 @example
2009 @group
2010 (open-dribble-file "~/dribble")
2011 @result{} nil
2012 @end group
2013 @end example
2014 @end deffn
2015
2016 See also the @code{open-termscript} function (@pxref{Terminal Output}).
2017
2018 @node Terminal Output
2019 @section Terminal Output
2020 @cindex terminal output
2021
2022 The terminal output functions send output to a text terminal, or keep
2023 track of output sent to the terminal. The variable @code{baud-rate}
2024 tells you what Emacs thinks is the output speed of the terminal.
2025
2026 @defopt baud-rate
2027 This variable's value is the output speed of the terminal, as far as
2028 Emacs knows. Setting this variable does not change the speed of actual
2029 data transmission, but the value is used for calculations such as
2030 padding.
2031
2032 It also affects decisions about whether to scroll part of the
2033 screen or repaint on text terminals. @xref{Forcing Redisplay},
2034 for the corresponding functionality on graphical terminals.
2035
2036 The value is measured in baud.
2037 @end defopt
2038
2039 If you are running across a network, and different parts of the
2040 network work at different baud rates, the value returned by Emacs may be
2041 different from the value used by your local terminal. Some network
2042 protocols communicate the local terminal speed to the remote machine, so
2043 that Emacs and other programs can get the proper value, but others do
2044 not. If Emacs has the wrong value, it makes decisions that are less
2045 than optimal. To fix the problem, set @code{baud-rate}.
2046
2047 @defun send-string-to-terminal string &optional terminal
2048 This function sends @var{string} to @var{terminal} without alteration.
2049 Control characters in @var{string} have terminal-dependent effects.
2050 This function operates only on text terminals. @var{terminal} may be
2051 a terminal object, a frame, or @code{nil} for the selected frame's
2052 terminal. In batch mode, @var{string} is sent to @code{stdout} when
2053 @var{terminal} is @code{nil}.
2054
2055 One use of this function is to define function keys on terminals that
2056 have downloadable function key definitions. For example, this is how (on
2057 certain terminals) to define function key 4 to move forward four
2058 characters (by transmitting the characters @kbd{C-u C-f} to the
2059 computer):
2060
2061 @example
2062 @group
2063 (send-string-to-terminal "\eF4\^U\^F")
2064 @result{} nil
2065 @end group
2066 @end example
2067 @end defun
2068
2069 @deffn Command open-termscript filename
2070 @cindex termscript file
2071 This function is used to open a @dfn{termscript file} that will record
2072 all the characters sent by Emacs to the terminal. It returns
2073 @code{nil}. Termscript files are useful for investigating problems
2074 where Emacs garbles the screen, problems that are due to incorrect
2075 Termcap entries or to undesirable settings of terminal options more
2076 often than to actual Emacs bugs. Once you are certain which characters
2077 were actually output, you can determine reliably whether they correspond
2078 to the Termcap specifications in use.
2079
2080 @example
2081 @group
2082 (open-termscript "../junk/termscript")
2083 @result{} nil
2084 @end group
2085 @end example
2086
2087 You close the termscript file by calling this function with an
2088 argument of @code{nil}.
2089
2090 See also @code{open-dribble-file} in @ref{Recording Input}.
2091 @end deffn
2092
2093 @node Sound Output
2094 @section Sound Output
2095 @cindex sound
2096
2097 To play sound using Emacs, use the function @code{play-sound}. Only
2098 certain systems are supported; if you call @code{play-sound} on a
2099 system which cannot really do the job, it gives an error.
2100
2101 @c FIXME: Add indexes for Au and WAV? --xfq
2102 The sound must be stored as a file in RIFF-WAVE format (@samp{.wav})
2103 or Sun Audio format (@samp{.au}).
2104
2105 @defun play-sound sound
2106 This function plays a specified sound. The argument, @var{sound}, has
2107 the form @code{(sound @var{properties}...)}, where the @var{properties}
2108 consist of alternating keywords (particular symbols recognized
2109 specially) and values corresponding to them.
2110
2111 Here is a table of the keywords that are currently meaningful in
2112 @var{sound}, and their meanings:
2113
2114 @table @code
2115 @item :file @var{file}
2116 This specifies the file containing the sound to play.
2117 If the file name is not absolute, it is expanded against
2118 the directory @code{data-directory}.
2119
2120 @item :data @var{data}
2121 This specifies the sound to play without need to refer to a file. The
2122 value, @var{data}, should be a string containing the same bytes as a
2123 sound file. We recommend using a unibyte string.
2124
2125 @item :volume @var{volume}
2126 This specifies how loud to play the sound. It should be a number in the
2127 range of 0 to 1. The default is to use whatever volume has been
2128 specified before.
2129
2130 @item :device @var{device}
2131 This specifies the system device on which to play the sound, as a
2132 string. The default device is system-dependent.
2133 @end table
2134
2135 Before actually playing the sound, @code{play-sound}
2136 calls the functions in the list @code{play-sound-functions}.
2137 Each function is called with one argument, @var{sound}.
2138 @end defun
2139
2140 @deffn Command play-sound-file file &optional volume device
2141 This function is an alternative interface to playing a sound @var{file}
2142 specifying an optional @var{volume} and @var{device}.
2143 @end deffn
2144
2145 @defvar play-sound-functions
2146 A list of functions to be called before playing a sound. Each function
2147 is called with one argument, a property list that describes the sound.
2148 @end defvar
2149
2150 @node X11 Keysyms
2151 @section Operating on X11 Keysyms
2152 @cindex X11 keysyms
2153
2154 To define system-specific X11 keysyms, set the variable
2155 @code{system-key-alist}.
2156
2157 @defvar system-key-alist
2158 This variable's value should be an alist with one element for each
2159 system-specific keysym. Each element has the form @code{(@var{code}
2160 . @var{symbol})}, where @var{code} is the numeric keysym code (not
2161 including the ``vendor specific'' bit,
2162 @ifnottex
2163 -2**28),
2164 @end ifnottex
2165 @tex
2166 $-2^{28}$),
2167 @end tex
2168 and @var{symbol} is the name for the function key.
2169
2170 For example @code{(168 . mute-acute)} defines a system-specific key (used
2171 by HP X servers) whose numeric code is
2172 @ifnottex
2173 -2**28
2174 @end ifnottex
2175 @tex
2176 $-2^{28}$
2177 @end tex
2178 + 168.
2179
2180 It is not crucial to exclude from the alist the keysyms of other X
2181 servers; those do no harm, as long as they don't conflict with the ones
2182 used by the X server actually in use.
2183
2184 The variable is always local to the current terminal, and cannot be
2185 buffer-local. @xref{Multiple Terminals}.
2186 @end defvar
2187
2188 You can specify which keysyms Emacs should use for the Meta, Alt, Hyper, and Super modifiers by setting these variables:
2189
2190 @defvar x-alt-keysym
2191 @defvarx x-meta-keysym
2192 @defvarx x-hyper-keysym
2193 @defvarx x-super-keysym
2194 The name of the keysym that should stand for the Alt modifier
2195 (respectively, for Meta, Hyper, and Super). For example, here is
2196 how to swap the Meta and Alt modifiers within Emacs:
2197 @lisp
2198 (setq x-alt-keysym 'meta)
2199 (setq x-meta-keysym 'alt)
2200 @end lisp
2201 @end defvar
2202
2203 @node Batch Mode
2204 @section Batch Mode
2205 @cindex batch mode
2206
2207 The command-line option @samp{-batch} causes Emacs to run
2208 noninteractively. In this mode, Emacs does not read commands from the
2209 terminal, it does not alter the terminal modes, and it does not expect
2210 to be outputting to an erasable screen. The idea is that you specify
2211 Lisp programs to run; when they are finished, Emacs should exit. The
2212 way to specify the programs to run is with @samp{-l @var{file}}, which
2213 loads the library named @var{file}, or @samp{-f @var{function}}, which
2214 calls @var{function} with no arguments, or @samp{--eval @var{form}}.
2215
2216 Any Lisp program output that would normally go to the echo area,
2217 either using @code{message}, or using @code{prin1}, etc., with @code{t}
2218 as the stream, goes instead to Emacs's standard error descriptor when
2219 in batch mode. Similarly, input that would normally come from the
2220 minibuffer is read from the standard input descriptor.
2221 Thus, Emacs behaves much like a noninteractive
2222 application program. (The echo area output that Emacs itself normally
2223 generates, such as command echoing, is suppressed entirely.)
2224
2225 @defvar noninteractive
2226 This variable is non-@code{nil} when Emacs is running in batch mode.
2227 @end defvar
2228
2229 @node Session Management
2230 @section Session Management
2231 @cindex session manager
2232
2233 Emacs supports the X Session Management Protocol, which is used to
2234 suspend and restart applications. In the X Window System, a program
2235 called the @dfn{session manager} is responsible for keeping track of
2236 the applications that are running. When the X server shuts down, the
2237 session manager asks applications to save their state, and delays the
2238 actual shutdown until they respond. An application can also cancel
2239 the shutdown.
2240
2241 When the session manager restarts a suspended session, it directs
2242 these applications to individually reload their saved state. It does
2243 this by specifying a special command-line argument that says what
2244 saved session to restore. For Emacs, this argument is @samp{--smid
2245 @var{session}}.
2246
2247 @defvar emacs-save-session-functions
2248 @cindex session file
2249 Emacs supports saving state via a hook called
2250 @code{emacs-save-session-functions}. Emacs runs this hook when the
2251 session manager tells it that the window system is shutting down. The
2252 functions are called with no arguments, and with the current buffer
2253 set to a temporary buffer. Each function can use @code{insert} to add
2254 Lisp code to this buffer. At the end, Emacs saves the buffer in a
2255 file, called the @dfn{session file}.
2256
2257 @findex emacs-session-restore
2258 Subsequently, when the session manager restarts Emacs, it loads the
2259 session file automatically (@pxref{Loading}). This is performed by a
2260 function named @code{emacs-session-restore}, which is called during
2261 startup. @xref{Startup Summary}.
2262
2263 If a function in @code{emacs-save-session-functions} returns
2264 non-@code{nil}, Emacs tells the session manager to cancel the
2265 shutdown.
2266 @end defvar
2267
2268 Here is an example that just inserts some text into @file{*scratch*} when
2269 Emacs is restarted by the session manager.
2270
2271 @example
2272 @group
2273 (add-hook 'emacs-save-session-functions 'save-yourself-test)
2274 @end group
2275
2276 @group
2277 (defun save-yourself-test ()
2278 (insert "(save-current-buffer
2279 (switch-to-buffer \"*scratch*\")
2280 (insert \"I am restored\"))")
2281 nil)
2282 @end group
2283 @end example
2284
2285 @node Desktop Notifications
2286 @section Desktop Notifications
2287 @cindex desktop notifications
2288 @cindex notifications, on desktop
2289
2290 Emacs is able to send @dfn{notifications} on systems that support the
2291 freedesktop.org Desktop Notifications Specification. In order to use
2292 this functionality, Emacs must have been compiled with D-Bus support,
2293 and the @code{notifications} library must be loaded. @xref{Top, ,
2294 D-Bus,dbus,D-Bus integration in Emacs}.
2295
2296 @defun notifications-notify &rest params
2297 This function sends a notification to the desktop via D-Bus,
2298 consisting of the parameters specified by the @var{params} arguments.
2299 These arguments should consist of alternating keyword and value pairs.
2300 The supported keywords and values are as follows:
2301
2302 @table @code
2303 @item :bus @var{bus}
2304 The D-Bus bus. This argument is needed only if a bus other than
2305 @code{:session} shall be used.
2306
2307 @item :title @var{title}
2308 The notification title.
2309
2310 @item :body @var{text}
2311 The notification body text. Depending on the implementation of the
2312 notification server, the text could contain HTML markups, like
2313 @samp{"<b>bold text</b>"}, hyperlinks, or images. Special HTML
2314 characters must be encoded, as @samp{"Contact
2315 &lt;postmaster@@localhost&gt;!"}.
2316
2317 @item :app-name @var{name}
2318 The name of the application sending the notification. The default is
2319 @code{notifications-application-name}.
2320
2321 @item :replaces-id @var{id}
2322 The notification @var{id} that this notification replaces. @var{id}
2323 must be the result of a previous @code{notifications-notify} call.
2324
2325 @item :app-icon @var{icon-file}
2326 The file name of the notification icon. If set to @code{nil}, no icon
2327 is displayed. The default is @code{notifications-application-icon}.
2328
2329 @item :actions (@var{key} @var{title} @var{key} @var{title} ...)
2330 A list of actions to be applied. @var{key} and @var{title} are both
2331 strings. The default action (usually invoked by clicking the
2332 notification) should have a key named @samp{"default"}. The title can
2333 be anything, though implementations are free not to display it.
2334
2335 @item :timeout @var{timeout}
2336 The timeout time in milliseconds since the display of the notification
2337 at which the notification should automatically close. If -1, the
2338 notification's expiration time is dependent on the notification
2339 server's settings, and may vary for the type of notification. If 0,
2340 the notification never expires. Default value is -1.
2341
2342 @item :urgency @var{urgency}
2343 The urgency level. It can be @code{low}, @code{normal}, or @code{critical}.
2344
2345 @item :action-items
2346 When this keyword is given, the @var{title} string of the actions is
2347 interpreted as icon name.
2348
2349 @item :category @var{category}
2350 The type of notification this is, a string. See the
2351 @uref{http://developer.gnome.org/notification-spec/#categories,
2352 Desktop Notifications Specification} for a list of standard
2353 categories.
2354
2355 @item :desktop-entry @var{filename}
2356 This specifies the name of the desktop filename representing the
2357 calling program, like @samp{"emacs"}.
2358
2359 @item :image-data (@var{width} @var{height} @var{rowstride} @var{has-alpha} @var{bits} @var{channels} @var{data})
2360 This is a raw data image format that describes the width, height,
2361 rowstride, whether there is an alpha channel, bits per sample,
2362 channels and image data, respectively.
2363
2364 @item :image-path @var{path}
2365 This is represented either as a URI (@samp{file://} is the only URI
2366 schema supported right now) or a name in a freedesktop.org-compliant
2367 icon theme from @samp{$XDG_DATA_DIRS/icons}.
2368
2369 @item :sound-file @var{filename}
2370 The path to a sound file to play when the notification pops up.
2371
2372 @item :sound-name @var{name}
2373 A themable named sound from the freedesktop.org sound naming
2374 specification from @samp{$XDG_DATA_DIRS/sounds}, to play when the
2375 notification pops up. Similar to the icon name, only for sounds. An
2376 example would be @samp{"message-new-instant"}.
2377
2378 @item :suppress-sound
2379 Causes the server to suppress playing any sounds, if it has that
2380 ability.
2381
2382 @item :resident
2383 When set the server will not automatically remove the notification
2384 when an action has been invoked. The notification will remain resident
2385 in the server until it is explicitly removed by the user or by the
2386 sender. This hint is likely only useful when the server has the
2387 @code{:persistence} capability.
2388
2389 @item :transient
2390 When set the server will treat the notification as transient and
2391 by-pass the server's persistence capability, if it should exist.
2392
2393 @item :x @var{position}
2394 @itemx :y @var{position}
2395 Specifies the X, Y location on the screen that the
2396 notification should point to. Both arguments must be used together.
2397
2398 @item :on-action @var{function}
2399 Function to call when an action is invoked. The notification @var{id}
2400 and the @var{key} of the action are passed as arguments to the
2401 function.
2402
2403 @item :on-close @var{function}
2404 Function to call when the notification has been closed by timeout or
2405 by the user. The function receive the notification @var{id} and the closing
2406 @var{reason} as arguments:
2407
2408 @itemize
2409 @item @code{expired} if the notification has expired
2410 @item @code{dismissed} if the notification was dismissed by the user
2411 @item @code{close-notification} if the notification was closed by a call to
2412 @code{notifications-close-notification}
2413 @item @code{undefined} if the notification server hasn't provided a reason
2414 @end itemize
2415 @end table
2416
2417 Which parameters are accepted by the notification server can be
2418 checked via @code{notifications-get-capabilities}.
2419
2420 This function returns a notification id, an integer, which can be used
2421 to manipulate the notification item with
2422 @code{notifications-close-notification} or the @code{:replaces-id}
2423 argument of another @code{notifications-notify} call. For example:
2424
2425 @example
2426 @group
2427 (defun my-on-action-function (id key)
2428 (message "Message %d, key \"%s\" pressed" id key))
2429 @result{} my-on-action-function
2430 @end group
2431
2432 @group
2433 (defun my-on-close-function (id reason)
2434 (message "Message %d, closed due to \"%s\"" id reason))
2435 @result{} my-on-close-function
2436 @end group
2437
2438 @group
2439 (notifications-notify
2440 :title "Title"
2441 :body "This is <b>important</b>."
2442 :actions '("Confirm" "I agree" "Refuse" "I disagree")
2443 :on-action 'my-on-action-function
2444 :on-close 'my-on-close-function)
2445 @result{} 22
2446 @end group
2447
2448 @group
2449 A message window opens on the desktop. Press "I agree"
2450 @result{} Message 22, key "Confirm" pressed
2451 Message 22, closed due to "dismissed"
2452 @end group
2453 @end example
2454 @end defun
2455
2456 @defun notifications-close-notification id &optional bus
2457 This function closes a notification with identifier @var{id}.
2458 @var{bus} can be a string denoting a D-Bus connection, the default is
2459 @code{:session}.
2460 @end defun
2461
2462 @defun notifications-get-capabilities &optional bus
2463 Returns the capabilities of the notification server, a list of
2464 symbols. @var{bus} can be a string denoting a D-Bus connection, the
2465 default is @code{:session}. The following capabilities can be
2466 expected:
2467
2468 @table @code
2469 @item :actions
2470 The server will provide the specified actions to the user.
2471
2472 @item :body
2473 Supports body text.
2474
2475 @item :body-hyperlinks
2476 The server supports hyperlinks in the notifications.
2477
2478 @item :body-images
2479 The server supports images in the notifications.
2480
2481 @item :body-markup
2482 Supports markup in the body text.
2483
2484 @item :icon-multi
2485 The server will render an animation of all the frames in a given image
2486 array.
2487
2488 @item :icon-static
2489 Supports display of exactly 1 frame of any given image array. This
2490 value is mutually exclusive with @code{:icon-multi}.
2491
2492 @item :persistence
2493 The server supports persistence of notifications.
2494
2495 @item :sound
2496 The server supports sounds on notifications.
2497 @end table
2498
2499 Further vendor-specific caps start with @code{:x-vendor}, like
2500 @code{:x-gnome-foo-cap}.
2501 @end defun
2502
2503 @defun notifications-get-server-information &optional bus
2504 Return information on the notification server, a list of strings.
2505 @var{bus} can be a string denoting a D-Bus connection, the default is
2506 @code{:session}. The returned list is @code{(@var{name} @var{vendor}
2507 @var{version} @var{spec-version})}.
2508
2509 @table @var
2510 @item name
2511 The product name of the server.
2512
2513 @item vendor
2514 The vendor name. For example, @samp{"KDE"}, @samp{"GNOME"}.
2515
2516 @item version
2517 The server's version number.
2518
2519 @item spec-version
2520 The specification version the server is compliant with.
2521 @end table
2522
2523 If @var{SPEC_VERSION} is @code{nil}, the server supports a
2524 specification prior to @samp{"1.0"}.
2525 @end defun
2526
2527 @node File Notifications
2528 @section Notifications on File Changes
2529 @cindex file notifications
2530 @cindex watch, for filesystem events
2531
2532 Several operating systems support watching of filesystems for changes
2533 of files. If configured properly, Emacs links a respective library
2534 like @file{gfilenotify}, @file{inotify}, or @file{w32notify}
2535 statically. These libraries enable watching of filesystems on the
2536 local machine.
2537
2538 It is also possible to watch filesystems on remote machines,
2539 @pxref{Remote Files,, Remote Files, emacs, The GNU Emacs Manual}
2540 This does not depend on one of the libraries linked to Emacs.
2541
2542 Since all these libraries emit different events on notified file
2543 changes, there is the Emacs library @code{filenotify} which provides a
2544 unique interface.
2545
2546 @defun file-notify-add-watch file flags callback
2547 Add a watch for filesystem events pertaining to @var{file}. This
2548 arranges for filesystem events pertaining to @var{file} to be reported
2549 to Emacs.
2550
2551 The returned value is a descriptor for the added watch. Its type
2552 depends on the underlying library, it cannot be assumed to be an
2553 integer as in the example below. It should be used for comparison by
2554 @code{equal} only.
2555
2556 If the @var{file} cannot be watched for some reason, this function
2557 signals a @code{file-notify-error} error.
2558
2559 Sometimes, mounted filesystems cannot be watched for file changes.
2560 This is not detected by this function, a non-@code{nil} return value
2561 does not guarantee that changes on @var{file} will be notified.
2562
2563 @var{flags} is a list of conditions to set what will be watched for.
2564 It can include the following symbols:
2565
2566 @table @code
2567 @item change
2568 watch for file changes
2569 @item attribute-change
2570 watch for file attribute changes, like permissions or modification
2571 time
2572 @end table
2573
2574 If @var{file} is a directory, changes for all files in that directory
2575 will be notified. This does not work recursively.
2576
2577 When any event happens, Emacs will call the @var{callback} function
2578 passing it a single argument @var{event}, which is of the form
2579
2580 @lisp
2581 (@var{descriptor} @var{action} @var{file} [@var{file1}])
2582 @end lisp
2583
2584 @var{descriptor} is the same object as the one returned by this
2585 function. @var{action} is the description of the event. It could be
2586 any one of the following symbols:
2587
2588 @table @code
2589 @item created
2590 @var{file} was created
2591 @item deleted
2592 @var{file} was deleted
2593 @item changed
2594 @var{file} has changed
2595 @item renamed
2596 @var{file} has been renamed to @var{file1}
2597 @item attribute-changed
2598 a @var{file} attribute was changed
2599 @end table
2600
2601 @var{file} and @var{file1} are the name of the file(s) whose event is
2602 being reported. For example:
2603
2604 @example
2605 @group
2606 (require 'filenotify)
2607 @result{} filenotify
2608 @end group
2609
2610 @group
2611 (defun my-notify-callback (event)
2612 (message "Event %S" event))
2613 @result{} my-notify-callback
2614 @end group
2615
2616 @group
2617 (file-notify-add-watch
2618 "/tmp" '(change attribute-change) 'my-notify-callback)
2619 @result{} 35025468
2620 @end group
2621
2622 @group
2623 (write-region "foo" nil "/tmp/foo")
2624 @result{} Event (35025468 created "/tmp/.#foo")
2625 Event (35025468 created "/tmp/foo")
2626 Event (35025468 changed "/tmp/foo")
2627 Event (35025468 deleted "/tmp/.#foo")
2628 @end group
2629
2630 @group
2631 (write-region "bla" nil "/tmp/foo")
2632 @result{} Event (35025468 created "/tmp/.#foo")
2633 Event (35025468 changed "/tmp/foo") [2 times]
2634 Event (35025468 deleted "/tmp/.#foo")
2635 @end group
2636
2637 @group
2638 (set-file-modes "/tmp/foo" (default-file-modes))
2639 @result{} Event (35025468 attribute-changed "/tmp/foo")
2640 @end group
2641 @end example
2642
2643 Whether the action @code{renamed} is returned, depends on the used
2644 watch library. It can be expected, when a directory is watched, and
2645 both @var{file} and @var{file1} belong to this directory. Otherwise,
2646 the actions @code{deleted} and @code{created} could be returned in a
2647 random order.
2648
2649 @example
2650 @group
2651 (rename-file "/tmp/foo" "/tmp/bla")
2652 @result{} Event (35025468 renamed "/tmp/foo" "/tmp/bla")
2653 @end group
2654
2655 @group
2656 (file-notify-add-watch
2657 "/var/tmp" '(change attribute-change) 'my-notify-callback)
2658 @result{} 35025504
2659 @end group
2660
2661 @group
2662 (rename-file "/tmp/bla" "/var/tmp/bla")
2663 @result{} ;; gfilenotify
2664 Event (35025468 renamed "/tmp/bla" "/var/tmp/bla")
2665
2666 @result{} ;; inotify
2667 Event (35025504 created "/var/tmp/bla")
2668 Event (35025468 deleted "/tmp/bla")
2669 @end group
2670 @end example
2671 @end defun
2672
2673 @defun file-notify-rm-watch descriptor
2674 Removes an existing file watch specified by its @var{descriptor}.
2675 @var{descriptor} should be an object returned by
2676 @code{file-notify-add-watch}.
2677 @end defun
2678
2679 @node Dynamic Libraries
2680 @section Dynamically Loaded Libraries
2681 @cindex dynamic libraries
2682
2683 A @dfn{dynamically loaded library} is a library that is loaded on
2684 demand, when its facilities are first needed. Emacs supports such
2685 on-demand loading of support libraries for some of its features.
2686
2687 @defvar dynamic-library-alist
2688 This is an alist of dynamic libraries and external library files
2689 implementing them.
2690
2691 Each element is a list of the form
2692 @w{@code{(@var{library} @var{files}@dots{})}}, where the @code{car} is
2693 a symbol representing a supported external library, and the rest are
2694 strings giving alternate filenames for that library.
2695
2696 Emacs tries to load the library from the files in the order they
2697 appear in the list; if none is found, the Emacs session won't have
2698 access to that library, and the features it provides will be
2699 unavailable.
2700
2701 Image support on some platforms uses this facility. Here's an example
2702 of setting this variable for supporting images on MS-Windows:
2703
2704 @example
2705 (setq dynamic-library-alist
2706 '((xpm "libxpm.dll" "xpm4.dll" "libXpm-nox4.dll")
2707 (png "libpng12d.dll" "libpng12.dll" "libpng.dll"
2708 "libpng13d.dll" "libpng13.dll")
2709 (jpeg "jpeg62.dll" "libjpeg.dll" "jpeg-62.dll"
2710 "jpeg.dll")
2711 (tiff "libtiff3.dll" "libtiff.dll")
2712 (gif "giflib4.dll" "libungif4.dll" "libungif.dll")
2713 (svg "librsvg-2-2.dll")
2714 (gdk-pixbuf "libgdk_pixbuf-2.0-0.dll")
2715 (glib "libglib-2.0-0.dll")
2716 (gobject "libgobject-2.0-0.dll")))
2717 @end example
2718
2719 Note that image types @code{pbm} and @code{xbm} do not need entries in
2720 this variable because they do not depend on external libraries and are
2721 always available in Emacs.
2722
2723 Also note that this variable is not meant to be a generic facility for
2724 accessing external libraries; only those already known by Emacs can
2725 be loaded through it.
2726
2727 This variable is ignored if the given @var{library} is statically
2728 linked into Emacs.
2729 @end defvar