Merge from origin/emacs-24
[emacs.git] / src / lread.c
blob6f71ff5f468c2786a83bd0f5ef7ff53d2af3e177
1 /* Lisp parsing and input streams.
3 Copyright (C) 1985-1989, 1993-1995, 1997-2014 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/file.h>
27 #include <errno.h>
28 #include <limits.h> /* For CHAR_BIT. */
29 #include <stat-time.h>
30 #include "lisp.h"
31 #include "intervals.h"
32 #include "character.h"
33 #include "buffer.h"
34 #include "charset.h"
35 #include "coding.h"
36 #include <epaths.h>
37 #include "commands.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "termhooks.h"
41 #include "blockinput.h"
43 #ifdef MSDOS
44 #include "msdos.h"
45 #endif
47 #ifdef HAVE_NS
48 #include "nsterm.h"
49 #endif
51 #include <unistd.h>
53 #ifdef HAVE_SETLOCALE
54 #include <locale.h>
55 #endif /* HAVE_SETLOCALE */
57 #include <fcntl.h>
59 #ifdef HAVE_FSEEKO
60 #define file_offset off_t
61 #define file_tell ftello
62 #else
63 #define file_offset long
64 #define file_tell ftell
65 #endif
67 /* Hash table read constants. */
68 static Lisp_Object Qhash_table, Qdata;
69 static Lisp_Object Qtest;
70 Lisp_Object Qsize;
71 static Lisp_Object Qweakness;
72 static Lisp_Object Qrehash_size;
73 static Lisp_Object Qrehash_threshold;
75 static Lisp_Object Qread_char, Qget_file_char, Qcurrent_load_list;
76 Lisp_Object Qstandard_input;
77 Lisp_Object Qvariable_documentation;
78 static Lisp_Object Qascii_character, Qload, Qload_file_name;
79 Lisp_Object Qbackquote, Qcomma, Qcomma_at, Qcomma_dot, Qfunction;
80 static Lisp_Object Qinhibit_file_name_operation;
81 static Lisp_Object Qeval_buffer_list;
82 Lisp_Object Qlexical_binding;
83 static Lisp_Object Qfile_truename, Qdo_after_load_evaluation; /* ACM 2006/5/16 */
85 /* Used instead of Qget_file_char while loading *.elc files compiled
86 by Emacs 21 or older. */
87 static Lisp_Object Qget_emacs_mule_file_char;
89 static Lisp_Object Qload_force_doc_strings;
91 static Lisp_Object Qload_in_progress;
93 /* The association list of objects read with the #n=object form.
94 Each member of the list has the form (n . object), and is used to
95 look up the object for the corresponding #n# construct.
96 It must be set to nil before all top-level calls to read0. */
97 static Lisp_Object read_objects;
99 /* File for get_file_char to read from. Use by load. */
100 static FILE *instream;
102 /* For use within read-from-string (this reader is non-reentrant!!) */
103 static ptrdiff_t read_from_string_index;
104 static ptrdiff_t read_from_string_index_byte;
105 static ptrdiff_t read_from_string_limit;
107 /* Number of characters read in the current call to Fread or
108 Fread_from_string. */
109 static EMACS_INT readchar_count;
111 /* This contains the last string skipped with #@. */
112 static char *saved_doc_string;
113 /* Length of buffer allocated in saved_doc_string. */
114 static ptrdiff_t saved_doc_string_size;
115 /* Length of actual data in saved_doc_string. */
116 static ptrdiff_t saved_doc_string_length;
117 /* This is the file position that string came from. */
118 static file_offset saved_doc_string_position;
120 /* This contains the previous string skipped with #@.
121 We copy it from saved_doc_string when a new string
122 is put in saved_doc_string. */
123 static char *prev_saved_doc_string;
124 /* Length of buffer allocated in prev_saved_doc_string. */
125 static ptrdiff_t prev_saved_doc_string_size;
126 /* Length of actual data in prev_saved_doc_string. */
127 static ptrdiff_t prev_saved_doc_string_length;
128 /* This is the file position that string came from. */
129 static file_offset prev_saved_doc_string_position;
131 /* True means inside a new-style backquote
132 with no surrounding parentheses.
133 Fread initializes this to false, so we need not specbind it
134 or worry about what happens to it when there is an error. */
135 static bool new_backquote_flag;
136 static Lisp_Object Qold_style_backquotes;
138 /* A list of file names for files being loaded in Fload. Used to
139 check for recursive loads. */
141 static Lisp_Object Vloads_in_progress;
143 static int read_emacs_mule_char (int, int (*) (int, Lisp_Object),
144 Lisp_Object);
146 static void readevalloop (Lisp_Object, FILE *, Lisp_Object, bool,
147 Lisp_Object, Lisp_Object,
148 Lisp_Object, Lisp_Object);
150 /* Functions that read one byte from the current source READCHARFUN
151 or unreads one byte. If the integer argument C is -1, it returns
152 one read byte, or -1 when there's no more byte in the source. If C
153 is 0 or positive, it unreads C, and the return value is not
154 interesting. */
156 static int readbyte_for_lambda (int, Lisp_Object);
157 static int readbyte_from_file (int, Lisp_Object);
158 static int readbyte_from_string (int, Lisp_Object);
160 /* Handle unreading and rereading of characters.
161 Write READCHAR to read a character,
162 UNREAD(c) to unread c to be read again.
164 These macros correctly read/unread multibyte characters. */
166 #define READCHAR readchar (readcharfun, NULL)
167 #define UNREAD(c) unreadchar (readcharfun, c)
169 /* Same as READCHAR but set *MULTIBYTE to the multibyteness of the source. */
170 #define READCHAR_REPORT_MULTIBYTE(multibyte) readchar (readcharfun, multibyte)
172 /* When READCHARFUN is Qget_file_char, Qget_emacs_mule_file_char,
173 Qlambda, or a cons, we use this to keep an unread character because
174 a file stream can't handle multibyte-char unreading. The value -1
175 means that there's no unread character. */
176 static int unread_char;
178 static int
179 readchar (Lisp_Object readcharfun, bool *multibyte)
181 Lisp_Object tem;
182 register int c;
183 int (*readbyte) (int, Lisp_Object);
184 unsigned char buf[MAX_MULTIBYTE_LENGTH];
185 int i, len;
186 bool emacs_mule_encoding = 0;
188 if (multibyte)
189 *multibyte = 0;
191 readchar_count++;
193 if (BUFFERP (readcharfun))
195 register struct buffer *inbuffer = XBUFFER (readcharfun);
197 ptrdiff_t pt_byte = BUF_PT_BYTE (inbuffer);
199 if (! BUFFER_LIVE_P (inbuffer))
200 return -1;
202 if (pt_byte >= BUF_ZV_BYTE (inbuffer))
203 return -1;
205 if (! NILP (BVAR (inbuffer, enable_multibyte_characters)))
207 /* Fetch the character code from the buffer. */
208 unsigned char *p = BUF_BYTE_ADDRESS (inbuffer, pt_byte);
209 BUF_INC_POS (inbuffer, pt_byte);
210 c = STRING_CHAR (p);
211 if (multibyte)
212 *multibyte = 1;
214 else
216 c = BUF_FETCH_BYTE (inbuffer, pt_byte);
217 if (! ASCII_CHAR_P (c))
218 c = BYTE8_TO_CHAR (c);
219 pt_byte++;
221 SET_BUF_PT_BOTH (inbuffer, BUF_PT (inbuffer) + 1, pt_byte);
223 return c;
225 if (MARKERP (readcharfun))
227 register struct buffer *inbuffer = XMARKER (readcharfun)->buffer;
229 ptrdiff_t bytepos = marker_byte_position (readcharfun);
231 if (bytepos >= BUF_ZV_BYTE (inbuffer))
232 return -1;
234 if (! NILP (BVAR (inbuffer, enable_multibyte_characters)))
236 /* Fetch the character code from the buffer. */
237 unsigned char *p = BUF_BYTE_ADDRESS (inbuffer, bytepos);
238 BUF_INC_POS (inbuffer, bytepos);
239 c = STRING_CHAR (p);
240 if (multibyte)
241 *multibyte = 1;
243 else
245 c = BUF_FETCH_BYTE (inbuffer, bytepos);
246 if (! ASCII_CHAR_P (c))
247 c = BYTE8_TO_CHAR (c);
248 bytepos++;
251 XMARKER (readcharfun)->bytepos = bytepos;
252 XMARKER (readcharfun)->charpos++;
254 return c;
257 if (EQ (readcharfun, Qlambda))
259 readbyte = readbyte_for_lambda;
260 goto read_multibyte;
263 if (EQ (readcharfun, Qget_file_char))
265 readbyte = readbyte_from_file;
266 goto read_multibyte;
269 if (STRINGP (readcharfun))
271 if (read_from_string_index >= read_from_string_limit)
272 c = -1;
273 else if (STRING_MULTIBYTE (readcharfun))
275 if (multibyte)
276 *multibyte = 1;
277 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, readcharfun,
278 read_from_string_index,
279 read_from_string_index_byte);
281 else
283 c = SREF (readcharfun, read_from_string_index_byte);
284 read_from_string_index++;
285 read_from_string_index_byte++;
287 return c;
290 if (CONSP (readcharfun))
292 /* This is the case that read_vector is reading from a unibyte
293 string that contains a byte sequence previously skipped
294 because of #@NUMBER. The car part of readcharfun is that
295 string, and the cdr part is a value of readcharfun given to
296 read_vector. */
297 readbyte = readbyte_from_string;
298 if (EQ (XCDR (readcharfun), Qget_emacs_mule_file_char))
299 emacs_mule_encoding = 1;
300 goto read_multibyte;
303 if (EQ (readcharfun, Qget_emacs_mule_file_char))
305 readbyte = readbyte_from_file;
306 emacs_mule_encoding = 1;
307 goto read_multibyte;
310 tem = call0 (readcharfun);
312 if (NILP (tem))
313 return -1;
314 return XINT (tem);
316 read_multibyte:
317 if (unread_char >= 0)
319 c = unread_char;
320 unread_char = -1;
321 return c;
323 c = (*readbyte) (-1, readcharfun);
324 if (c < 0)
325 return c;
326 if (multibyte)
327 *multibyte = 1;
328 if (ASCII_CHAR_P (c))
329 return c;
330 if (emacs_mule_encoding)
331 return read_emacs_mule_char (c, readbyte, readcharfun);
332 i = 0;
333 buf[i++] = c;
334 len = BYTES_BY_CHAR_HEAD (c);
335 while (i < len)
337 c = (*readbyte) (-1, readcharfun);
338 if (c < 0 || ! TRAILING_CODE_P (c))
340 while (--i > 1)
341 (*readbyte) (buf[i], readcharfun);
342 return BYTE8_TO_CHAR (buf[0]);
344 buf[i++] = c;
346 return STRING_CHAR (buf);
349 #define FROM_FILE_P(readcharfun) \
350 (EQ (readcharfun, Qget_file_char) \
351 || EQ (readcharfun, Qget_emacs_mule_file_char))
353 static void
354 skip_dyn_bytes (Lisp_Object readcharfun, ptrdiff_t n)
356 if (FROM_FILE_P (readcharfun))
358 block_input (); /* FIXME: Not sure if it's needed. */
359 fseek (instream, n, SEEK_CUR);
360 unblock_input ();
362 else
363 { /* We're not reading directly from a file. In that case, it's difficult
364 to reliably count bytes, since these are usually meant for the file's
365 encoding, whereas we're now typically in the internal encoding.
366 But luckily, skip_dyn_bytes is used to skip over a single
367 dynamic-docstring (or dynamic byte-code) which is always quoted such
368 that \037 is the final char. */
369 int c;
370 do {
371 c = READCHAR;
372 } while (c >= 0 && c != '\037');
376 static void
377 skip_dyn_eof (Lisp_Object readcharfun)
379 if (FROM_FILE_P (readcharfun))
381 block_input (); /* FIXME: Not sure if it's needed. */
382 fseek (instream, 0, SEEK_END);
383 unblock_input ();
385 else
386 while (READCHAR >= 0);
389 /* Unread the character C in the way appropriate for the stream READCHARFUN.
390 If the stream is a user function, call it with the char as argument. */
392 static void
393 unreadchar (Lisp_Object readcharfun, int c)
395 readchar_count--;
396 if (c == -1)
397 /* Don't back up the pointer if we're unreading the end-of-input mark,
398 since readchar didn't advance it when we read it. */
400 else if (BUFFERP (readcharfun))
402 struct buffer *b = XBUFFER (readcharfun);
403 ptrdiff_t charpos = BUF_PT (b);
404 ptrdiff_t bytepos = BUF_PT_BYTE (b);
406 if (! NILP (BVAR (b, enable_multibyte_characters)))
407 BUF_DEC_POS (b, bytepos);
408 else
409 bytepos--;
411 SET_BUF_PT_BOTH (b, charpos - 1, bytepos);
413 else if (MARKERP (readcharfun))
415 struct buffer *b = XMARKER (readcharfun)->buffer;
416 ptrdiff_t bytepos = XMARKER (readcharfun)->bytepos;
418 XMARKER (readcharfun)->charpos--;
419 if (! NILP (BVAR (b, enable_multibyte_characters)))
420 BUF_DEC_POS (b, bytepos);
421 else
422 bytepos--;
424 XMARKER (readcharfun)->bytepos = bytepos;
426 else if (STRINGP (readcharfun))
428 read_from_string_index--;
429 read_from_string_index_byte
430 = string_char_to_byte (readcharfun, read_from_string_index);
432 else if (CONSP (readcharfun))
434 unread_char = c;
436 else if (EQ (readcharfun, Qlambda))
438 unread_char = c;
440 else if (FROM_FILE_P (readcharfun))
442 unread_char = c;
444 else
445 call1 (readcharfun, make_number (c));
448 static int
449 readbyte_for_lambda (int c, Lisp_Object readcharfun)
451 return read_bytecode_char (c >= 0);
455 static int
456 readbyte_from_file (int c, Lisp_Object readcharfun)
458 if (c >= 0)
460 block_input ();
461 ungetc (c, instream);
462 unblock_input ();
463 return 0;
466 block_input ();
467 c = getc (instream);
469 /* Interrupted reads have been observed while reading over the network. */
470 while (c == EOF && ferror (instream) && errno == EINTR)
472 unblock_input ();
473 QUIT;
474 block_input ();
475 clearerr (instream);
476 c = getc (instream);
479 unblock_input ();
481 return (c == EOF ? -1 : c);
484 static int
485 readbyte_from_string (int c, Lisp_Object readcharfun)
487 Lisp_Object string = XCAR (readcharfun);
489 if (c >= 0)
491 read_from_string_index--;
492 read_from_string_index_byte
493 = string_char_to_byte (string, read_from_string_index);
496 if (read_from_string_index >= read_from_string_limit)
497 c = -1;
498 else
499 FETCH_STRING_CHAR_ADVANCE (c, string,
500 read_from_string_index,
501 read_from_string_index_byte);
502 return c;
506 /* Read one non-ASCII character from INSTREAM. The character is
507 encoded in `emacs-mule' and the first byte is already read in
508 C. */
510 static int
511 read_emacs_mule_char (int c, int (*readbyte) (int, Lisp_Object), Lisp_Object readcharfun)
513 /* Emacs-mule coding uses at most 4-byte for one character. */
514 unsigned char buf[4];
515 int len = emacs_mule_bytes[c];
516 struct charset *charset;
517 int i;
518 unsigned code;
520 if (len == 1)
521 /* C is not a valid leading-code of `emacs-mule'. */
522 return BYTE8_TO_CHAR (c);
524 i = 0;
525 buf[i++] = c;
526 while (i < len)
528 c = (*readbyte) (-1, readcharfun);
529 if (c < 0xA0)
531 while (--i > 1)
532 (*readbyte) (buf[i], readcharfun);
533 return BYTE8_TO_CHAR (buf[0]);
535 buf[i++] = c;
538 if (len == 2)
540 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[0]]);
541 code = buf[1] & 0x7F;
543 else if (len == 3)
545 if (buf[0] == EMACS_MULE_LEADING_CODE_PRIVATE_11
546 || buf[0] == EMACS_MULE_LEADING_CODE_PRIVATE_12)
548 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[1]]);
549 code = buf[2] & 0x7F;
551 else
553 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[0]]);
554 code = ((buf[1] << 8) | buf[2]) & 0x7F7F;
557 else
559 charset = CHARSET_FROM_ID (emacs_mule_charset[buf[1]]);
560 code = ((buf[2] << 8) | buf[3]) & 0x7F7F;
562 c = DECODE_CHAR (charset, code);
563 if (c < 0)
564 Fsignal (Qinvalid_read_syntax,
565 list1 (build_string ("invalid multibyte form")));
566 return c;
570 static Lisp_Object read_internal_start (Lisp_Object, Lisp_Object,
571 Lisp_Object);
572 static Lisp_Object read0 (Lisp_Object);
573 static Lisp_Object read1 (Lisp_Object, int *, bool);
575 static Lisp_Object read_list (bool, Lisp_Object);
576 static Lisp_Object read_vector (Lisp_Object, bool);
578 static Lisp_Object substitute_object_recurse (Lisp_Object, Lisp_Object,
579 Lisp_Object);
580 static void substitute_object_in_subtree (Lisp_Object,
581 Lisp_Object);
582 static void substitute_in_interval (INTERVAL, Lisp_Object);
585 /* Get a character from the tty. */
587 /* Read input events until we get one that's acceptable for our purposes.
589 If NO_SWITCH_FRAME, switch-frame events are stashed
590 until we get a character we like, and then stuffed into
591 unread_switch_frame.
593 If ASCII_REQUIRED, check function key events to see
594 if the unmodified version of the symbol has a Qascii_character
595 property, and use that character, if present.
597 If ERROR_NONASCII, signal an error if the input we
598 get isn't an ASCII character with modifiers. If it's false but
599 ASCII_REQUIRED is true, just re-read until we get an ASCII
600 character.
602 If INPUT_METHOD, invoke the current input method
603 if the character warrants that.
605 If SECONDS is a number, wait that many seconds for input, and
606 return Qnil if no input arrives within that time. */
608 static Lisp_Object
609 read_filtered_event (bool no_switch_frame, bool ascii_required,
610 bool error_nonascii, bool input_method, Lisp_Object seconds)
612 Lisp_Object val, delayed_switch_frame;
613 struct timespec end_time;
615 #ifdef HAVE_WINDOW_SYSTEM
616 if (display_hourglass_p)
617 cancel_hourglass ();
618 #endif
620 delayed_switch_frame = Qnil;
622 /* Compute timeout. */
623 if (NUMBERP (seconds))
625 double duration = extract_float (seconds);
626 struct timespec wait_time = dtotimespec (duration);
627 end_time = timespec_add (current_timespec (), wait_time);
630 /* Read until we get an acceptable event. */
631 retry:
633 val = read_char (0, Qnil, (input_method ? Qnil : Qt), 0,
634 NUMBERP (seconds) ? &end_time : NULL);
635 while (INTEGERP (val) && XINT (val) == -2); /* wrong_kboard_jmpbuf */
637 if (BUFFERP (val))
638 goto retry;
640 /* `switch-frame' events are put off until after the next ASCII
641 character. This is better than signaling an error just because
642 the last characters were typed to a separate minibuffer frame,
643 for example. Eventually, some code which can deal with
644 switch-frame events will read it and process it. */
645 if (no_switch_frame
646 && EVENT_HAS_PARAMETERS (val)
647 && EQ (EVENT_HEAD_KIND (EVENT_HEAD (val)), Qswitch_frame))
649 delayed_switch_frame = val;
650 goto retry;
653 if (ascii_required && !(NUMBERP (seconds) && NILP (val)))
655 /* Convert certain symbols to their ASCII equivalents. */
656 if (SYMBOLP (val))
658 Lisp_Object tem, tem1;
659 tem = Fget (val, Qevent_symbol_element_mask);
660 if (!NILP (tem))
662 tem1 = Fget (Fcar (tem), Qascii_character);
663 /* Merge this symbol's modifier bits
664 with the ASCII equivalent of its basic code. */
665 if (!NILP (tem1))
666 XSETFASTINT (val, XINT (tem1) | XINT (Fcar (Fcdr (tem))));
670 /* If we don't have a character now, deal with it appropriately. */
671 if (!INTEGERP (val))
673 if (error_nonascii)
675 Vunread_command_events = list1 (val);
676 error ("Non-character input-event");
678 else
679 goto retry;
683 if (! NILP (delayed_switch_frame))
684 unread_switch_frame = delayed_switch_frame;
686 #if 0
688 #ifdef HAVE_WINDOW_SYSTEM
689 if (display_hourglass_p)
690 start_hourglass ();
691 #endif
693 #endif
695 return val;
698 DEFUN ("read-char", Fread_char, Sread_char, 0, 3, 0,
699 doc: /* Read a character from the command input (keyboard or macro).
700 It is returned as a number.
701 If the character has modifiers, they are resolved and reflected to the
702 character code if possible (e.g. C-SPC -> 0).
704 If the user generates an event which is not a character (i.e. a mouse
705 click or function key event), `read-char' signals an error. As an
706 exception, switch-frame events are put off until non-character events
707 can be read.
708 If you want to read non-character events, or ignore them, call
709 `read-event' or `read-char-exclusive' instead.
711 If the optional argument PROMPT is non-nil, display that as a prompt.
712 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
713 input method is turned on in the current buffer, that input method
714 is used for reading a character.
715 If the optional argument SECONDS is non-nil, it should be a number
716 specifying the maximum number of seconds to wait for input. If no
717 input arrives in that time, return nil. SECONDS may be a
718 floating-point value. */)
719 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
721 Lisp_Object val;
723 if (! NILP (prompt))
724 message_with_string ("%s", prompt, 0);
725 val = read_filtered_event (1, 1, 1, ! NILP (inherit_input_method), seconds);
727 return (NILP (val) ? Qnil
728 : make_number (char_resolve_modifier_mask (XINT (val))));
731 DEFUN ("read-event", Fread_event, Sread_event, 0, 3, 0,
732 doc: /* Read an event object from the input stream.
733 If the optional argument PROMPT is non-nil, display that as a prompt.
734 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
735 input method is turned on in the current buffer, that input method
736 is used for reading a character.
737 If the optional argument SECONDS is non-nil, it should be a number
738 specifying the maximum number of seconds to wait for input. If no
739 input arrives in that time, return nil. SECONDS may be a
740 floating-point value. */)
741 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
743 if (! NILP (prompt))
744 message_with_string ("%s", prompt, 0);
745 return read_filtered_event (0, 0, 0, ! NILP (inherit_input_method), seconds);
748 DEFUN ("read-char-exclusive", Fread_char_exclusive, Sread_char_exclusive, 0, 3, 0,
749 doc: /* Read a character from the command input (keyboard or macro).
750 It is returned as a number. Non-character events are ignored.
751 If the character has modifiers, they are resolved and reflected to the
752 character code if possible (e.g. C-SPC -> 0).
754 If the optional argument PROMPT is non-nil, display that as a prompt.
755 If the optional argument INHERIT-INPUT-METHOD is non-nil and some
756 input method is turned on in the current buffer, that input method
757 is used for reading a character.
758 If the optional argument SECONDS is non-nil, it should be a number
759 specifying the maximum number of seconds to wait for input. If no
760 input arrives in that time, return nil. SECONDS may be a
761 floating-point value. */)
762 (Lisp_Object prompt, Lisp_Object inherit_input_method, Lisp_Object seconds)
764 Lisp_Object val;
766 if (! NILP (prompt))
767 message_with_string ("%s", prompt, 0);
769 val = read_filtered_event (1, 1, 0, ! NILP (inherit_input_method), seconds);
771 return (NILP (val) ? Qnil
772 : make_number (char_resolve_modifier_mask (XINT (val))));
775 DEFUN ("get-file-char", Fget_file_char, Sget_file_char, 0, 0, 0,
776 doc: /* Don't use this yourself. */)
777 (void)
779 register Lisp_Object val;
780 block_input ();
781 XSETINT (val, getc (instream));
782 unblock_input ();
783 return val;
789 /* Return true if the lisp code read using READCHARFUN defines a non-nil
790 `lexical-binding' file variable. After returning, the stream is
791 positioned following the first line, if it is a comment or #! line,
792 otherwise nothing is read. */
794 static bool
795 lisp_file_lexically_bound_p (Lisp_Object readcharfun)
797 int ch = READCHAR;
799 if (ch == '#')
801 ch = READCHAR;
802 if (ch != '!')
804 UNREAD (ch);
805 UNREAD ('#');
806 return 0;
808 while (ch != '\n' && ch != EOF)
809 ch = READCHAR;
810 if (ch == '\n') ch = READCHAR;
811 /* It is OK to leave the position after a #! line, since
812 that is what read1 does. */
815 if (ch != ';')
816 /* The first line isn't a comment, just give up. */
818 UNREAD (ch);
819 return 0;
821 else
822 /* Look for an appropriate file-variable in the first line. */
824 bool rv = 0;
825 enum {
826 NOMINAL, AFTER_FIRST_DASH, AFTER_ASTERIX
827 } beg_end_state = NOMINAL;
828 bool in_file_vars = 0;
830 #define UPDATE_BEG_END_STATE(ch) \
831 if (beg_end_state == NOMINAL) \
832 beg_end_state = (ch == '-' ? AFTER_FIRST_DASH : NOMINAL); \
833 else if (beg_end_state == AFTER_FIRST_DASH) \
834 beg_end_state = (ch == '*' ? AFTER_ASTERIX : NOMINAL); \
835 else if (beg_end_state == AFTER_ASTERIX) \
837 if (ch == '-') \
838 in_file_vars = !in_file_vars; \
839 beg_end_state = NOMINAL; \
842 /* Skip until we get to the file vars, if any. */
845 ch = READCHAR;
846 UPDATE_BEG_END_STATE (ch);
848 while (!in_file_vars && ch != '\n' && ch != EOF);
850 while (in_file_vars)
852 char var[100], val[100];
853 unsigned i;
855 ch = READCHAR;
857 /* Read a variable name. */
858 while (ch == ' ' || ch == '\t')
859 ch = READCHAR;
861 i = 0;
862 while (ch != ':' && ch != '\n' && ch != EOF && in_file_vars)
864 if (i < sizeof var - 1)
865 var[i++] = ch;
866 UPDATE_BEG_END_STATE (ch);
867 ch = READCHAR;
870 /* Stop scanning if no colon was found before end marker. */
871 if (!in_file_vars || ch == '\n' || ch == EOF)
872 break;
874 while (i > 0 && (var[i - 1] == ' ' || var[i - 1] == '\t'))
875 i--;
876 var[i] = '\0';
878 if (ch == ':')
880 /* Read a variable value. */
881 ch = READCHAR;
883 while (ch == ' ' || ch == '\t')
884 ch = READCHAR;
886 i = 0;
887 while (ch != ';' && ch != '\n' && ch != EOF && in_file_vars)
889 if (i < sizeof val - 1)
890 val[i++] = ch;
891 UPDATE_BEG_END_STATE (ch);
892 ch = READCHAR;
894 if (! in_file_vars)
895 /* The value was terminated by an end-marker, which remove. */
896 i -= 3;
897 while (i > 0 && (val[i - 1] == ' ' || val[i - 1] == '\t'))
898 i--;
899 val[i] = '\0';
901 if (strcmp (var, "lexical-binding") == 0)
902 /* This is it... */
904 rv = (strcmp (val, "nil") != 0);
905 break;
910 while (ch != '\n' && ch != EOF)
911 ch = READCHAR;
913 return rv;
917 /* Value is a version number of byte compiled code if the file
918 associated with file descriptor FD is a compiled Lisp file that's
919 safe to load. Only files compiled with Emacs are safe to load.
920 Files compiled with XEmacs can lead to a crash in Fbyte_code
921 because of an incompatible change in the byte compiler. */
923 static int
924 safe_to_load_version (int fd)
926 char buf[512];
927 int nbytes, i;
928 int version = 1;
930 /* Read the first few bytes from the file, and look for a line
931 specifying the byte compiler version used. */
932 nbytes = emacs_read (fd, buf, sizeof buf);
933 if (nbytes > 0)
935 /* Skip to the next newline, skipping over the initial `ELC'
936 with NUL bytes following it, but note the version. */
937 for (i = 0; i < nbytes && buf[i] != '\n'; ++i)
938 if (i == 4)
939 version = buf[i];
941 if (i >= nbytes
942 || fast_c_string_match_ignore_case (Vbytecomp_version_regexp,
943 buf + i, nbytes - i) < 0)
944 version = 0;
947 lseek (fd, 0, SEEK_SET);
948 return version;
952 /* Callback for record_unwind_protect. Restore the old load list OLD,
953 after loading a file successfully. */
955 static void
956 record_load_unwind (Lisp_Object old)
958 Vloads_in_progress = old;
961 /* This handler function is used via internal_condition_case_1. */
963 static Lisp_Object
964 load_error_handler (Lisp_Object data)
966 return Qnil;
969 static void
970 load_warn_old_style_backquotes (Lisp_Object file)
972 if (!NILP (Vold_style_backquotes))
974 AUTO_STRING (format, "Loading `%s': old-style backquotes detected!");
975 Fmessage (2, (Lisp_Object []) {format, file});
979 DEFUN ("get-load-suffixes", Fget_load_suffixes, Sget_load_suffixes, 0, 0, 0,
980 doc: /* Return the suffixes that `load' should try if a suffix is \
981 required.
982 This uses the variables `load-suffixes' and `load-file-rep-suffixes'. */)
983 (void)
985 Lisp_Object lst = Qnil, suffixes = Vload_suffixes, suffix, ext;
986 while (CONSP (suffixes))
988 Lisp_Object exts = Vload_file_rep_suffixes;
989 suffix = XCAR (suffixes);
990 suffixes = XCDR (suffixes);
991 while (CONSP (exts))
993 ext = XCAR (exts);
994 exts = XCDR (exts);
995 lst = Fcons (concat2 (suffix, ext), lst);
998 return Fnreverse (lst);
1001 DEFUN ("load", Fload, Sload, 1, 5, 0,
1002 doc: /* Execute a file of Lisp code named FILE.
1003 First try FILE with `.elc' appended, then try with `.el',
1004 then try FILE unmodified (the exact suffixes in the exact order are
1005 determined by `load-suffixes'). Environment variable references in
1006 FILE are replaced with their values by calling `substitute-in-file-name'.
1007 This function searches the directories in `load-path'.
1009 If optional second arg NOERROR is non-nil,
1010 report no error if FILE doesn't exist.
1011 Print messages at start and end of loading unless
1012 optional third arg NOMESSAGE is non-nil (but `force-load-messages'
1013 overrides that).
1014 If optional fourth arg NOSUFFIX is non-nil, don't try adding
1015 suffixes `.elc' or `.el' to the specified name FILE.
1016 If optional fifth arg MUST-SUFFIX is non-nil, insist on
1017 the suffix `.elc' or `.el'; don't accept just FILE unless
1018 it ends in one of those suffixes or includes a directory name.
1020 If NOSUFFIX is nil, then if a file could not be found, try looking for
1021 a different representation of the file by adding non-empty suffixes to
1022 its name, before trying another file. Emacs uses this feature to find
1023 compressed versions of files when Auto Compression mode is enabled.
1024 If NOSUFFIX is non-nil, disable this feature.
1026 The suffixes that this function tries out, when NOSUFFIX is nil, are
1027 given by the return value of `get-load-suffixes' and the values listed
1028 in `load-file-rep-suffixes'. If MUST-SUFFIX is non-nil, only the
1029 return value of `get-load-suffixes' is used, i.e. the file name is
1030 required to have a non-empty suffix.
1032 When searching suffixes, this function normally stops at the first
1033 one that exists. If the option `load-prefer-newer' is non-nil,
1034 however, it tries all suffixes, and uses whichever file is the newest.
1036 Loading a file records its definitions, and its `provide' and
1037 `require' calls, in an element of `load-history' whose
1038 car is the file name loaded. See `load-history'.
1040 While the file is in the process of being loaded, the variable
1041 `load-in-progress' is non-nil and the variable `load-file-name'
1042 is bound to the file's name.
1044 Return t if the file exists and loads successfully. */)
1045 (Lisp_Object file, Lisp_Object noerror, Lisp_Object nomessage,
1046 Lisp_Object nosuffix, Lisp_Object must_suffix)
1048 FILE *stream;
1049 int fd;
1050 int fd_index;
1051 ptrdiff_t count = SPECPDL_INDEX ();
1052 struct gcpro gcpro1, gcpro2, gcpro3;
1053 Lisp_Object found, efound, hist_file_name;
1054 /* True means we printed the ".el is newer" message. */
1055 bool newer = 0;
1056 /* True means we are loading a compiled file. */
1057 bool compiled = 0;
1058 Lisp_Object handler;
1059 bool safe_p = 1;
1060 const char *fmode = "r";
1061 int version;
1063 #ifdef DOS_NT
1064 fmode = "rt";
1065 #endif /* DOS_NT */
1067 CHECK_STRING (file);
1069 /* If file name is magic, call the handler. */
1070 /* This shouldn't be necessary any more now that `openp' handles it right.
1071 handler = Ffind_file_name_handler (file, Qload);
1072 if (!NILP (handler))
1073 return call5 (handler, Qload, file, noerror, nomessage, nosuffix); */
1075 /* Do this after the handler to avoid
1076 the need to gcpro noerror, nomessage and nosuffix.
1077 (Below here, we care only whether they are nil or not.)
1078 The presence of this call is the result of a historical accident:
1079 it used to be in every file-operation and when it got removed
1080 everywhere, it accidentally stayed here. Since then, enough people
1081 supposedly have things like (load "$PROJECT/foo.el") in their .emacs
1082 that it seemed risky to remove. */
1083 if (! NILP (noerror))
1085 file = internal_condition_case_1 (Fsubstitute_in_file_name, file,
1086 Qt, load_error_handler);
1087 if (NILP (file))
1088 return Qnil;
1090 else
1091 file = Fsubstitute_in_file_name (file);
1093 /* Avoid weird lossage with null string as arg,
1094 since it would try to load a directory as a Lisp file. */
1095 if (SCHARS (file) == 0)
1097 fd = -1;
1098 errno = ENOENT;
1100 else
1102 Lisp_Object suffixes;
1103 found = Qnil;
1104 GCPRO2 (file, found);
1106 if (! NILP (must_suffix))
1108 /* Don't insist on adding a suffix if FILE already ends with one. */
1109 ptrdiff_t size = SBYTES (file);
1110 if (size > 3
1111 && !strcmp (SSDATA (file) + size - 3, ".el"))
1112 must_suffix = Qnil;
1113 else if (size > 4
1114 && !strcmp (SSDATA (file) + size - 4, ".elc"))
1115 must_suffix = Qnil;
1116 /* Don't insist on adding a suffix
1117 if the argument includes a directory name. */
1118 else if (! NILP (Ffile_name_directory (file)))
1119 must_suffix = Qnil;
1122 if (!NILP (nosuffix))
1123 suffixes = Qnil;
1124 else
1126 suffixes = Fget_load_suffixes ();
1127 if (NILP (must_suffix))
1129 Lisp_Object arg[2];
1130 arg[0] = suffixes;
1131 arg[1] = Vload_file_rep_suffixes;
1132 suffixes = Fappend (2, arg);
1136 fd = openp (Vload_path, file, suffixes, &found, Qnil, load_prefer_newer);
1137 UNGCPRO;
1140 if (fd == -1)
1142 if (NILP (noerror))
1143 report_file_error ("Cannot open load file", file);
1144 return Qnil;
1147 /* Tell startup.el whether or not we found the user's init file. */
1148 if (EQ (Qt, Vuser_init_file))
1149 Vuser_init_file = found;
1151 /* If FD is -2, that means openp found a magic file. */
1152 if (fd == -2)
1154 if (NILP (Fequal (found, file)))
1155 /* If FOUND is a different file name from FILE,
1156 find its handler even if we have already inhibited
1157 the `load' operation on FILE. */
1158 handler = Ffind_file_name_handler (found, Qt);
1159 else
1160 handler = Ffind_file_name_handler (found, Qload);
1161 if (! NILP (handler))
1162 return call5 (handler, Qload, found, noerror, nomessage, Qt);
1163 #ifdef DOS_NT
1164 /* Tramp has to deal with semi-broken packages that prepend
1165 drive letters to remote files. For that reason, Tramp
1166 catches file operations that test for file existence, which
1167 makes openp think X:/foo.elc files are remote. However,
1168 Tramp does not catch `load' operations for such files, so we
1169 end up with a nil as the `load' handler above. If we would
1170 continue with fd = -2, we will behave wrongly, and in
1171 particular try reading a .elc file in the "rt" mode instead
1172 of "rb". See bug #9311 for the results. To work around
1173 this, we try to open the file locally, and go with that if it
1174 succeeds. */
1175 fd = emacs_open (SSDATA (ENCODE_FILE (found)), O_RDONLY, 0);
1176 if (fd == -1)
1177 fd = -2;
1178 #endif
1181 if (fd < 0)
1183 /* Pacify older GCC with --enable-gcc-warnings. */
1184 IF_LINT (fd_index = 0);
1186 else
1188 fd_index = SPECPDL_INDEX ();
1189 record_unwind_protect_int (close_file_unwind, fd);
1192 /* Check if we're stuck in a recursive load cycle.
1194 2000-09-21: It's not possible to just check for the file loaded
1195 being a member of Vloads_in_progress. This fails because of the
1196 way the byte compiler currently works; `provide's are not
1197 evaluated, see font-lock.el/jit-lock.el as an example. This
1198 leads to a certain amount of ``normal'' recursion.
1200 Also, just loading a file recursively is not always an error in
1201 the general case; the second load may do something different. */
1203 int load_count = 0;
1204 Lisp_Object tem;
1205 for (tem = Vloads_in_progress; CONSP (tem); tem = XCDR (tem))
1206 if (!NILP (Fequal (found, XCAR (tem))) && (++load_count > 3))
1207 signal_error ("Recursive load", Fcons (found, Vloads_in_progress));
1208 record_unwind_protect (record_load_unwind, Vloads_in_progress);
1209 Vloads_in_progress = Fcons (found, Vloads_in_progress);
1212 /* All loads are by default dynamic, unless the file itself specifies
1213 otherwise using a file-variable in the first line. This is bound here
1214 so that it takes effect whether or not we use
1215 Vload_source_file_function. */
1216 specbind (Qlexical_binding, Qnil);
1218 /* Get the name for load-history. */
1219 hist_file_name = (! NILP (Vpurify_flag)
1220 ? concat2 (Ffile_name_directory (file),
1221 Ffile_name_nondirectory (found))
1222 : found) ;
1224 version = -1;
1226 /* Check for the presence of old-style quotes and warn about them. */
1227 specbind (Qold_style_backquotes, Qnil);
1228 record_unwind_protect (load_warn_old_style_backquotes, file);
1230 if (!memcmp (SDATA (found) + SBYTES (found) - 4, ".elc", 4)
1231 || (fd >= 0 && (version = safe_to_load_version (fd)) > 0))
1232 /* Load .elc files directly, but not when they are
1233 remote and have no handler! */
1235 if (fd != -2)
1237 struct stat s1, s2;
1238 int result;
1240 GCPRO3 (file, found, hist_file_name);
1242 if (version < 0
1243 && ! (version = safe_to_load_version (fd)))
1245 safe_p = 0;
1246 if (!load_dangerous_libraries)
1247 error ("File `%s' was not compiled in Emacs", SDATA (found));
1248 else if (!NILP (nomessage) && !force_load_messages)
1249 message_with_string ("File `%s' not compiled in Emacs", found, 1);
1252 compiled = 1;
1254 efound = ENCODE_FILE (found);
1256 #ifdef DOS_NT
1257 fmode = "rb";
1258 #endif /* DOS_NT */
1260 /* openp already checked for newness, no point doing it again.
1261 FIXME would be nice to get a message when openp
1262 ignores suffix order due to load_prefer_newer. */
1263 if (!load_prefer_newer)
1265 result = stat (SSDATA (efound), &s1);
1266 if (result == 0)
1268 SSET (efound, SBYTES (efound) - 1, 0);
1269 result = stat (SSDATA (efound), &s2);
1270 SSET (efound, SBYTES (efound) - 1, 'c');
1273 if (result == 0
1274 && timespec_cmp (get_stat_mtime (&s1), get_stat_mtime (&s2)) < 0)
1276 /* Make the progress messages mention that source is newer. */
1277 newer = 1;
1279 /* If we won't print another message, mention this anyway. */
1280 if (!NILP (nomessage) && !force_load_messages)
1282 Lisp_Object msg_file;
1283 msg_file = Fsubstring (found, make_number (0), make_number (-1));
1284 message_with_string ("Source file `%s' newer than byte-compiled file",
1285 msg_file, 1);
1288 } /* !load_prefer_newer */
1289 UNGCPRO;
1292 else
1294 /* We are loading a source file (*.el). */
1295 if (!NILP (Vload_source_file_function))
1297 Lisp_Object val;
1299 if (fd >= 0)
1301 emacs_close (fd);
1302 clear_unwind_protect (fd_index);
1304 val = call4 (Vload_source_file_function, found, hist_file_name,
1305 NILP (noerror) ? Qnil : Qt,
1306 (NILP (nomessage) || force_load_messages) ? Qnil : Qt);
1307 return unbind_to (count, val);
1311 GCPRO3 (file, found, hist_file_name);
1313 if (fd < 0)
1315 /* We somehow got here with fd == -2, meaning the file is deemed
1316 to be remote. Don't even try to reopen the file locally;
1317 just force a failure. */
1318 stream = NULL;
1319 errno = EINVAL;
1321 else
1323 #ifdef WINDOWSNT
1324 emacs_close (fd);
1325 clear_unwind_protect (fd_index);
1326 efound = ENCODE_FILE (found);
1327 stream = emacs_fopen (SSDATA (efound), fmode);
1328 #else
1329 stream = fdopen (fd, fmode);
1330 #endif
1332 if (! stream)
1333 report_file_error ("Opening stdio stream", file);
1334 set_unwind_protect_ptr (fd_index, fclose_unwind, stream);
1336 if (! NILP (Vpurify_flag))
1337 Vpreloaded_file_list = Fcons (Fpurecopy (file), Vpreloaded_file_list);
1339 if (NILP (nomessage) || force_load_messages)
1341 if (!safe_p)
1342 message_with_string ("Loading %s (compiled; note unsafe, not compiled in Emacs)...",
1343 file, 1);
1344 else if (!compiled)
1345 message_with_string ("Loading %s (source)...", file, 1);
1346 else if (newer)
1347 message_with_string ("Loading %s (compiled; note, source file is newer)...",
1348 file, 1);
1349 else /* The typical case; compiled file newer than source file. */
1350 message_with_string ("Loading %s...", file, 1);
1353 specbind (Qload_file_name, found);
1354 specbind (Qinhibit_file_name_operation, Qnil);
1355 specbind (Qload_in_progress, Qt);
1357 instream = stream;
1358 if (lisp_file_lexically_bound_p (Qget_file_char))
1359 Fset (Qlexical_binding, Qt);
1361 if (! version || version >= 22)
1362 readevalloop (Qget_file_char, stream, hist_file_name,
1363 0, Qnil, Qnil, Qnil, Qnil);
1364 else
1366 /* We can't handle a file which was compiled with
1367 byte-compile-dynamic by older version of Emacs. */
1368 specbind (Qload_force_doc_strings, Qt);
1369 readevalloop (Qget_emacs_mule_file_char, stream, hist_file_name,
1370 0, Qnil, Qnil, Qnil, Qnil);
1372 unbind_to (count, Qnil);
1374 /* Run any eval-after-load forms for this file. */
1375 if (!NILP (Ffboundp (Qdo_after_load_evaluation)))
1376 call1 (Qdo_after_load_evaluation, hist_file_name) ;
1378 UNGCPRO;
1380 xfree (saved_doc_string);
1381 saved_doc_string = 0;
1382 saved_doc_string_size = 0;
1384 xfree (prev_saved_doc_string);
1385 prev_saved_doc_string = 0;
1386 prev_saved_doc_string_size = 0;
1388 if (!noninteractive && (NILP (nomessage) || force_load_messages))
1390 if (!safe_p)
1391 message_with_string ("Loading %s (compiled; note unsafe, not compiled in Emacs)...done",
1392 file, 1);
1393 else if (!compiled)
1394 message_with_string ("Loading %s (source)...done", file, 1);
1395 else if (newer)
1396 message_with_string ("Loading %s (compiled; note, source file is newer)...done",
1397 file, 1);
1398 else /* The typical case; compiled file newer than source file. */
1399 message_with_string ("Loading %s...done", file, 1);
1402 return Qt;
1405 static bool
1406 complete_filename_p (Lisp_Object pathname)
1408 const unsigned char *s = SDATA (pathname);
1409 return (IS_DIRECTORY_SEP (s[0])
1410 || (SCHARS (pathname) > 2
1411 && IS_DEVICE_SEP (s[1]) && IS_DIRECTORY_SEP (s[2])));
1414 DEFUN ("locate-file-internal", Flocate_file_internal, Slocate_file_internal, 2, 4, 0,
1415 doc: /* Search for FILENAME through PATH.
1416 Returns the file's name in absolute form, or nil if not found.
1417 If SUFFIXES is non-nil, it should be a list of suffixes to append to
1418 file name when searching.
1419 If non-nil, PREDICATE is used instead of `file-readable-p'.
1420 PREDICATE can also be an integer to pass to the faccessat(2) function,
1421 in which case file-name-handlers are ignored.
1422 This function will normally skip directories, so if you want it to find
1423 directories, make sure the PREDICATE function returns `dir-ok' for them. */)
1424 (Lisp_Object filename, Lisp_Object path, Lisp_Object suffixes, Lisp_Object predicate)
1426 Lisp_Object file;
1427 int fd = openp (path, filename, suffixes, &file, predicate, false);
1428 if (NILP (predicate) && fd >= 0)
1429 emacs_close (fd);
1430 return file;
1433 static Lisp_Object Qdir_ok;
1435 /* Search for a file whose name is STR, looking in directories
1436 in the Lisp list PATH, and trying suffixes from SUFFIX.
1437 On success, return a file descriptor (or 1 or -2 as described below).
1438 On failure, return -1 and set errno.
1440 SUFFIXES is a list of strings containing possible suffixes.
1441 The empty suffix is automatically added if the list is empty.
1443 PREDICATE non-nil means don't open the files,
1444 just look for one that satisfies the predicate. In this case,
1445 return 1 on success. The predicate can be a lisp function or
1446 an integer to pass to `access' (in which case file-name-handlers
1447 are ignored).
1449 If STOREPTR is nonzero, it points to a slot where the name of
1450 the file actually found should be stored as a Lisp string.
1451 nil is stored there on failure.
1453 If the file we find is remote, return -2
1454 but store the found remote file name in *STOREPTR.
1456 If NEWER is true, try all SUFFIXes and return the result for the
1457 newest file that exists. Does not apply to remote files,
1458 or if PREDICATE is specified. */
1461 openp (Lisp_Object path, Lisp_Object str, Lisp_Object suffixes,
1462 Lisp_Object *storeptr, Lisp_Object predicate, bool newer)
1464 ptrdiff_t fn_size = 100;
1465 char buf[100];
1466 char *fn = buf;
1467 bool absolute;
1468 ptrdiff_t want_length;
1469 Lisp_Object filename;
1470 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6, gcpro7;
1471 Lisp_Object string, tail, encoded_fn, save_string;
1472 ptrdiff_t max_suffix_len = 0;
1473 int last_errno = ENOENT;
1474 int save_fd = -1;
1475 USE_SAFE_ALLOCA;
1477 /* The last-modified time of the newest matching file found.
1478 Initialize it to something less than all valid timestamps. */
1479 struct timespec save_mtime = make_timespec (TYPE_MINIMUM (time_t), -1);
1481 CHECK_STRING (str);
1483 for (tail = suffixes; CONSP (tail); tail = XCDR (tail))
1485 CHECK_STRING_CAR (tail);
1486 max_suffix_len = max (max_suffix_len,
1487 SBYTES (XCAR (tail)));
1490 string = filename = encoded_fn = save_string = Qnil;
1491 GCPRO7 (str, string, save_string, filename, path, suffixes, encoded_fn);
1493 if (storeptr)
1494 *storeptr = Qnil;
1496 absolute = complete_filename_p (str);
1498 for (; CONSP (path); path = XCDR (path))
1500 filename = Fexpand_file_name (str, XCAR (path));
1501 if (!complete_filename_p (filename))
1502 /* If there are non-absolute elts in PATH (eg "."). */
1503 /* Of course, this could conceivably lose if luser sets
1504 default-directory to be something non-absolute... */
1506 filename = Fexpand_file_name (filename, BVAR (current_buffer, directory));
1507 if (!complete_filename_p (filename))
1508 /* Give up on this path element! */
1509 continue;
1512 /* Calculate maximum length of any filename made from
1513 this path element/specified file name and any possible suffix. */
1514 want_length = max_suffix_len + SBYTES (filename);
1515 if (fn_size <= want_length)
1517 fn_size = 100 + want_length;
1518 fn = SAFE_ALLOCA (fn_size);
1521 /* Loop over suffixes. */
1522 for (tail = NILP (suffixes) ? list1 (empty_unibyte_string) : suffixes;
1523 CONSP (tail); tail = XCDR (tail))
1525 Lisp_Object suffix = XCAR (tail);
1526 ptrdiff_t fnlen, lsuffix = SBYTES (suffix);
1527 Lisp_Object handler;
1529 /* Concatenate path element/specified name with the suffix.
1530 If the directory starts with /:, remove that. */
1531 int prefixlen = ((SCHARS (filename) > 2
1532 && SREF (filename, 0) == '/'
1533 && SREF (filename, 1) == ':')
1534 ? 2 : 0);
1535 fnlen = SBYTES (filename) - prefixlen;
1536 memcpy (fn, SDATA (filename) + prefixlen, fnlen);
1537 memcpy (fn + fnlen, SDATA (suffix), lsuffix + 1);
1538 fnlen += lsuffix;
1539 /* Check that the file exists and is not a directory. */
1540 /* We used to only check for handlers on non-absolute file names:
1541 if (absolute)
1542 handler = Qnil;
1543 else
1544 handler = Ffind_file_name_handler (filename, Qfile_exists_p);
1545 It's not clear why that was the case and it breaks things like
1546 (load "/bar.el") where the file is actually "/bar.el.gz". */
1547 /* make_string has its own ideas on when to return a unibyte
1548 string and when a multibyte string, but we know better.
1549 We must have a unibyte string when dumping, since
1550 file-name encoding is shaky at best at that time, and in
1551 particular default-file-name-coding-system is reset
1552 several times during loadup. We therefore don't want to
1553 encode the file before passing it to file I/O library
1554 functions. */
1555 if (!STRING_MULTIBYTE (filename) && !STRING_MULTIBYTE (suffix))
1556 string = make_unibyte_string (fn, fnlen);
1557 else
1558 string = make_string (fn, fnlen);
1559 handler = Ffind_file_name_handler (string, Qfile_exists_p);
1560 if ((!NILP (handler) || !NILP (predicate)) && !NATNUMP (predicate))
1562 bool exists;
1563 if (NILP (predicate))
1564 exists = !NILP (Ffile_readable_p (string));
1565 else
1567 Lisp_Object tmp = call1 (predicate, string);
1568 if (NILP (tmp))
1569 exists = false;
1570 else if (EQ (tmp, Qdir_ok)
1571 || NILP (Ffile_directory_p (string)))
1572 exists = true;
1573 else
1575 exists = false;
1576 last_errno = EISDIR;
1580 if (exists)
1582 /* We succeeded; return this descriptor and filename. */
1583 if (storeptr)
1584 *storeptr = string;
1585 SAFE_FREE ();
1586 UNGCPRO;
1587 return -2;
1590 else
1592 int fd;
1593 const char *pfn;
1594 struct stat st;
1596 encoded_fn = ENCODE_FILE (string);
1597 pfn = SSDATA (encoded_fn);
1599 /* Check that we can access or open it. */
1600 if (NATNUMP (predicate))
1602 fd = -1;
1603 if (INT_MAX < XFASTINT (predicate))
1604 last_errno = EINVAL;
1605 else if (faccessat (AT_FDCWD, pfn, XFASTINT (predicate),
1606 AT_EACCESS)
1607 == 0)
1609 if (file_directory_p (pfn))
1610 last_errno = EISDIR;
1611 else
1612 fd = 1;
1615 else
1617 fd = emacs_open (pfn, O_RDONLY, 0);
1618 if (fd < 0)
1620 if (errno != ENOENT)
1621 last_errno = errno;
1623 else
1625 int err = (fstat (fd, &st) != 0 ? errno
1626 : S_ISDIR (st.st_mode) ? EISDIR : 0);
1627 if (err)
1629 last_errno = err;
1630 emacs_close (fd);
1631 fd = -1;
1636 if (fd >= 0)
1638 if (newer && !NATNUMP (predicate))
1640 struct timespec mtime = get_stat_mtime (&st);
1642 if (timespec_cmp (mtime, save_mtime) <= 0)
1643 emacs_close (fd);
1644 else
1646 if (0 <= save_fd)
1647 emacs_close (save_fd);
1648 save_fd = fd;
1649 save_mtime = mtime;
1650 save_string = string;
1653 else
1655 /* We succeeded; return this descriptor and filename. */
1656 if (storeptr)
1657 *storeptr = string;
1658 SAFE_FREE ();
1659 UNGCPRO;
1660 return fd;
1664 /* No more suffixes. Return the newest. */
1665 if (0 <= save_fd && ! CONSP (XCDR (tail)))
1667 if (storeptr)
1668 *storeptr = save_string;
1669 SAFE_FREE ();
1670 UNGCPRO;
1671 return save_fd;
1675 if (absolute)
1676 break;
1679 SAFE_FREE ();
1680 UNGCPRO;
1681 errno = last_errno;
1682 return -1;
1686 /* Merge the list we've accumulated of globals from the current input source
1687 into the load_history variable. The details depend on whether
1688 the source has an associated file name or not.
1690 FILENAME is the file name that we are loading from.
1692 ENTIRE is true if loading that entire file, false if evaluating
1693 part of it. */
1695 static void
1696 build_load_history (Lisp_Object filename, bool entire)
1698 Lisp_Object tail, prev, newelt;
1699 Lisp_Object tem, tem2;
1700 bool foundit = 0;
1702 tail = Vload_history;
1703 prev = Qnil;
1705 while (CONSP (tail))
1707 tem = XCAR (tail);
1709 /* Find the feature's previous assoc list... */
1710 if (!NILP (Fequal (filename, Fcar (tem))))
1712 foundit = 1;
1714 /* If we're loading the entire file, remove old data. */
1715 if (entire)
1717 if (NILP (prev))
1718 Vload_history = XCDR (tail);
1719 else
1720 Fsetcdr (prev, XCDR (tail));
1723 /* Otherwise, cons on new symbols that are not already members. */
1724 else
1726 tem2 = Vcurrent_load_list;
1728 while (CONSP (tem2))
1730 newelt = XCAR (tem2);
1732 if (NILP (Fmember (newelt, tem)))
1733 Fsetcar (tail, Fcons (XCAR (tem),
1734 Fcons (newelt, XCDR (tem))));
1736 tem2 = XCDR (tem2);
1737 QUIT;
1741 else
1742 prev = tail;
1743 tail = XCDR (tail);
1744 QUIT;
1747 /* If we're loading an entire file, cons the new assoc onto the
1748 front of load-history, the most-recently-loaded position. Also
1749 do this if we didn't find an existing member for the file. */
1750 if (entire || !foundit)
1751 Vload_history = Fcons (Fnreverse (Vcurrent_load_list),
1752 Vload_history);
1755 static void
1756 readevalloop_1 (int old)
1758 load_convert_to_unibyte = old;
1761 /* Signal an `end-of-file' error, if possible with file name
1762 information. */
1764 static _Noreturn void
1765 end_of_file_error (void)
1767 if (STRINGP (Vload_file_name))
1768 xsignal1 (Qend_of_file, Vload_file_name);
1770 xsignal0 (Qend_of_file);
1773 static Lisp_Object
1774 readevalloop_eager_expand_eval (Lisp_Object val, Lisp_Object macroexpand)
1776 /* If we macroexpand the toplevel form non-recursively and it ends
1777 up being a `progn' (or if it was a progn to start), treat each
1778 form in the progn as a top-level form. This way, if one form in
1779 the progn defines a macro, that macro is in effect when we expand
1780 the remaining forms. See similar code in bytecomp.el. */
1781 val = call2 (macroexpand, val, Qnil);
1782 if (EQ (CAR_SAFE (val), Qprogn))
1784 struct gcpro gcpro1;
1785 Lisp_Object subforms = XCDR (val);
1787 GCPRO1 (subforms);
1788 for (val = Qnil; CONSP (subforms); subforms = XCDR (subforms))
1789 val = readevalloop_eager_expand_eval (XCAR (subforms),
1790 macroexpand);
1791 UNGCPRO;
1793 else
1794 val = eval_sub (call2 (macroexpand, val, Qt));
1795 return val;
1798 /* UNIBYTE specifies how to set load_convert_to_unibyte
1799 for this invocation.
1800 READFUN, if non-nil, is used instead of `read'.
1802 START, END specify region to read in current buffer (from eval-region).
1803 If the input is not from a buffer, they must be nil. */
1805 static void
1806 readevalloop (Lisp_Object readcharfun,
1807 FILE *stream,
1808 Lisp_Object sourcename,
1809 bool printflag,
1810 Lisp_Object unibyte, Lisp_Object readfun,
1811 Lisp_Object start, Lisp_Object end)
1813 register int c;
1814 register Lisp_Object val;
1815 ptrdiff_t count = SPECPDL_INDEX ();
1816 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1817 struct buffer *b = 0;
1818 bool continue_reading_p;
1819 Lisp_Object lex_bound;
1820 /* True if reading an entire buffer. */
1821 bool whole_buffer = 0;
1822 /* True on the first time around. */
1823 bool first_sexp = 1;
1824 Lisp_Object macroexpand = intern ("internal-macroexpand-for-load");
1826 if (NILP (Ffboundp (macroexpand))
1827 /* Don't macroexpand in .elc files, since it should have been done
1828 already. We actually don't know whether we're in a .elc file or not,
1829 so we use circumstantial evidence: .el files normally go through
1830 Vload_source_file_function -> load-with-code-conversion
1831 -> eval-buffer. */
1832 || EQ (readcharfun, Qget_file_char)
1833 || EQ (readcharfun, Qget_emacs_mule_file_char))
1834 macroexpand = Qnil;
1836 if (MARKERP (readcharfun))
1838 if (NILP (start))
1839 start = readcharfun;
1842 if (BUFFERP (readcharfun))
1843 b = XBUFFER (readcharfun);
1844 else if (MARKERP (readcharfun))
1845 b = XMARKER (readcharfun)->buffer;
1847 /* We assume START is nil when input is not from a buffer. */
1848 if (! NILP (start) && !b)
1849 emacs_abort ();
1851 specbind (Qstandard_input, readcharfun); /* GCPROs readcharfun. */
1852 specbind (Qcurrent_load_list, Qnil);
1853 record_unwind_protect_int (readevalloop_1, load_convert_to_unibyte);
1854 load_convert_to_unibyte = !NILP (unibyte);
1856 /* If lexical binding is active (either because it was specified in
1857 the file's header, or via a buffer-local variable), create an empty
1858 lexical environment, otherwise, turn off lexical binding. */
1859 lex_bound = find_symbol_value (Qlexical_binding);
1860 specbind (Qinternal_interpreter_environment,
1861 (NILP (lex_bound) || EQ (lex_bound, Qunbound)
1862 ? Qnil : list1 (Qt)));
1864 GCPRO4 (sourcename, readfun, start, end);
1866 /* Try to ensure sourcename is a truename, except whilst preloading. */
1867 if (NILP (Vpurify_flag)
1868 && !NILP (sourcename) && !NILP (Ffile_name_absolute_p (sourcename))
1869 && !NILP (Ffboundp (Qfile_truename)))
1870 sourcename = call1 (Qfile_truename, sourcename) ;
1872 LOADHIST_ATTACH (sourcename);
1874 continue_reading_p = 1;
1875 while (continue_reading_p)
1877 ptrdiff_t count1 = SPECPDL_INDEX ();
1879 if (b != 0 && !BUFFER_LIVE_P (b))
1880 error ("Reading from killed buffer");
1882 if (!NILP (start))
1884 /* Switch to the buffer we are reading from. */
1885 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1886 set_buffer_internal (b);
1888 /* Save point in it. */
1889 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1890 /* Save ZV in it. */
1891 record_unwind_protect (save_restriction_restore, save_restriction_save ());
1892 /* Those get unbound after we read one expression. */
1894 /* Set point and ZV around stuff to be read. */
1895 Fgoto_char (start);
1896 if (!NILP (end))
1897 Fnarrow_to_region (make_number (BEGV), end);
1899 /* Just for cleanliness, convert END to a marker
1900 if it is an integer. */
1901 if (INTEGERP (end))
1902 end = Fpoint_max_marker ();
1905 /* On the first cycle, we can easily test here
1906 whether we are reading the whole buffer. */
1907 if (b && first_sexp)
1908 whole_buffer = (PT == BEG && ZV == Z);
1910 instream = stream;
1911 read_next:
1912 c = READCHAR;
1913 if (c == ';')
1915 while ((c = READCHAR) != '\n' && c != -1);
1916 goto read_next;
1918 if (c < 0)
1920 unbind_to (count1, Qnil);
1921 break;
1924 /* Ignore whitespace here, so we can detect eof. */
1925 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'
1926 || c == 0xa0) /* NBSP */
1927 goto read_next;
1929 if (!NILP (Vpurify_flag) && c == '(')
1931 val = read_list (0, readcharfun);
1933 else
1935 UNREAD (c);
1936 read_objects = Qnil;
1937 if (!NILP (readfun))
1939 val = call1 (readfun, readcharfun);
1941 /* If READCHARFUN has set point to ZV, we should
1942 stop reading, even if the form read sets point
1943 to a different value when evaluated. */
1944 if (BUFFERP (readcharfun))
1946 struct buffer *buf = XBUFFER (readcharfun);
1947 if (BUF_PT (buf) == BUF_ZV (buf))
1948 continue_reading_p = 0;
1951 else if (! NILP (Vload_read_function))
1952 val = call1 (Vload_read_function, readcharfun);
1953 else
1954 val = read_internal_start (readcharfun, Qnil, Qnil);
1957 if (!NILP (start) && continue_reading_p)
1958 start = Fpoint_marker ();
1960 /* Restore saved point and BEGV. */
1961 unbind_to (count1, Qnil);
1963 /* Now eval what we just read. */
1964 if (!NILP (macroexpand))
1965 val = readevalloop_eager_expand_eval (val, macroexpand);
1966 else
1967 val = eval_sub (val);
1969 if (printflag)
1971 Vvalues = Fcons (val, Vvalues);
1972 if (EQ (Vstandard_output, Qt))
1973 Fprin1 (val, Qnil);
1974 else
1975 Fprint (val, Qnil);
1978 first_sexp = 0;
1981 build_load_history (sourcename,
1982 stream || whole_buffer);
1984 UNGCPRO;
1986 unbind_to (count, Qnil);
1989 DEFUN ("eval-buffer", Feval_buffer, Seval_buffer, 0, 5, "",
1990 doc: /* Execute the current buffer as Lisp code.
1991 When called from a Lisp program (i.e., not interactively), this
1992 function accepts up to five optional arguments:
1993 BUFFER is the buffer to evaluate (nil means use current buffer).
1994 PRINTFLAG controls printing of output:
1995 A value of nil means discard it; anything else is stream for print.
1996 FILENAME specifies the file name to use for `load-history'.
1997 UNIBYTE, if non-nil, specifies `load-convert-to-unibyte' for this
1998 invocation.
1999 DO-ALLOW-PRINT, if non-nil, specifies that `print' and related
2000 functions should work normally even if PRINTFLAG is nil.
2002 This function preserves the position of point. */)
2003 (Lisp_Object buffer, Lisp_Object printflag, Lisp_Object filename, Lisp_Object unibyte, Lisp_Object do_allow_print)
2005 ptrdiff_t count = SPECPDL_INDEX ();
2006 Lisp_Object tem, buf;
2008 if (NILP (buffer))
2009 buf = Fcurrent_buffer ();
2010 else
2011 buf = Fget_buffer (buffer);
2012 if (NILP (buf))
2013 error ("No such buffer");
2015 if (NILP (printflag) && NILP (do_allow_print))
2016 tem = Qsymbolp;
2017 else
2018 tem = printflag;
2020 if (NILP (filename))
2021 filename = BVAR (XBUFFER (buf), filename);
2023 specbind (Qeval_buffer_list, Fcons (buf, Veval_buffer_list));
2024 specbind (Qstandard_output, tem);
2025 record_unwind_protect (save_excursion_restore, save_excursion_save ());
2026 BUF_TEMP_SET_PT (XBUFFER (buf), BUF_BEGV (XBUFFER (buf)));
2027 specbind (Qlexical_binding, lisp_file_lexically_bound_p (buf) ? Qt : Qnil);
2028 readevalloop (buf, 0, filename,
2029 !NILP (printflag), unibyte, Qnil, Qnil, Qnil);
2030 unbind_to (count, Qnil);
2032 return Qnil;
2035 DEFUN ("eval-region", Feval_region, Seval_region, 2, 4, "r",
2036 doc: /* Execute the region as Lisp code.
2037 When called from programs, expects two arguments,
2038 giving starting and ending indices in the current buffer
2039 of the text to be executed.
2040 Programs can pass third argument PRINTFLAG which controls output:
2041 A value of nil means discard it; anything else is stream for printing it.
2042 Also the fourth argument READ-FUNCTION, if non-nil, is used
2043 instead of `read' to read each expression. It gets one argument
2044 which is the input stream for reading characters.
2046 This function does not move point. */)
2047 (Lisp_Object start, Lisp_Object end, Lisp_Object printflag, Lisp_Object read_function)
2049 /* FIXME: Do the eval-sexp-add-defvars dance! */
2050 ptrdiff_t count = SPECPDL_INDEX ();
2051 Lisp_Object tem, cbuf;
2053 cbuf = Fcurrent_buffer ();
2055 if (NILP (printflag))
2056 tem = Qsymbolp;
2057 else
2058 tem = printflag;
2059 specbind (Qstandard_output, tem);
2060 specbind (Qeval_buffer_list, Fcons (cbuf, Veval_buffer_list));
2062 /* `readevalloop' calls functions which check the type of start and end. */
2063 readevalloop (cbuf, 0, BVAR (XBUFFER (cbuf), filename),
2064 !NILP (printflag), Qnil, read_function,
2065 start, end);
2067 return unbind_to (count, Qnil);
2071 DEFUN ("read", Fread, Sread, 0, 1, 0,
2072 doc: /* Read one Lisp expression as text from STREAM, return as Lisp object.
2073 If STREAM is nil, use the value of `standard-input' (which see).
2074 STREAM or the value of `standard-input' may be:
2075 a buffer (read from point and advance it)
2076 a marker (read from where it points and advance it)
2077 a function (call it with no arguments for each character,
2078 call it with a char as argument to push a char back)
2079 a string (takes text from string, starting at the beginning)
2080 t (read text line using minibuffer and use it, or read from
2081 standard input in batch mode). */)
2082 (Lisp_Object stream)
2084 if (NILP (stream))
2085 stream = Vstandard_input;
2086 if (EQ (stream, Qt))
2087 stream = Qread_char;
2088 if (EQ (stream, Qread_char))
2089 /* FIXME: ?! When is this used !? */
2090 return call1 (intern ("read-minibuffer"),
2091 build_string ("Lisp expression: "));
2093 return read_internal_start (stream, Qnil, Qnil);
2096 DEFUN ("read-from-string", Fread_from_string, Sread_from_string, 1, 3, 0,
2097 doc: /* Read one Lisp expression which is represented as text by STRING.
2098 Returns a cons: (OBJECT-READ . FINAL-STRING-INDEX).
2099 FINAL-STRING-INDEX is an integer giving the position of the next
2100 remaining character in STRING. START and END optionally delimit
2101 a substring of STRING from which to read; they default to 0 and
2102 (length STRING) respectively. Negative values are counted from
2103 the end of STRING. */)
2104 (Lisp_Object string, Lisp_Object start, Lisp_Object end)
2106 Lisp_Object ret;
2107 CHECK_STRING (string);
2108 /* `read_internal_start' sets `read_from_string_index'. */
2109 ret = read_internal_start (string, start, end);
2110 return Fcons (ret, make_number (read_from_string_index));
2113 /* Function to set up the global context we need in toplevel read
2114 calls. START and END only used when STREAM is a string. */
2115 static Lisp_Object
2116 read_internal_start (Lisp_Object stream, Lisp_Object start, Lisp_Object end)
2118 Lisp_Object retval;
2120 readchar_count = 0;
2121 new_backquote_flag = 0;
2122 read_objects = Qnil;
2123 if (EQ (Vread_with_symbol_positions, Qt)
2124 || EQ (Vread_with_symbol_positions, stream))
2125 Vread_symbol_positions_list = Qnil;
2127 if (STRINGP (stream)
2128 || ((CONSP (stream) && STRINGP (XCAR (stream)))))
2130 ptrdiff_t startval, endval;
2131 Lisp_Object string;
2133 if (STRINGP (stream))
2134 string = stream;
2135 else
2136 string = XCAR (stream);
2138 validate_subarray (string, start, end, SCHARS (string),
2139 &startval, &endval);
2141 read_from_string_index = startval;
2142 read_from_string_index_byte = string_char_to_byte (string, startval);
2143 read_from_string_limit = endval;
2146 retval = read0 (stream);
2147 if (EQ (Vread_with_symbol_positions, Qt)
2148 || EQ (Vread_with_symbol_positions, stream))
2149 Vread_symbol_positions_list = Fnreverse (Vread_symbol_positions_list);
2150 return retval;
2154 /* Signal Qinvalid_read_syntax error.
2155 S is error string of length N (if > 0) */
2157 static _Noreturn void
2158 invalid_syntax (const char *s)
2160 xsignal1 (Qinvalid_read_syntax, build_string (s));
2164 /* Use this for recursive reads, in contexts where internal tokens
2165 are not allowed. */
2167 static Lisp_Object
2168 read0 (Lisp_Object readcharfun)
2170 register Lisp_Object val;
2171 int c;
2173 val = read1 (readcharfun, &c, 0);
2174 if (!c)
2175 return val;
2177 xsignal1 (Qinvalid_read_syntax,
2178 Fmake_string (make_number (1), make_number (c)));
2181 static ptrdiff_t read_buffer_size;
2182 static char *read_buffer;
2184 /* Read a \-escape sequence, assuming we already read the `\'.
2185 If the escape sequence forces unibyte, return eight-bit char. */
2187 static int
2188 read_escape (Lisp_Object readcharfun, bool stringp)
2190 int c = READCHAR;
2191 /* \u allows up to four hex digits, \U up to eight. Default to the
2192 behavior for \u, and change this value in the case that \U is seen. */
2193 int unicode_hex_count = 4;
2195 switch (c)
2197 case -1:
2198 end_of_file_error ();
2200 case 'a':
2201 return '\007';
2202 case 'b':
2203 return '\b';
2204 case 'd':
2205 return 0177;
2206 case 'e':
2207 return 033;
2208 case 'f':
2209 return '\f';
2210 case 'n':
2211 return '\n';
2212 case 'r':
2213 return '\r';
2214 case 't':
2215 return '\t';
2216 case 'v':
2217 return '\v';
2218 case '\n':
2219 return -1;
2220 case ' ':
2221 if (stringp)
2222 return -1;
2223 return ' ';
2225 case 'M':
2226 c = READCHAR;
2227 if (c != '-')
2228 error ("Invalid escape character syntax");
2229 c = READCHAR;
2230 if (c == '\\')
2231 c = read_escape (readcharfun, 0);
2232 return c | meta_modifier;
2234 case 'S':
2235 c = READCHAR;
2236 if (c != '-')
2237 error ("Invalid escape character syntax");
2238 c = READCHAR;
2239 if (c == '\\')
2240 c = read_escape (readcharfun, 0);
2241 return c | shift_modifier;
2243 case 'H':
2244 c = READCHAR;
2245 if (c != '-')
2246 error ("Invalid escape character syntax");
2247 c = READCHAR;
2248 if (c == '\\')
2249 c = read_escape (readcharfun, 0);
2250 return c | hyper_modifier;
2252 case 'A':
2253 c = READCHAR;
2254 if (c != '-')
2255 error ("Invalid escape character syntax");
2256 c = READCHAR;
2257 if (c == '\\')
2258 c = read_escape (readcharfun, 0);
2259 return c | alt_modifier;
2261 case 's':
2262 c = READCHAR;
2263 if (stringp || c != '-')
2265 UNREAD (c);
2266 return ' ';
2268 c = READCHAR;
2269 if (c == '\\')
2270 c = read_escape (readcharfun, 0);
2271 return c | super_modifier;
2273 case 'C':
2274 c = READCHAR;
2275 if (c != '-')
2276 error ("Invalid escape character syntax");
2277 case '^':
2278 c = READCHAR;
2279 if (c == '\\')
2280 c = read_escape (readcharfun, 0);
2281 if ((c & ~CHAR_MODIFIER_MASK) == '?')
2282 return 0177 | (c & CHAR_MODIFIER_MASK);
2283 else if (! SINGLE_BYTE_CHAR_P ((c & ~CHAR_MODIFIER_MASK)))
2284 return c | ctrl_modifier;
2285 /* ASCII control chars are made from letters (both cases),
2286 as well as the non-letters within 0100...0137. */
2287 else if ((c & 0137) >= 0101 && (c & 0137) <= 0132)
2288 return (c & (037 | ~0177));
2289 else if ((c & 0177) >= 0100 && (c & 0177) <= 0137)
2290 return (c & (037 | ~0177));
2291 else
2292 return c | ctrl_modifier;
2294 case '0':
2295 case '1':
2296 case '2':
2297 case '3':
2298 case '4':
2299 case '5':
2300 case '6':
2301 case '7':
2302 /* An octal escape, as in ANSI C. */
2304 register int i = c - '0';
2305 register int count = 0;
2306 while (++count < 3)
2308 if ((c = READCHAR) >= '0' && c <= '7')
2310 i *= 8;
2311 i += c - '0';
2313 else
2315 UNREAD (c);
2316 break;
2320 if (i >= 0x80 && i < 0x100)
2321 i = BYTE8_TO_CHAR (i);
2322 return i;
2325 case 'x':
2326 /* A hex escape, as in ANSI C. */
2328 unsigned int i = 0;
2329 int count = 0;
2330 while (1)
2332 c = READCHAR;
2333 if (c >= '0' && c <= '9')
2335 i *= 16;
2336 i += c - '0';
2338 else if ((c >= 'a' && c <= 'f')
2339 || (c >= 'A' && c <= 'F'))
2341 i *= 16;
2342 if (c >= 'a' && c <= 'f')
2343 i += c - 'a' + 10;
2344 else
2345 i += c - 'A' + 10;
2347 else
2349 UNREAD (c);
2350 break;
2352 /* Allow hex escapes as large as ?\xfffffff, because some
2353 packages use them to denote characters with modifiers. */
2354 if ((CHAR_META | (CHAR_META - 1)) < i)
2355 error ("Hex character out of range: \\x%x...", i);
2356 count += count < 3;
2359 if (count < 3 && i >= 0x80)
2360 return BYTE8_TO_CHAR (i);
2361 return i;
2364 case 'U':
2365 /* Post-Unicode-2.0: Up to eight hex chars. */
2366 unicode_hex_count = 8;
2367 case 'u':
2369 /* A Unicode escape. We only permit them in strings and characters,
2370 not arbitrarily in the source code, as in some other languages. */
2372 unsigned int i = 0;
2373 int count = 0;
2375 while (++count <= unicode_hex_count)
2377 c = READCHAR;
2378 /* `isdigit' and `isalpha' may be locale-specific, which we don't
2379 want. */
2380 if (c >= '0' && c <= '9') i = (i << 4) + (c - '0');
2381 else if (c >= 'a' && c <= 'f') i = (i << 4) + (c - 'a') + 10;
2382 else if (c >= 'A' && c <= 'F') i = (i << 4) + (c - 'A') + 10;
2383 else
2384 error ("Non-hex digit used for Unicode escape");
2386 if (i > 0x10FFFF)
2387 error ("Non-Unicode character: 0x%x", i);
2388 return i;
2391 default:
2392 return c;
2396 /* Return the digit that CHARACTER stands for in the given BASE.
2397 Return -1 if CHARACTER is out of range for BASE,
2398 and -2 if CHARACTER is not valid for any supported BASE. */
2399 static int
2400 digit_to_number (int character, int base)
2402 int digit;
2404 if ('0' <= character && character <= '9')
2405 digit = character - '0';
2406 else if ('a' <= character && character <= 'z')
2407 digit = character - 'a' + 10;
2408 else if ('A' <= character && character <= 'Z')
2409 digit = character - 'A' + 10;
2410 else
2411 return -2;
2413 return digit < base ? digit : -1;
2416 /* Read an integer in radix RADIX using READCHARFUN to read
2417 characters. RADIX must be in the interval [2..36]; if it isn't, a
2418 read error is signaled . Value is the integer read. Signals an
2419 error if encountering invalid read syntax or if RADIX is out of
2420 range. */
2422 static Lisp_Object
2423 read_integer (Lisp_Object readcharfun, EMACS_INT radix)
2425 /* Room for sign, leading 0, other digits, trailing null byte.
2426 Also, room for invalid syntax diagnostic. */
2427 char buf[max (1 + 1 + sizeof (uintmax_t) * CHAR_BIT + 1,
2428 sizeof "integer, radix " + INT_STRLEN_BOUND (EMACS_INT))];
2430 int valid = -1; /* 1 if valid, 0 if not, -1 if incomplete. */
2432 if (radix < 2 || radix > 36)
2433 valid = 0;
2434 else
2436 char *p = buf;
2437 int c, digit;
2439 c = READCHAR;
2440 if (c == '-' || c == '+')
2442 *p++ = c;
2443 c = READCHAR;
2446 if (c == '0')
2448 *p++ = c;
2449 valid = 1;
2451 /* Ignore redundant leading zeros, so the buffer doesn't
2452 fill up with them. */
2454 c = READCHAR;
2455 while (c == '0');
2458 while ((digit = digit_to_number (c, radix)) >= -1)
2460 if (digit == -1)
2461 valid = 0;
2462 if (valid < 0)
2463 valid = 1;
2465 if (p < buf + sizeof buf - 1)
2466 *p++ = c;
2467 else
2468 valid = 0;
2470 c = READCHAR;
2473 UNREAD (c);
2474 *p = '\0';
2477 if (! valid)
2479 sprintf (buf, "integer, radix %"pI"d", radix);
2480 invalid_syntax (buf);
2483 return string_to_number (buf, radix, 0);
2487 /* If the next token is ')' or ']' or '.', we store that character
2488 in *PCH and the return value is not interesting. Else, we store
2489 zero in *PCH and we read and return one lisp object.
2491 FIRST_IN_LIST is true if this is the first element of a list. */
2493 static Lisp_Object
2494 read1 (Lisp_Object readcharfun, int *pch, bool first_in_list)
2496 int c;
2497 bool uninterned_symbol = 0;
2498 bool multibyte;
2500 *pch = 0;
2502 retry:
2504 c = READCHAR_REPORT_MULTIBYTE (&multibyte);
2505 if (c < 0)
2506 end_of_file_error ();
2508 switch (c)
2510 case '(':
2511 return read_list (0, readcharfun);
2513 case '[':
2514 return read_vector (readcharfun, 0);
2516 case ')':
2517 case ']':
2519 *pch = c;
2520 return Qnil;
2523 case '#':
2524 c = READCHAR;
2525 if (c == 's')
2527 c = READCHAR;
2528 if (c == '(')
2530 /* Accept extended format for hashtables (extensible to
2531 other types), e.g.
2532 #s(hash-table size 2 test equal data (k1 v1 k2 v2)) */
2533 Lisp_Object tmp = read_list (0, readcharfun);
2534 Lisp_Object head = CAR_SAFE (tmp);
2535 Lisp_Object data = Qnil;
2536 Lisp_Object val = Qnil;
2537 /* The size is 2 * number of allowed keywords to
2538 make-hash-table. */
2539 Lisp_Object params[10];
2540 Lisp_Object ht;
2541 Lisp_Object key = Qnil;
2542 int param_count = 0;
2544 if (!EQ (head, Qhash_table))
2545 error ("Invalid extended read marker at head of #s list "
2546 "(only hash-table allowed)");
2548 tmp = CDR_SAFE (tmp);
2550 /* This is repetitive but fast and simple. */
2551 params[param_count] = QCsize;
2552 params[param_count + 1] = Fplist_get (tmp, Qsize);
2553 if (!NILP (params[param_count + 1]))
2554 param_count += 2;
2556 params[param_count] = QCtest;
2557 params[param_count + 1] = Fplist_get (tmp, Qtest);
2558 if (!NILP (params[param_count + 1]))
2559 param_count += 2;
2561 params[param_count] = QCweakness;
2562 params[param_count + 1] = Fplist_get (tmp, Qweakness);
2563 if (!NILP (params[param_count + 1]))
2564 param_count += 2;
2566 params[param_count] = QCrehash_size;
2567 params[param_count + 1] = Fplist_get (tmp, Qrehash_size);
2568 if (!NILP (params[param_count + 1]))
2569 param_count += 2;
2571 params[param_count] = QCrehash_threshold;
2572 params[param_count + 1] = Fplist_get (tmp, Qrehash_threshold);
2573 if (!NILP (params[param_count + 1]))
2574 param_count += 2;
2576 /* This is the hashtable data. */
2577 data = Fplist_get (tmp, Qdata);
2579 /* Now use params to make a new hashtable and fill it. */
2580 ht = Fmake_hash_table (param_count, params);
2582 while (CONSP (data))
2584 key = XCAR (data);
2585 data = XCDR (data);
2586 if (!CONSP (data))
2587 error ("Odd number of elements in hashtable data");
2588 val = XCAR (data);
2589 data = XCDR (data);
2590 Fputhash (key, val, ht);
2593 return ht;
2595 UNREAD (c);
2596 invalid_syntax ("#");
2598 if (c == '^')
2600 c = READCHAR;
2601 if (c == '[')
2603 Lisp_Object tmp;
2604 tmp = read_vector (readcharfun, 0);
2605 if (ASIZE (tmp) < CHAR_TABLE_STANDARD_SLOTS)
2606 error ("Invalid size char-table");
2607 XSETPVECTYPE (XVECTOR (tmp), PVEC_CHAR_TABLE);
2608 return tmp;
2610 else if (c == '^')
2612 c = READCHAR;
2613 if (c == '[')
2615 /* Sub char-table can't be read as a regular
2616 vector because of a two C integer fields. */
2617 Lisp_Object tbl, tmp = read_list (1, readcharfun);
2618 ptrdiff_t size = XINT (Flength (tmp));
2619 int i, depth, min_char;
2620 struct Lisp_Cons *cell;
2622 if (size == 0)
2623 error ("Zero-sized sub char-table");
2625 if (! RANGED_INTEGERP (1, XCAR (tmp), 3))
2626 error ("Invalid depth in sub char-table");
2627 depth = XINT (XCAR (tmp));
2628 if (chartab_size[depth] != size - 2)
2629 error ("Invalid size in sub char-table");
2630 cell = XCONS (tmp), tmp = XCDR (tmp), size--;
2631 free_cons (cell);
2633 if (! RANGED_INTEGERP (0, XCAR (tmp), MAX_CHAR))
2634 error ("Invalid minimum character in sub-char-table");
2635 min_char = XINT (XCAR (tmp));
2636 cell = XCONS (tmp), tmp = XCDR (tmp), size--;
2637 free_cons (cell);
2639 tbl = make_uninit_sub_char_table (depth, min_char);
2640 for (i = 0; i < size; i++)
2642 XSUB_CHAR_TABLE (tbl)->contents[i] = XCAR (tmp);
2643 cell = XCONS (tmp), tmp = XCDR (tmp);
2644 free_cons (cell);
2646 return tbl;
2648 invalid_syntax ("#^^");
2650 invalid_syntax ("#^");
2652 if (c == '&')
2654 Lisp_Object length;
2655 length = read1 (readcharfun, pch, first_in_list);
2656 c = READCHAR;
2657 if (c == '"')
2659 Lisp_Object tmp, val;
2660 EMACS_INT size_in_chars = bool_vector_bytes (XFASTINT (length));
2661 unsigned char *data;
2663 UNREAD (c);
2664 tmp = read1 (readcharfun, pch, first_in_list);
2665 if (STRING_MULTIBYTE (tmp)
2666 || (size_in_chars != SCHARS (tmp)
2667 /* We used to print 1 char too many
2668 when the number of bits was a multiple of 8.
2669 Accept such input in case it came from an old
2670 version. */
2671 && ! (XFASTINT (length)
2672 == (SCHARS (tmp) - 1) * BOOL_VECTOR_BITS_PER_CHAR)))
2673 invalid_syntax ("#&...");
2675 val = make_uninit_bool_vector (XFASTINT (length));
2676 data = bool_vector_uchar_data (val);
2677 memcpy (data, SDATA (tmp), size_in_chars);
2678 /* Clear the extraneous bits in the last byte. */
2679 if (XINT (length) != size_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2680 data[size_in_chars - 1]
2681 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2682 return val;
2684 invalid_syntax ("#&...");
2686 if (c == '[')
2688 /* Accept compiled functions at read-time so that we don't have to
2689 build them using function calls. */
2690 Lisp_Object tmp;
2691 struct Lisp_Vector *vec;
2692 tmp = read_vector (readcharfun, 1);
2693 vec = XVECTOR (tmp);
2694 if (vec->header.size == 0)
2695 invalid_syntax ("Empty byte-code object");
2696 make_byte_code (vec);
2697 return tmp;
2699 if (c == '(')
2701 Lisp_Object tmp;
2702 struct gcpro gcpro1;
2703 int ch;
2705 /* Read the string itself. */
2706 tmp = read1 (readcharfun, &ch, 0);
2707 if (ch != 0 || !STRINGP (tmp))
2708 invalid_syntax ("#");
2709 GCPRO1 (tmp);
2710 /* Read the intervals and their properties. */
2711 while (1)
2713 Lisp_Object beg, end, plist;
2715 beg = read1 (readcharfun, &ch, 0);
2716 end = plist = Qnil;
2717 if (ch == ')')
2718 break;
2719 if (ch == 0)
2720 end = read1 (readcharfun, &ch, 0);
2721 if (ch == 0)
2722 plist = read1 (readcharfun, &ch, 0);
2723 if (ch)
2724 invalid_syntax ("Invalid string property list");
2725 Fset_text_properties (beg, end, plist, tmp);
2727 UNGCPRO;
2728 return tmp;
2731 /* #@NUMBER is used to skip NUMBER following bytes.
2732 That's used in .elc files to skip over doc strings
2733 and function definitions. */
2734 if (c == '@')
2736 enum { extra = 100 };
2737 ptrdiff_t i, nskip = 0, digits = 0;
2739 /* Read a decimal integer. */
2740 while ((c = READCHAR) >= 0
2741 && c >= '0' && c <= '9')
2743 if ((STRING_BYTES_BOUND - extra) / 10 <= nskip)
2744 string_overflow ();
2745 digits++;
2746 nskip *= 10;
2747 nskip += c - '0';
2748 if (digits == 2 && nskip == 0)
2749 { /* We've just seen #@00, which means "skip to end". */
2750 skip_dyn_eof (readcharfun);
2751 return Qnil;
2754 if (nskip > 0)
2755 /* We can't use UNREAD here, because in the code below we side-step
2756 READCHAR. Instead, assume the first char after #@NNN occupies
2757 a single byte, which is the case normally since it's just
2758 a space. */
2759 nskip--;
2760 else
2761 UNREAD (c);
2763 if (load_force_doc_strings
2764 && (FROM_FILE_P (readcharfun)))
2766 /* If we are supposed to force doc strings into core right now,
2767 record the last string that we skipped,
2768 and record where in the file it comes from. */
2770 /* But first exchange saved_doc_string
2771 with prev_saved_doc_string, so we save two strings. */
2773 char *temp = saved_doc_string;
2774 ptrdiff_t temp_size = saved_doc_string_size;
2775 file_offset temp_pos = saved_doc_string_position;
2776 ptrdiff_t temp_len = saved_doc_string_length;
2778 saved_doc_string = prev_saved_doc_string;
2779 saved_doc_string_size = prev_saved_doc_string_size;
2780 saved_doc_string_position = prev_saved_doc_string_position;
2781 saved_doc_string_length = prev_saved_doc_string_length;
2783 prev_saved_doc_string = temp;
2784 prev_saved_doc_string_size = temp_size;
2785 prev_saved_doc_string_position = temp_pos;
2786 prev_saved_doc_string_length = temp_len;
2789 if (saved_doc_string_size == 0)
2791 saved_doc_string = xmalloc (nskip + extra);
2792 saved_doc_string_size = nskip + extra;
2794 if (nskip > saved_doc_string_size)
2796 saved_doc_string = xrealloc (saved_doc_string, nskip + extra);
2797 saved_doc_string_size = nskip + extra;
2800 saved_doc_string_position = file_tell (instream);
2802 /* Copy that many characters into saved_doc_string. */
2803 block_input ();
2804 for (i = 0; i < nskip && c >= 0; i++)
2805 saved_doc_string[i] = c = getc (instream);
2806 unblock_input ();
2808 saved_doc_string_length = i;
2810 else
2811 /* Skip that many bytes. */
2812 skip_dyn_bytes (readcharfun, nskip);
2814 goto retry;
2816 if (c == '!')
2818 /* #! appears at the beginning of an executable file.
2819 Skip the first line. */
2820 while (c != '\n' && c >= 0)
2821 c = READCHAR;
2822 goto retry;
2824 if (c == '$')
2825 return Vload_file_name;
2826 if (c == '\'')
2827 return list2 (Qfunction, read0 (readcharfun));
2828 /* #:foo is the uninterned symbol named foo. */
2829 if (c == ':')
2831 uninterned_symbol = 1;
2832 c = READCHAR;
2833 if (!(c > 040
2834 && c != 0xa0 /* NBSP */
2835 && (c >= 0200
2836 || strchr ("\"';()[]#`,", c) == NULL)))
2838 /* No symbol character follows, this is the empty
2839 symbol. */
2840 UNREAD (c);
2841 return Fmake_symbol (empty_unibyte_string);
2843 goto read_symbol;
2845 /* ## is the empty symbol. */
2846 if (c == '#')
2847 return Fintern (empty_unibyte_string, Qnil);
2848 /* Reader forms that can reuse previously read objects. */
2849 if (c >= '0' && c <= '9')
2851 EMACS_INT n = 0;
2852 Lisp_Object tem;
2854 /* Read a non-negative integer. */
2855 while (c >= '0' && c <= '9')
2857 if (MOST_POSITIVE_FIXNUM / 10 < n
2858 || MOST_POSITIVE_FIXNUM < n * 10 + c - '0')
2859 n = MOST_POSITIVE_FIXNUM + 1;
2860 else
2861 n = n * 10 + c - '0';
2862 c = READCHAR;
2865 if (n <= MOST_POSITIVE_FIXNUM)
2867 if (c == 'r' || c == 'R')
2868 return read_integer (readcharfun, n);
2870 if (! NILP (Vread_circle))
2872 /* #n=object returns object, but associates it with
2873 n for #n#. */
2874 if (c == '=')
2876 /* Make a placeholder for #n# to use temporarily. */
2877 AUTO_CONS (placeholder, Qnil, Qnil);
2878 Lisp_Object cell = Fcons (make_number (n), placeholder);
2879 read_objects = Fcons (cell, read_objects);
2881 /* Read the object itself. */
2882 tem = read0 (readcharfun);
2884 /* Now put it everywhere the placeholder was... */
2885 substitute_object_in_subtree (tem, placeholder);
2887 /* ...and #n# will use the real value from now on. */
2888 Fsetcdr (cell, tem);
2890 return tem;
2893 /* #n# returns a previously read object. */
2894 if (c == '#')
2896 tem = Fassq (make_number (n), read_objects);
2897 if (CONSP (tem))
2898 return XCDR (tem);
2902 /* Fall through to error message. */
2904 else if (c == 'x' || c == 'X')
2905 return read_integer (readcharfun, 16);
2906 else if (c == 'o' || c == 'O')
2907 return read_integer (readcharfun, 8);
2908 else if (c == 'b' || c == 'B')
2909 return read_integer (readcharfun, 2);
2911 UNREAD (c);
2912 invalid_syntax ("#");
2914 case ';':
2915 while ((c = READCHAR) >= 0 && c != '\n');
2916 goto retry;
2918 case '\'':
2919 return list2 (Qquote, read0 (readcharfun));
2921 case '`':
2923 int next_char = READCHAR;
2924 UNREAD (next_char);
2925 /* Transition from old-style to new-style:
2926 If we see "(`" it used to mean old-style, which usually works
2927 fine because ` should almost never appear in such a position
2928 for new-style. But occasionally we need "(`" to mean new
2929 style, so we try to distinguish the two by the fact that we
2930 can either write "( `foo" or "(` foo", where the first
2931 intends to use new-style whereas the second intends to use
2932 old-style. For Emacs-25, we should completely remove this
2933 first_in_list exception (old-style can still be obtained via
2934 "(\`" anyway). */
2935 if (!new_backquote_flag && first_in_list && next_char == ' ')
2937 Vold_style_backquotes = Qt;
2938 goto default_label;
2940 else
2942 Lisp_Object value;
2943 bool saved_new_backquote_flag = new_backquote_flag;
2945 new_backquote_flag = 1;
2946 value = read0 (readcharfun);
2947 new_backquote_flag = saved_new_backquote_flag;
2949 return list2 (Qbackquote, value);
2952 case ',':
2954 int next_char = READCHAR;
2955 UNREAD (next_char);
2956 /* Transition from old-style to new-style:
2957 It used to be impossible to have a new-style , other than within
2958 a new-style `. This is sufficient when ` and , are used in the
2959 normal way, but ` and , can also appear in args to macros that
2960 will not interpret them in the usual way, in which case , may be
2961 used without any ` anywhere near.
2962 So we now use the same heuristic as for backquote: old-style
2963 unquotes are only recognized when first on a list, and when
2964 followed by a space.
2965 Because it's more difficult to peek 2 chars ahead, a new-style
2966 ,@ can still not be used outside of a `, unless it's in the middle
2967 of a list. */
2968 if (new_backquote_flag
2969 || !first_in_list
2970 || (next_char != ' ' && next_char != '@'))
2972 Lisp_Object comma_type = Qnil;
2973 Lisp_Object value;
2974 int ch = READCHAR;
2976 if (ch == '@')
2977 comma_type = Qcomma_at;
2978 else if (ch == '.')
2979 comma_type = Qcomma_dot;
2980 else
2982 if (ch >= 0) UNREAD (ch);
2983 comma_type = Qcomma;
2986 value = read0 (readcharfun);
2987 return list2 (comma_type, value);
2989 else
2991 Vold_style_backquotes = Qt;
2992 goto default_label;
2995 case '?':
2997 int modifiers;
2998 int next_char;
2999 bool ok;
3001 c = READCHAR;
3002 if (c < 0)
3003 end_of_file_error ();
3005 /* Accept `single space' syntax like (list ? x) where the
3006 whitespace character is SPC or TAB.
3007 Other literal whitespace like NL, CR, and FF are not accepted,
3008 as there are well-established escape sequences for these. */
3009 if (c == ' ' || c == '\t')
3010 return make_number (c);
3012 if (c == '\\')
3013 c = read_escape (readcharfun, 0);
3014 modifiers = c & CHAR_MODIFIER_MASK;
3015 c &= ~CHAR_MODIFIER_MASK;
3016 if (CHAR_BYTE8_P (c))
3017 c = CHAR_TO_BYTE8 (c);
3018 c |= modifiers;
3020 next_char = READCHAR;
3021 ok = (next_char <= 040
3022 || (next_char < 0200
3023 && strchr ("\"';()[]#?`,.", next_char) != NULL));
3024 UNREAD (next_char);
3025 if (ok)
3026 return make_number (c);
3028 invalid_syntax ("?");
3031 case '"':
3033 char *p = read_buffer;
3034 char *end = read_buffer + read_buffer_size;
3035 int ch;
3036 /* True if we saw an escape sequence specifying
3037 a multibyte character. */
3038 bool force_multibyte = 0;
3039 /* True if we saw an escape sequence specifying
3040 a single-byte character. */
3041 bool force_singlebyte = 0;
3042 bool cancel = 0;
3043 ptrdiff_t nchars = 0;
3045 while ((ch = READCHAR) >= 0
3046 && ch != '\"')
3048 if (end - p < MAX_MULTIBYTE_LENGTH)
3050 ptrdiff_t offset = p - read_buffer;
3051 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3052 memory_full (SIZE_MAX);
3053 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
3054 read_buffer_size *= 2;
3055 p = read_buffer + offset;
3056 end = read_buffer + read_buffer_size;
3059 if (ch == '\\')
3061 int modifiers;
3063 ch = read_escape (readcharfun, 1);
3065 /* CH is -1 if \ newline has just been seen. */
3066 if (ch == -1)
3068 if (p == read_buffer)
3069 cancel = 1;
3070 continue;
3073 modifiers = ch & CHAR_MODIFIER_MASK;
3074 ch = ch & ~CHAR_MODIFIER_MASK;
3076 if (CHAR_BYTE8_P (ch))
3077 force_singlebyte = 1;
3078 else if (! ASCII_CHAR_P (ch))
3079 force_multibyte = 1;
3080 else /* I.e. ASCII_CHAR_P (ch). */
3082 /* Allow `\C- ' and `\C-?'. */
3083 if (modifiers == CHAR_CTL)
3085 if (ch == ' ')
3086 ch = 0, modifiers = 0;
3087 else if (ch == '?')
3088 ch = 127, modifiers = 0;
3090 if (modifiers & CHAR_SHIFT)
3092 /* Shift modifier is valid only with [A-Za-z]. */
3093 if (ch >= 'A' && ch <= 'Z')
3094 modifiers &= ~CHAR_SHIFT;
3095 else if (ch >= 'a' && ch <= 'z')
3096 ch -= ('a' - 'A'), modifiers &= ~CHAR_SHIFT;
3099 if (modifiers & CHAR_META)
3101 /* Move the meta bit to the right place for a
3102 string. */
3103 modifiers &= ~CHAR_META;
3104 ch = BYTE8_TO_CHAR (ch | 0x80);
3105 force_singlebyte = 1;
3109 /* Any modifiers remaining are invalid. */
3110 if (modifiers)
3111 error ("Invalid modifier in string");
3112 p += CHAR_STRING (ch, (unsigned char *) p);
3114 else
3116 p += CHAR_STRING (ch, (unsigned char *) p);
3117 if (CHAR_BYTE8_P (ch))
3118 force_singlebyte = 1;
3119 else if (! ASCII_CHAR_P (ch))
3120 force_multibyte = 1;
3122 nchars++;
3125 if (ch < 0)
3126 end_of_file_error ();
3128 /* If purifying, and string starts with \ newline,
3129 return zero instead. This is for doc strings
3130 that we are really going to find in etc/DOC.nn.nn. */
3131 if (!NILP (Vpurify_flag) && NILP (Vdoc_file_name) && cancel)
3132 return make_number (0);
3134 if (! force_multibyte && force_singlebyte)
3136 /* READ_BUFFER contains raw 8-bit bytes and no multibyte
3137 forms. Convert it to unibyte. */
3138 nchars = str_as_unibyte ((unsigned char *) read_buffer,
3139 p - read_buffer);
3140 p = read_buffer + nchars;
3143 return make_specified_string (read_buffer, nchars, p - read_buffer,
3144 (force_multibyte
3145 || (p - read_buffer != nchars)));
3148 case '.':
3150 int next_char = READCHAR;
3151 UNREAD (next_char);
3153 if (next_char <= 040
3154 || (next_char < 0200
3155 && strchr ("\"';([#?`,", next_char) != NULL))
3157 *pch = c;
3158 return Qnil;
3161 /* Otherwise, we fall through! Note that the atom-reading loop
3162 below will now loop at least once, assuring that we will not
3163 try to UNREAD two characters in a row. */
3165 default:
3166 default_label:
3167 if (c <= 040) goto retry;
3168 if (c == 0xa0) /* NBSP */
3169 goto retry;
3171 read_symbol:
3173 char *p = read_buffer;
3174 bool quoted = 0;
3175 EMACS_INT start_position = readchar_count - 1;
3178 char *end = read_buffer + read_buffer_size;
3182 if (end - p < MAX_MULTIBYTE_LENGTH)
3184 ptrdiff_t offset = p - read_buffer;
3185 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3186 memory_full (SIZE_MAX);
3187 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
3188 read_buffer_size *= 2;
3189 p = read_buffer + offset;
3190 end = read_buffer + read_buffer_size;
3193 if (c == '\\')
3195 c = READCHAR;
3196 if (c == -1)
3197 end_of_file_error ();
3198 quoted = 1;
3201 if (multibyte)
3202 p += CHAR_STRING (c, (unsigned char *) p);
3203 else
3204 *p++ = c;
3205 c = READCHAR;
3207 while (c > 040
3208 && c != 0xa0 /* NBSP */
3209 && (c >= 0200
3210 || strchr ("\"';()[]#`,", c) == NULL));
3212 if (p == end)
3214 ptrdiff_t offset = p - read_buffer;
3215 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3216 memory_full (SIZE_MAX);
3217 read_buffer = xrealloc (read_buffer, read_buffer_size * 2);
3218 read_buffer_size *= 2;
3219 p = read_buffer + offset;
3220 end = read_buffer + read_buffer_size;
3222 *p = 0;
3223 UNREAD (c);
3226 if (!quoted && !uninterned_symbol)
3228 Lisp_Object result = string_to_number (read_buffer, 10, 0);
3229 if (! NILP (result))
3230 return result;
3233 Lisp_Object name, result;
3234 ptrdiff_t nbytes = p - read_buffer;
3235 ptrdiff_t nchars
3236 = (multibyte
3237 ? multibyte_chars_in_text ((unsigned char *) read_buffer,
3238 nbytes)
3239 : nbytes);
3241 name = ((uninterned_symbol && ! NILP (Vpurify_flag)
3242 ? make_pure_string : make_specified_string)
3243 (read_buffer, nchars, nbytes, multibyte));
3244 result = (uninterned_symbol ? Fmake_symbol (name)
3245 : Fintern (name, Qnil));
3247 if (EQ (Vread_with_symbol_positions, Qt)
3248 || EQ (Vread_with_symbol_positions, readcharfun))
3249 Vread_symbol_positions_list
3250 = Fcons (Fcons (result, make_number (start_position)),
3251 Vread_symbol_positions_list);
3252 return result;
3259 /* List of nodes we've seen during substitute_object_in_subtree. */
3260 static Lisp_Object seen_list;
3262 static void
3263 substitute_object_in_subtree (Lisp_Object object, Lisp_Object placeholder)
3265 Lisp_Object check_object;
3267 /* We haven't seen any objects when we start. */
3268 seen_list = Qnil;
3270 /* Make all the substitutions. */
3271 check_object
3272 = substitute_object_recurse (object, placeholder, object);
3274 /* Clear seen_list because we're done with it. */
3275 seen_list = Qnil;
3277 /* The returned object here is expected to always eq the
3278 original. */
3279 if (!EQ (check_object, object))
3280 error ("Unexpected mutation error in reader");
3283 /* Feval doesn't get called from here, so no gc protection is needed. */
3284 #define SUBSTITUTE(get_val, set_val) \
3285 do { \
3286 Lisp_Object old_value = get_val; \
3287 Lisp_Object true_value \
3288 = substitute_object_recurse (object, placeholder, \
3289 old_value); \
3291 if (!EQ (old_value, true_value)) \
3293 set_val; \
3295 } while (0)
3297 static Lisp_Object
3298 substitute_object_recurse (Lisp_Object object, Lisp_Object placeholder, Lisp_Object subtree)
3300 /* If we find the placeholder, return the target object. */
3301 if (EQ (placeholder, subtree))
3302 return object;
3304 /* If we've been to this node before, don't explore it again. */
3305 if (!EQ (Qnil, Fmemq (subtree, seen_list)))
3306 return subtree;
3308 /* If this node can be the entry point to a cycle, remember that
3309 we've seen it. It can only be such an entry point if it was made
3310 by #n=, which means that we can find it as a value in
3311 read_objects. */
3312 if (!EQ (Qnil, Frassq (subtree, read_objects)))
3313 seen_list = Fcons (subtree, seen_list);
3315 /* Recurse according to subtree's type.
3316 Every branch must return a Lisp_Object. */
3317 switch (XTYPE (subtree))
3319 case Lisp_Vectorlike:
3321 ptrdiff_t i, length = 0;
3322 if (BOOL_VECTOR_P (subtree))
3323 return subtree; /* No sub-objects anyway. */
3324 else if (CHAR_TABLE_P (subtree) || SUB_CHAR_TABLE_P (subtree)
3325 || COMPILEDP (subtree) || HASH_TABLE_P (subtree))
3326 length = ASIZE (subtree) & PSEUDOVECTOR_SIZE_MASK;
3327 else if (VECTORP (subtree))
3328 length = ASIZE (subtree);
3329 else
3330 /* An unknown pseudovector may contain non-Lisp fields, so we
3331 can't just blindly traverse all its fields. We used to call
3332 `Flength' which signaled `sequencep', so I just preserved this
3333 behavior. */
3334 wrong_type_argument (Qsequencep, subtree);
3336 for (i = 0; i < length; i++)
3337 SUBSTITUTE (AREF (subtree, i),
3338 ASET (subtree, i, true_value));
3339 return subtree;
3342 case Lisp_Cons:
3344 SUBSTITUTE (XCAR (subtree),
3345 XSETCAR (subtree, true_value));
3346 SUBSTITUTE (XCDR (subtree),
3347 XSETCDR (subtree, true_value));
3348 return subtree;
3351 case Lisp_String:
3353 /* Check for text properties in each interval.
3354 substitute_in_interval contains part of the logic. */
3356 INTERVAL root_interval = string_intervals (subtree);
3357 AUTO_CONS (arg, object, placeholder);
3359 traverse_intervals_noorder (root_interval,
3360 &substitute_in_interval, arg);
3362 return subtree;
3365 /* Other types don't recurse any further. */
3366 default:
3367 return subtree;
3371 /* Helper function for substitute_object_recurse. */
3372 static void
3373 substitute_in_interval (INTERVAL interval, Lisp_Object arg)
3375 Lisp_Object object = Fcar (arg);
3376 Lisp_Object placeholder = Fcdr (arg);
3378 SUBSTITUTE (interval->plist, set_interval_plist (interval, true_value));
3382 #define LEAD_INT 1
3383 #define DOT_CHAR 2
3384 #define TRAIL_INT 4
3385 #define E_EXP 16
3388 /* Convert STRING to a number, assuming base BASE. Return a fixnum if CP has
3389 integer syntax and fits in a fixnum, else return the nearest float if CP has
3390 either floating point or integer syntax and BASE is 10, else return nil. If
3391 IGNORE_TRAILING, consider just the longest prefix of CP that has
3392 valid floating point syntax. Signal an overflow if BASE is not 10 and the
3393 number has integer syntax but does not fit. */
3395 Lisp_Object
3396 string_to_number (char const *string, int base, bool ignore_trailing)
3398 int state;
3399 char const *cp = string;
3400 int leading_digit;
3401 bool float_syntax = 0;
3402 double value = 0;
3404 /* Compute NaN and infinities using a variable, to cope with compilers that
3405 think they are smarter than we are. */
3406 double zero = 0;
3408 /* Negate the value ourselves. This treats 0, NaNs, and infinity properly on
3409 IEEE floating point hosts, and works around a formerly-common bug where
3410 atof ("-0.0") drops the sign. */
3411 bool negative = *cp == '-';
3413 bool signedp = negative || *cp == '+';
3414 cp += signedp;
3416 state = 0;
3418 leading_digit = digit_to_number (*cp, base);
3419 if (leading_digit >= 0)
3421 state |= LEAD_INT;
3423 ++cp;
3424 while (digit_to_number (*cp, base) >= 0);
3426 if (*cp == '.')
3428 state |= DOT_CHAR;
3429 cp++;
3432 if (base == 10)
3434 if ('0' <= *cp && *cp <= '9')
3436 state |= TRAIL_INT;
3438 cp++;
3439 while ('0' <= *cp && *cp <= '9');
3441 if (*cp == 'e' || *cp == 'E')
3443 char const *ecp = cp;
3444 cp++;
3445 if (*cp == '+' || *cp == '-')
3446 cp++;
3447 if ('0' <= *cp && *cp <= '9')
3449 state |= E_EXP;
3451 cp++;
3452 while ('0' <= *cp && *cp <= '9');
3454 else if (cp[-1] == '+'
3455 && cp[0] == 'I' && cp[1] == 'N' && cp[2] == 'F')
3457 state |= E_EXP;
3458 cp += 3;
3459 value = 1.0 / zero;
3461 else if (cp[-1] == '+'
3462 && cp[0] == 'N' && cp[1] == 'a' && cp[2] == 'N')
3464 state |= E_EXP;
3465 cp += 3;
3466 value = zero / zero;
3468 /* If that made a "negative" NaN, negate it. */
3470 int i;
3471 union { double d; char c[sizeof (double)]; }
3472 u_data, u_minus_zero;
3473 u_data.d = value;
3474 u_minus_zero.d = -0.0;
3475 for (i = 0; i < sizeof (double); i++)
3476 if (u_data.c[i] & u_minus_zero.c[i])
3478 value = -value;
3479 break;
3482 /* Now VALUE is a positive NaN. */
3484 else
3485 cp = ecp;
3488 float_syntax = ((state & (DOT_CHAR|TRAIL_INT)) == (DOT_CHAR|TRAIL_INT)
3489 || state == (LEAD_INT|E_EXP));
3492 /* Return nil if the number uses invalid syntax. If IGNORE_TRAILING, accept
3493 any prefix that matches. Otherwise, the entire string must match. */
3494 if (! (ignore_trailing
3495 ? ((state & LEAD_INT) != 0 || float_syntax)
3496 : (!*cp && ((state & ~DOT_CHAR) == LEAD_INT || float_syntax))))
3497 return Qnil;
3499 /* If the number uses integer and not float syntax, and is in C-language
3500 range, use its value, preferably as a fixnum. */
3501 if (leading_digit >= 0 && ! float_syntax)
3503 uintmax_t n;
3505 /* Fast special case for single-digit integers. This also avoids a
3506 glitch when BASE is 16 and IGNORE_TRAILING, because in that
3507 case some versions of strtoumax accept numbers like "0x1" that Emacs
3508 does not allow. */
3509 if (digit_to_number (string[signedp + 1], base) < 0)
3510 return make_number (negative ? -leading_digit : leading_digit);
3512 errno = 0;
3513 n = strtoumax (string + signedp, NULL, base);
3514 if (errno == ERANGE)
3516 /* Unfortunately there's no simple and accurate way to convert
3517 non-base-10 numbers that are out of C-language range. */
3518 if (base != 10)
3519 xsignal1 (Qoverflow_error, build_string (string));
3521 else if (n <= (negative ? -MOST_NEGATIVE_FIXNUM : MOST_POSITIVE_FIXNUM))
3523 EMACS_INT signed_n = n;
3524 return make_number (negative ? -signed_n : signed_n);
3526 else
3527 value = n;
3530 /* Either the number uses float syntax, or it does not fit into a fixnum.
3531 Convert it from string to floating point, unless the value is already
3532 known because it is an infinity, a NAN, or its absolute value fits in
3533 uintmax_t. */
3534 if (! value)
3535 value = atof (string + signedp);
3537 return make_float (negative ? -value : value);
3541 static Lisp_Object
3542 read_vector (Lisp_Object readcharfun, bool bytecodeflag)
3544 ptrdiff_t i, size;
3545 Lisp_Object *ptr;
3546 Lisp_Object tem, item, vector;
3547 struct Lisp_Cons *otem;
3548 Lisp_Object len;
3550 tem = read_list (1, readcharfun);
3551 len = Flength (tem);
3552 vector = Fmake_vector (len, Qnil);
3554 size = ASIZE (vector);
3555 ptr = XVECTOR (vector)->contents;
3556 for (i = 0; i < size; i++)
3558 item = Fcar (tem);
3559 /* If `load-force-doc-strings' is t when reading a lazily-loaded
3560 bytecode object, the docstring containing the bytecode and
3561 constants values must be treated as unibyte and passed to
3562 Fread, to get the actual bytecode string and constants vector. */
3563 if (bytecodeflag && load_force_doc_strings)
3565 if (i == COMPILED_BYTECODE)
3567 if (!STRINGP (item))
3568 error ("Invalid byte code");
3570 /* Delay handling the bytecode slot until we know whether
3571 it is lazily-loaded (we can tell by whether the
3572 constants slot is nil). */
3573 ASET (vector, COMPILED_CONSTANTS, item);
3574 item = Qnil;
3576 else if (i == COMPILED_CONSTANTS)
3578 Lisp_Object bytestr = ptr[COMPILED_CONSTANTS];
3580 if (NILP (item))
3582 /* Coerce string to unibyte (like string-as-unibyte,
3583 but without generating extra garbage and
3584 guaranteeing no change in the contents). */
3585 STRING_SET_CHARS (bytestr, SBYTES (bytestr));
3586 STRING_SET_UNIBYTE (bytestr);
3588 item = Fread (Fcons (bytestr, readcharfun));
3589 if (!CONSP (item))
3590 error ("Invalid byte code");
3592 otem = XCONS (item);
3593 bytestr = XCAR (item);
3594 item = XCDR (item);
3595 free_cons (otem);
3598 /* Now handle the bytecode slot. */
3599 ASET (vector, COMPILED_BYTECODE, bytestr);
3601 else if (i == COMPILED_DOC_STRING
3602 && STRINGP (item)
3603 && ! STRING_MULTIBYTE (item))
3605 if (EQ (readcharfun, Qget_emacs_mule_file_char))
3606 item = Fdecode_coding_string (item, Qemacs_mule, Qnil, Qnil);
3607 else
3608 item = Fstring_as_multibyte (item);
3611 ASET (vector, i, item);
3612 otem = XCONS (tem);
3613 tem = Fcdr (tem);
3614 free_cons (otem);
3616 return vector;
3619 /* FLAG means check for ']' to terminate rather than ')' and '.'. */
3621 static Lisp_Object
3622 read_list (bool flag, Lisp_Object readcharfun)
3624 Lisp_Object val, tail;
3625 Lisp_Object elt, tem;
3626 struct gcpro gcpro1, gcpro2;
3627 /* 0 is the normal case.
3628 1 means this list is a doc reference; replace it with the number 0.
3629 2 means this list is a doc reference; replace it with the doc string. */
3630 int doc_reference = 0;
3632 /* Initialize this to 1 if we are reading a list. */
3633 bool first_in_list = flag <= 0;
3635 val = Qnil;
3636 tail = Qnil;
3638 while (1)
3640 int ch;
3641 GCPRO2 (val, tail);
3642 elt = read1 (readcharfun, &ch, first_in_list);
3643 UNGCPRO;
3645 first_in_list = 0;
3647 /* While building, if the list starts with #$, treat it specially. */
3648 if (EQ (elt, Vload_file_name)
3649 && ! NILP (elt)
3650 && !NILP (Vpurify_flag))
3652 if (NILP (Vdoc_file_name))
3653 /* We have not yet called Snarf-documentation, so assume
3654 this file is described in the DOC file
3655 and Snarf-documentation will fill in the right value later.
3656 For now, replace the whole list with 0. */
3657 doc_reference = 1;
3658 else
3659 /* We have already called Snarf-documentation, so make a relative
3660 file name for this file, so it can be found properly
3661 in the installed Lisp directory.
3662 We don't use Fexpand_file_name because that would make
3663 the directory absolute now. */
3665 AUTO_STRING (dot_dot_lisp, "../lisp/");
3666 elt = concat2 (dot_dot_lisp, Ffile_name_nondirectory (elt));
3669 else if (EQ (elt, Vload_file_name)
3670 && ! NILP (elt)
3671 && load_force_doc_strings)
3672 doc_reference = 2;
3674 if (ch)
3676 if (flag > 0)
3678 if (ch == ']')
3679 return val;
3680 invalid_syntax (") or . in a vector");
3682 if (ch == ')')
3683 return val;
3684 if (ch == '.')
3686 GCPRO2 (val, tail);
3687 if (!NILP (tail))
3688 XSETCDR (tail, read0 (readcharfun));
3689 else
3690 val = read0 (readcharfun);
3691 read1 (readcharfun, &ch, 0);
3692 UNGCPRO;
3693 if (ch == ')')
3695 if (doc_reference == 1)
3696 return make_number (0);
3697 if (doc_reference == 2 && INTEGERP (XCDR (val)))
3699 char *saved = NULL;
3700 file_offset saved_position;
3701 /* Get a doc string from the file we are loading.
3702 If it's in saved_doc_string, get it from there.
3704 Here, we don't know if the string is a
3705 bytecode string or a doc string. As a
3706 bytecode string must be unibyte, we always
3707 return a unibyte string. If it is actually a
3708 doc string, caller must make it
3709 multibyte. */
3711 /* Position is negative for user variables. */
3712 EMACS_INT pos = eabs (XINT (XCDR (val)));
3713 if (pos >= saved_doc_string_position
3714 && pos < (saved_doc_string_position
3715 + saved_doc_string_length))
3717 saved = saved_doc_string;
3718 saved_position = saved_doc_string_position;
3720 /* Look in prev_saved_doc_string the same way. */
3721 else if (pos >= prev_saved_doc_string_position
3722 && pos < (prev_saved_doc_string_position
3723 + prev_saved_doc_string_length))
3725 saved = prev_saved_doc_string;
3726 saved_position = prev_saved_doc_string_position;
3728 if (saved)
3730 ptrdiff_t start = pos - saved_position;
3731 ptrdiff_t from, to;
3733 /* Process quoting with ^A,
3734 and find the end of the string,
3735 which is marked with ^_ (037). */
3736 for (from = start, to = start;
3737 saved[from] != 037;)
3739 int c = saved[from++];
3740 if (c == 1)
3742 c = saved[from++];
3743 saved[to++] = (c == 1 ? c
3744 : c == '0' ? 0
3745 : c == '_' ? 037
3746 : c);
3748 else
3749 saved[to++] = c;
3752 return make_unibyte_string (saved + start,
3753 to - start);
3755 else
3756 return get_doc_string (val, 1, 0);
3759 return val;
3761 invalid_syntax (". in wrong context");
3763 invalid_syntax ("] in a list");
3765 tem = list1 (elt);
3766 if (!NILP (tail))
3767 XSETCDR (tail, tem);
3768 else
3769 val = tem;
3770 tail = tem;
3774 static Lisp_Object initial_obarray;
3776 /* `oblookup' stores the bucket number here, for the sake of Funintern. */
3778 static size_t oblookup_last_bucket_number;
3780 /* Get an error if OBARRAY is not an obarray.
3781 If it is one, return it. */
3783 Lisp_Object
3784 check_obarray (Lisp_Object obarray)
3786 if (!VECTORP (obarray) || ASIZE (obarray) == 0)
3788 /* If Vobarray is now invalid, force it to be valid. */
3789 if (EQ (Vobarray, obarray)) Vobarray = initial_obarray;
3790 wrong_type_argument (Qvectorp, obarray);
3792 return obarray;
3795 /* Intern a symbol with name STRING in OBARRAY using bucket INDEX. */
3797 Lisp_Object
3798 intern_driver (Lisp_Object string, Lisp_Object obarray, ptrdiff_t index)
3800 Lisp_Object *ptr, sym = Fmake_symbol (string);
3802 XSYMBOL (sym)->interned = (EQ (obarray, initial_obarray)
3803 ? SYMBOL_INTERNED_IN_INITIAL_OBARRAY
3804 : SYMBOL_INTERNED);
3806 if ((SREF (string, 0) == ':') && EQ (obarray, initial_obarray))
3808 XSYMBOL (sym)->constant = 1;
3809 XSYMBOL (sym)->redirect = SYMBOL_PLAINVAL;
3810 SET_SYMBOL_VAL (XSYMBOL (sym), sym);
3813 ptr = aref_addr (obarray, index);
3814 set_symbol_next (sym, SYMBOLP (*ptr) ? XSYMBOL (*ptr) : NULL);
3815 *ptr = sym;
3816 return sym;
3819 /* Intern the C string STR: return a symbol with that name,
3820 interned in the current obarray. */
3822 Lisp_Object
3823 intern_1 (const char *str, ptrdiff_t len)
3825 Lisp_Object obarray = check_obarray (Vobarray);
3826 Lisp_Object tem = oblookup (obarray, str, len, len);
3828 return SYMBOLP (tem) ? tem : intern_driver (make_string (str, len),
3829 obarray, XINT (tem));
3832 Lisp_Object
3833 intern_c_string_1 (const char *str, ptrdiff_t len)
3835 Lisp_Object obarray = check_obarray (Vobarray);
3836 Lisp_Object tem = oblookup (obarray, str, len, len);
3838 if (!SYMBOLP (tem))
3840 /* Creating a non-pure string from a string literal not implemented yet.
3841 We could just use make_string here and live with the extra copy. */
3842 eassert (!NILP (Vpurify_flag));
3843 tem = intern_driver (make_pure_c_string (str, len), obarray, XINT (tem));
3845 return tem;
3848 DEFUN ("intern", Fintern, Sintern, 1, 2, 0,
3849 doc: /* Return the canonical symbol whose name is STRING.
3850 If there is none, one is created by this function and returned.
3851 A second optional argument specifies the obarray to use;
3852 it defaults to the value of `obarray'. */)
3853 (Lisp_Object string, Lisp_Object obarray)
3855 Lisp_Object tem;
3857 obarray = check_obarray (NILP (obarray) ? Vobarray : obarray);
3858 CHECK_STRING (string);
3860 tem = oblookup (obarray, SSDATA (string), SCHARS (string), SBYTES (string));
3861 if (!SYMBOLP (tem))
3862 tem = intern_driver (NILP (Vpurify_flag) ? string
3863 : Fpurecopy (string), obarray, XINT (tem));
3864 return tem;
3867 DEFUN ("intern-soft", Fintern_soft, Sintern_soft, 1, 2, 0,
3868 doc: /* Return the canonical symbol named NAME, or nil if none exists.
3869 NAME may be a string or a symbol. If it is a symbol, that exact
3870 symbol is searched for.
3871 A second optional argument specifies the obarray to use;
3872 it defaults to the value of `obarray'. */)
3873 (Lisp_Object name, Lisp_Object obarray)
3875 register Lisp_Object tem, string;
3877 if (NILP (obarray)) obarray = Vobarray;
3878 obarray = check_obarray (obarray);
3880 if (!SYMBOLP (name))
3882 CHECK_STRING (name);
3883 string = name;
3885 else
3886 string = SYMBOL_NAME (name);
3888 tem = oblookup (obarray, SSDATA (string), SCHARS (string), SBYTES (string));
3889 if (INTEGERP (tem) || (SYMBOLP (name) && !EQ (name, tem)))
3890 return Qnil;
3891 else
3892 return tem;
3895 DEFUN ("unintern", Funintern, Sunintern, 1, 2, 0,
3896 doc: /* Delete the symbol named NAME, if any, from OBARRAY.
3897 The value is t if a symbol was found and deleted, nil otherwise.
3898 NAME may be a string or a symbol. If it is a symbol, that symbol
3899 is deleted, if it belongs to OBARRAY--no other symbol is deleted.
3900 OBARRAY, if nil, defaults to the value of the variable `obarray'.
3901 usage: (unintern NAME OBARRAY) */)
3902 (Lisp_Object name, Lisp_Object obarray)
3904 register Lisp_Object string, tem;
3905 size_t hash;
3907 if (NILP (obarray)) obarray = Vobarray;
3908 obarray = check_obarray (obarray);
3910 if (SYMBOLP (name))
3911 string = SYMBOL_NAME (name);
3912 else
3914 CHECK_STRING (name);
3915 string = name;
3918 tem = oblookup (obarray, SSDATA (string),
3919 SCHARS (string),
3920 SBYTES (string));
3921 if (INTEGERP (tem))
3922 return Qnil;
3923 /* If arg was a symbol, don't delete anything but that symbol itself. */
3924 if (SYMBOLP (name) && !EQ (name, tem))
3925 return Qnil;
3927 /* There are plenty of other symbols which will screw up the Emacs
3928 session if we unintern them, as well as even more ways to use
3929 `setq' or `fset' or whatnot to make the Emacs session
3930 unusable. Let's not go down this silly road. --Stef */
3931 /* if (EQ (tem, Qnil) || EQ (tem, Qt))
3932 error ("Attempt to unintern t or nil"); */
3934 XSYMBOL (tem)->interned = SYMBOL_UNINTERNED;
3936 hash = oblookup_last_bucket_number;
3938 if (EQ (AREF (obarray, hash), tem))
3940 if (XSYMBOL (tem)->next)
3942 Lisp_Object sym;
3943 XSETSYMBOL (sym, XSYMBOL (tem)->next);
3944 ASET (obarray, hash, sym);
3946 else
3947 ASET (obarray, hash, make_number (0));
3949 else
3951 Lisp_Object tail, following;
3953 for (tail = AREF (obarray, hash);
3954 XSYMBOL (tail)->next;
3955 tail = following)
3957 XSETSYMBOL (following, XSYMBOL (tail)->next);
3958 if (EQ (following, tem))
3960 set_symbol_next (tail, XSYMBOL (following)->next);
3961 break;
3966 return Qt;
3969 /* Return the symbol in OBARRAY whose names matches the string
3970 of SIZE characters (SIZE_BYTE bytes) at PTR.
3971 If there is no such symbol, return the integer bucket number of
3972 where the symbol would be if it were present.
3974 Also store the bucket number in oblookup_last_bucket_number. */
3976 Lisp_Object
3977 oblookup (Lisp_Object obarray, register const char *ptr, ptrdiff_t size, ptrdiff_t size_byte)
3979 size_t hash;
3980 size_t obsize;
3981 register Lisp_Object tail;
3982 Lisp_Object bucket, tem;
3984 obarray = check_obarray (obarray);
3985 obsize = ASIZE (obarray);
3987 /* This is sometimes needed in the middle of GC. */
3988 obsize &= ~ARRAY_MARK_FLAG;
3989 hash = hash_string (ptr, size_byte) % obsize;
3990 bucket = AREF (obarray, hash);
3991 oblookup_last_bucket_number = hash;
3992 if (EQ (bucket, make_number (0)))
3994 else if (!SYMBOLP (bucket))
3995 error ("Bad data in guts of obarray"); /* Like CADR error message. */
3996 else
3997 for (tail = bucket; ; XSETSYMBOL (tail, XSYMBOL (tail)->next))
3999 if (SBYTES (SYMBOL_NAME (tail)) == size_byte
4000 && SCHARS (SYMBOL_NAME (tail)) == size
4001 && !memcmp (SDATA (SYMBOL_NAME (tail)), ptr, size_byte))
4002 return tail;
4003 else if (XSYMBOL (tail)->next == 0)
4004 break;
4006 XSETINT (tem, hash);
4007 return tem;
4010 void
4011 map_obarray (Lisp_Object obarray, void (*fn) (Lisp_Object, Lisp_Object), Lisp_Object arg)
4013 ptrdiff_t i;
4014 register Lisp_Object tail;
4015 CHECK_VECTOR (obarray);
4016 for (i = ASIZE (obarray) - 1; i >= 0; i--)
4018 tail = AREF (obarray, i);
4019 if (SYMBOLP (tail))
4020 while (1)
4022 (*fn) (tail, arg);
4023 if (XSYMBOL (tail)->next == 0)
4024 break;
4025 XSETSYMBOL (tail, XSYMBOL (tail)->next);
4030 static void
4031 mapatoms_1 (Lisp_Object sym, Lisp_Object function)
4033 call1 (function, sym);
4036 DEFUN ("mapatoms", Fmapatoms, Smapatoms, 1, 2, 0,
4037 doc: /* Call FUNCTION on every symbol in OBARRAY.
4038 OBARRAY defaults to the value of `obarray'. */)
4039 (Lisp_Object function, Lisp_Object obarray)
4041 if (NILP (obarray)) obarray = Vobarray;
4042 obarray = check_obarray (obarray);
4044 map_obarray (obarray, mapatoms_1, function);
4045 return Qnil;
4048 #define OBARRAY_SIZE 1511
4050 void
4051 init_obarray (void)
4053 Lisp_Object oblength;
4054 ptrdiff_t size = 100 + MAX_MULTIBYTE_LENGTH;
4056 XSETFASTINT (oblength, OBARRAY_SIZE);
4058 Vobarray = Fmake_vector (oblength, make_number (0));
4059 initial_obarray = Vobarray;
4060 staticpro (&initial_obarray);
4062 Qunbound = Fmake_symbol (build_pure_c_string ("unbound"));
4063 /* Set temporary dummy values to Qnil and Vpurify_flag to satisfy the
4064 NILP (Vpurify_flag) check in intern_c_string. */
4065 Qnil = make_number (-1); Vpurify_flag = make_number (1);
4066 Qnil = intern_c_string ("nil");
4068 /* Fmake_symbol inits fields of new symbols with Qunbound and Qnil,
4069 so those two need to be fixed manually. */
4070 SET_SYMBOL_VAL (XSYMBOL (Qunbound), Qunbound);
4071 set_symbol_function (Qunbound, Qnil);
4072 set_symbol_plist (Qunbound, Qnil);
4073 SET_SYMBOL_VAL (XSYMBOL (Qnil), Qnil);
4074 XSYMBOL (Qnil)->constant = 1;
4075 XSYMBOL (Qnil)->declared_special = 1;
4076 set_symbol_plist (Qnil, Qnil);
4077 set_symbol_function (Qnil, Qnil);
4079 Qt = intern_c_string ("t");
4080 SET_SYMBOL_VAL (XSYMBOL (Qt), Qt);
4081 XSYMBOL (Qnil)->declared_special = 1;
4082 XSYMBOL (Qt)->constant = 1;
4084 /* Qt is correct even if CANNOT_DUMP. loadup.el will set to nil at end. */
4085 Vpurify_flag = Qt;
4087 DEFSYM (Qvariable_documentation, "variable-documentation");
4089 read_buffer = xmalloc (size);
4090 read_buffer_size = size;
4093 void
4094 defsubr (struct Lisp_Subr *sname)
4096 Lisp_Object sym, tem;
4097 sym = intern_c_string (sname->symbol_name);
4098 XSETPVECTYPE (sname, PVEC_SUBR);
4099 XSETSUBR (tem, sname);
4100 set_symbol_function (sym, tem);
4103 #ifdef NOTDEF /* Use fset in subr.el now! */
4104 void
4105 defalias (struct Lisp_Subr *sname, char *string)
4107 Lisp_Object sym;
4108 sym = intern (string);
4109 XSETSUBR (XSYMBOL (sym)->function, sname);
4111 #endif /* NOTDEF */
4113 /* Define an "integer variable"; a symbol whose value is forwarded to a
4114 C variable of type EMACS_INT. Sample call (with "xx" to fool make-docfile):
4115 DEFxxVAR_INT ("emacs-priority", &emacs_priority, "Documentation"); */
4116 void
4117 defvar_int (struct Lisp_Intfwd *i_fwd,
4118 const char *namestring, EMACS_INT *address)
4120 Lisp_Object sym;
4121 sym = intern_c_string (namestring);
4122 i_fwd->type = Lisp_Fwd_Int;
4123 i_fwd->intvar = address;
4124 XSYMBOL (sym)->declared_special = 1;
4125 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4126 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)i_fwd);
4129 /* Similar but define a variable whose value is t if address contains 1,
4130 nil if address contains 0. */
4131 void
4132 defvar_bool (struct Lisp_Boolfwd *b_fwd,
4133 const char *namestring, bool *address)
4135 Lisp_Object sym;
4136 sym = intern_c_string (namestring);
4137 b_fwd->type = Lisp_Fwd_Bool;
4138 b_fwd->boolvar = address;
4139 XSYMBOL (sym)->declared_special = 1;
4140 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4141 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)b_fwd);
4142 Vbyte_boolean_vars = Fcons (sym, Vbyte_boolean_vars);
4145 /* Similar but define a variable whose value is the Lisp Object stored
4146 at address. Two versions: with and without gc-marking of the C
4147 variable. The nopro version is used when that variable will be
4148 gc-marked for some other reason, since marking the same slot twice
4149 can cause trouble with strings. */
4150 void
4151 defvar_lisp_nopro (struct Lisp_Objfwd *o_fwd,
4152 const char *namestring, Lisp_Object *address)
4154 Lisp_Object sym;
4155 sym = intern_c_string (namestring);
4156 o_fwd->type = Lisp_Fwd_Obj;
4157 o_fwd->objvar = address;
4158 XSYMBOL (sym)->declared_special = 1;
4159 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4160 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)o_fwd);
4163 void
4164 defvar_lisp (struct Lisp_Objfwd *o_fwd,
4165 const char *namestring, Lisp_Object *address)
4167 defvar_lisp_nopro (o_fwd, namestring, address);
4168 staticpro (address);
4171 /* Similar but define a variable whose value is the Lisp Object stored
4172 at a particular offset in the current kboard object. */
4174 void
4175 defvar_kboard (struct Lisp_Kboard_Objfwd *ko_fwd,
4176 const char *namestring, int offset)
4178 Lisp_Object sym;
4179 sym = intern_c_string (namestring);
4180 ko_fwd->type = Lisp_Fwd_Kboard_Obj;
4181 ko_fwd->offset = offset;
4182 XSYMBOL (sym)->declared_special = 1;
4183 XSYMBOL (sym)->redirect = SYMBOL_FORWARDED;
4184 SET_SYMBOL_FWD (XSYMBOL (sym), (union Lisp_Fwd *)ko_fwd);
4187 /* Check that the elements of lpath exist. */
4189 static void
4190 load_path_check (Lisp_Object lpath)
4192 Lisp_Object path_tail;
4194 /* The only elements that might not exist are those from
4195 PATH_LOADSEARCH, EMACSLOADPATH. Anything else is only added if
4196 it exists. */
4197 for (path_tail = lpath; !NILP (path_tail); path_tail = XCDR (path_tail))
4199 Lisp_Object dirfile;
4200 dirfile = Fcar (path_tail);
4201 if (STRINGP (dirfile))
4203 dirfile = Fdirectory_file_name (dirfile);
4204 if (! file_accessible_directory_p (dirfile))
4205 dir_warning ("Lisp directory", XCAR (path_tail));
4210 /* Return the default load-path, to be used if EMACSLOADPATH is unset.
4211 This does not include the standard site-lisp directories
4212 under the installation prefix (i.e., PATH_SITELOADSEARCH),
4213 but it does (unless no_site_lisp is set) include site-lisp
4214 directories in the source/build directories if those exist and we
4215 are running uninstalled.
4217 Uses the following logic:
4218 If CANNOT_DUMP: Use PATH_LOADSEARCH.
4219 The remainder is what happens when dumping works:
4220 If purify-flag (ie dumping) just use PATH_DUMPLOADSEARCH.
4221 Otherwise use PATH_LOADSEARCH.
4223 If !initialized, then just return PATH_DUMPLOADSEARCH.
4224 If initialized:
4225 If Vinstallation_directory is not nil (ie, running uninstalled):
4226 If installation-dir/lisp exists and not already a member,
4227 we must be running uninstalled. Reset the load-path
4228 to just installation-dir/lisp. (The default PATH_LOADSEARCH
4229 refers to the eventual installation directories. Since we
4230 are not yet installed, we should not use them, even if they exist.)
4231 If installation-dir/lisp does not exist, just add
4232 PATH_DUMPLOADSEARCH at the end instead.
4233 Add installation-dir/site-lisp (if !no_site_lisp, and exists
4234 and not already a member) at the front.
4235 If installation-dir != source-dir (ie running an uninstalled,
4236 out-of-tree build) AND install-dir/src/Makefile exists BUT
4237 install-dir/src/Makefile.in does NOT exist (this is a sanity
4238 check), then repeat the above steps for source-dir/lisp, site-lisp. */
4240 static Lisp_Object
4241 load_path_default (void)
4243 Lisp_Object lpath = Qnil;
4244 const char *normal;
4246 #ifdef CANNOT_DUMP
4247 #ifdef HAVE_NS
4248 const char *loadpath = ns_load_path ();
4249 #endif
4251 normal = PATH_LOADSEARCH;
4252 #ifdef HAVE_NS
4253 lpath = decode_env_path (0, loadpath ? loadpath : normal, 0);
4254 #else
4255 lpath = decode_env_path (0, normal, 0);
4256 #endif
4258 #else /* !CANNOT_DUMP */
4260 normal = NILP (Vpurify_flag) ? PATH_LOADSEARCH : PATH_DUMPLOADSEARCH;
4262 if (initialized)
4264 #ifdef HAVE_NS
4265 const char *loadpath = ns_load_path ();
4266 lpath = decode_env_path (0, loadpath ? loadpath : normal, 0);
4267 #else
4268 lpath = decode_env_path (0, normal, 0);
4269 #endif
4270 if (!NILP (Vinstallation_directory))
4272 Lisp_Object tem, tem1;
4274 /* Add to the path the lisp subdir of the installation
4275 dir, if it is accessible. Note: in out-of-tree builds,
4276 this directory is empty save for Makefile. */
4277 tem = Fexpand_file_name (build_string ("lisp"),
4278 Vinstallation_directory);
4279 tem1 = Ffile_accessible_directory_p (tem);
4280 if (!NILP (tem1))
4282 if (NILP (Fmember (tem, lpath)))
4284 /* We are running uninstalled. The default load-path
4285 points to the eventual installed lisp directories.
4286 We should not use those now, even if they exist,
4287 so start over from a clean slate. */
4288 lpath = list1 (tem);
4291 else
4292 /* That dir doesn't exist, so add the build-time
4293 Lisp dirs instead. */
4295 Lisp_Object dump_path =
4296 decode_env_path (0, PATH_DUMPLOADSEARCH, 0);
4297 lpath = nconc2 (lpath, dump_path);
4300 /* Add site-lisp under the installation dir, if it exists. */
4301 if (!no_site_lisp)
4303 tem = Fexpand_file_name (build_string ("site-lisp"),
4304 Vinstallation_directory);
4305 tem1 = Ffile_accessible_directory_p (tem);
4306 if (!NILP (tem1))
4308 if (NILP (Fmember (tem, lpath)))
4309 lpath = Fcons (tem, lpath);
4313 /* If Emacs was not built in the source directory,
4314 and it is run from where it was built, add to load-path
4315 the lisp and site-lisp dirs under that directory. */
4317 if (NILP (Fequal (Vinstallation_directory, Vsource_directory)))
4319 Lisp_Object tem2;
4321 tem = Fexpand_file_name (build_string ("src/Makefile"),
4322 Vinstallation_directory);
4323 tem1 = Ffile_exists_p (tem);
4325 /* Don't be fooled if they moved the entire source tree
4326 AFTER dumping Emacs. If the build directory is indeed
4327 different from the source dir, src/Makefile.in and
4328 src/Makefile will not be found together. */
4329 tem = Fexpand_file_name (build_string ("src/Makefile.in"),
4330 Vinstallation_directory);
4331 tem2 = Ffile_exists_p (tem);
4332 if (!NILP (tem1) && NILP (tem2))
4334 tem = Fexpand_file_name (build_string ("lisp"),
4335 Vsource_directory);
4337 if (NILP (Fmember (tem, lpath)))
4338 lpath = Fcons (tem, lpath);
4340 if (!no_site_lisp)
4342 tem = Fexpand_file_name (build_string ("site-lisp"),
4343 Vsource_directory);
4344 tem1 = Ffile_accessible_directory_p (tem);
4345 if (!NILP (tem1))
4347 if (NILP (Fmember (tem, lpath)))
4348 lpath = Fcons (tem, lpath);
4352 } /* Vinstallation_directory != Vsource_directory */
4354 } /* if Vinstallation_directory */
4356 else /* !initialized */
4358 /* NORMAL refers to PATH_DUMPLOADSEARCH, ie the lisp dir in the
4359 source directory. We used to add ../lisp (ie the lisp dir in
4360 the build directory) at the front here, but that should not
4361 be necessary, since in out of tree builds lisp/ is empty, save
4362 for Makefile. */
4363 lpath = decode_env_path (0, normal, 0);
4365 #endif /* !CANNOT_DUMP */
4367 return lpath;
4370 void
4371 init_lread (void)
4373 /* First, set Vload_path. */
4375 /* Ignore EMACSLOADPATH when dumping. */
4376 #ifdef CANNOT_DUMP
4377 bool use_loadpath = true;
4378 #else
4379 bool use_loadpath = NILP (Vpurify_flag);
4380 #endif
4382 if (use_loadpath && egetenv ("EMACSLOADPATH"))
4384 Vload_path = decode_env_path ("EMACSLOADPATH", 0, 1);
4386 /* Check (non-nil) user-supplied elements. */
4387 load_path_check (Vload_path);
4389 /* If no nils in the environment variable, use as-is.
4390 Otherwise, replace any nils with the default. */
4391 if (! NILP (Fmemq (Qnil, Vload_path)))
4393 Lisp_Object elem, elpath = Vload_path;
4394 Lisp_Object default_lpath = load_path_default ();
4396 /* Check defaults, before adding site-lisp. */
4397 load_path_check (default_lpath);
4399 /* Add the site-lisp directories to the front of the default. */
4400 if (!no_site_lisp)
4402 Lisp_Object sitelisp;
4403 sitelisp = decode_env_path (0, PATH_SITELOADSEARCH, 0);
4404 if (! NILP (sitelisp))
4405 default_lpath = nconc2 (sitelisp, default_lpath);
4408 Vload_path = Qnil;
4410 /* Replace nils from EMACSLOADPATH by default. */
4411 while (CONSP (elpath))
4413 Lisp_Object arg[2];
4414 elem = XCAR (elpath);
4415 elpath = XCDR (elpath);
4416 arg[0] = Vload_path;
4417 arg[1] = NILP (elem) ? default_lpath : Fcons (elem, Qnil);
4418 Vload_path = Fappend (2, arg);
4420 } /* Fmemq (Qnil, Vload_path) */
4422 else
4424 Vload_path = load_path_default ();
4426 /* Check before adding site-lisp directories.
4427 The install should have created them, but they are not
4428 required, so no need to warn if they are absent.
4429 Or we might be running before installation. */
4430 load_path_check (Vload_path);
4432 /* Add the site-lisp directories at the front. */
4433 if (initialized && !no_site_lisp)
4435 Lisp_Object sitelisp;
4436 sitelisp = decode_env_path (0, PATH_SITELOADSEARCH, 0);
4437 if (! NILP (sitelisp)) Vload_path = nconc2 (sitelisp, Vload_path);
4441 Vvalues = Qnil;
4443 load_in_progress = 0;
4444 Vload_file_name = Qnil;
4445 Vstandard_input = Qt;
4446 Vloads_in_progress = Qnil;
4449 /* Print a warning that directory intended for use USE and with name
4450 DIRNAME cannot be accessed. On entry, errno should correspond to
4451 the access failure. Print the warning on stderr and put it in
4452 *Messages*. */
4454 void
4455 dir_warning (char const *use, Lisp_Object dirname)
4457 static char const format[] = "Warning: %s `%s': %s\n";
4458 int access_errno = errno;
4459 fprintf (stderr, format, use, SSDATA (dirname), strerror (access_errno));
4461 /* Don't log the warning before we've initialized!! */
4462 if (initialized)
4464 char const *diagnostic = emacs_strerror (access_errno);
4465 USE_SAFE_ALLOCA;
4466 char *buffer = SAFE_ALLOCA (sizeof format - 3 * (sizeof "%s" - 1)
4467 + strlen (use) + SBYTES (dirname)
4468 + strlen (diagnostic));
4469 ptrdiff_t message_len = esprintf (buffer, format, use, SSDATA (dirname),
4470 diagnostic);
4471 message_dolog (buffer, message_len, 0, STRING_MULTIBYTE (dirname));
4472 SAFE_FREE ();
4476 void
4477 syms_of_lread (void)
4479 defsubr (&Sread);
4480 defsubr (&Sread_from_string);
4481 defsubr (&Sintern);
4482 defsubr (&Sintern_soft);
4483 defsubr (&Sunintern);
4484 defsubr (&Sget_load_suffixes);
4485 defsubr (&Sload);
4486 defsubr (&Seval_buffer);
4487 defsubr (&Seval_region);
4488 defsubr (&Sread_char);
4489 defsubr (&Sread_char_exclusive);
4490 defsubr (&Sread_event);
4491 defsubr (&Sget_file_char);
4492 defsubr (&Smapatoms);
4493 defsubr (&Slocate_file_internal);
4495 DEFVAR_LISP ("obarray", Vobarray,
4496 doc: /* Symbol table for use by `intern' and `read'.
4497 It is a vector whose length ought to be prime for best results.
4498 The vector's contents don't make sense if examined from Lisp programs;
4499 to find all the symbols in an obarray, use `mapatoms'. */);
4501 DEFVAR_LISP ("values", Vvalues,
4502 doc: /* List of values of all expressions which were read, evaluated and printed.
4503 Order is reverse chronological. */);
4504 XSYMBOL (intern ("values"))->declared_special = 0;
4506 DEFVAR_LISP ("standard-input", Vstandard_input,
4507 doc: /* Stream for read to get input from.
4508 See documentation of `read' for possible values. */);
4509 Vstandard_input = Qt;
4511 DEFVAR_LISP ("read-with-symbol-positions", Vread_with_symbol_positions,
4512 doc: /* If non-nil, add position of read symbols to `read-symbol-positions-list'.
4514 If this variable is a buffer, then only forms read from that buffer
4515 will be added to `read-symbol-positions-list'.
4516 If this variable is t, then all read forms will be added.
4517 The effect of all other values other than nil are not currently
4518 defined, although they may be in the future.
4520 The positions are relative to the last call to `read' or
4521 `read-from-string'. It is probably a bad idea to set this variable at
4522 the toplevel; bind it instead. */);
4523 Vread_with_symbol_positions = Qnil;
4525 DEFVAR_LISP ("read-symbol-positions-list", Vread_symbol_positions_list,
4526 doc: /* A list mapping read symbols to their positions.
4527 This variable is modified during calls to `read' or
4528 `read-from-string', but only when `read-with-symbol-positions' is
4529 non-nil.
4531 Each element of the list looks like (SYMBOL . CHAR-POSITION), where
4532 CHAR-POSITION is an integer giving the offset of that occurrence of the
4533 symbol from the position where `read' or `read-from-string' started.
4535 Note that a symbol will appear multiple times in this list, if it was
4536 read multiple times. The list is in the same order as the symbols
4537 were read in. */);
4538 Vread_symbol_positions_list = Qnil;
4540 DEFVAR_LISP ("read-circle", Vread_circle,
4541 doc: /* Non-nil means read recursive structures using #N= and #N# syntax. */);
4542 Vread_circle = Qt;
4544 DEFVAR_LISP ("load-path", Vload_path,
4545 doc: /* List of directories to search for files to load.
4546 Each element is a string (directory name) or nil (meaning `default-directory').
4547 Initialized during startup as described in Info node `(elisp)Library Search'. */);
4549 DEFVAR_LISP ("load-suffixes", Vload_suffixes,
4550 doc: /* List of suffixes for (compiled or source) Emacs Lisp files.
4551 This list should not include the empty string.
4552 `load' and related functions try to append these suffixes, in order,
4553 to the specified file name if a Lisp suffix is allowed or required. */);
4554 Vload_suffixes = list2 (build_pure_c_string (".elc"),
4555 build_pure_c_string (".el"));
4556 DEFVAR_LISP ("load-file-rep-suffixes", Vload_file_rep_suffixes,
4557 doc: /* List of suffixes that indicate representations of \
4558 the same file.
4559 This list should normally start with the empty string.
4561 Enabling Auto Compression mode appends the suffixes in
4562 `jka-compr-load-suffixes' to this list and disabling Auto Compression
4563 mode removes them again. `load' and related functions use this list to
4564 determine whether they should look for compressed versions of a file
4565 and, if so, which suffixes they should try to append to the file name
4566 in order to do so. However, if you want to customize which suffixes
4567 the loading functions recognize as compression suffixes, you should
4568 customize `jka-compr-load-suffixes' rather than the present variable. */);
4569 Vload_file_rep_suffixes = list1 (empty_unibyte_string);
4571 DEFVAR_BOOL ("load-in-progress", load_in_progress,
4572 doc: /* Non-nil if inside of `load'. */);
4573 DEFSYM (Qload_in_progress, "load-in-progress");
4575 DEFVAR_LISP ("after-load-alist", Vafter_load_alist,
4576 doc: /* An alist of functions to be evalled when particular files are loaded.
4577 Each element looks like (REGEXP-OR-FEATURE FUNCS...).
4579 REGEXP-OR-FEATURE is either a regular expression to match file names, or
4580 a symbol \(a feature name).
4582 When `load' is run and the file-name argument matches an element's
4583 REGEXP-OR-FEATURE, or when `provide' is run and provides the symbol
4584 REGEXP-OR-FEATURE, the FUNCS in the element are called.
4586 An error in FORMS does not undo the load, but does prevent execution of
4587 the rest of the FORMS. */);
4588 Vafter_load_alist = Qnil;
4590 DEFVAR_LISP ("load-history", Vload_history,
4591 doc: /* Alist mapping loaded file names to symbols and features.
4592 Each alist element should be a list (FILE-NAME ENTRIES...), where
4593 FILE-NAME is the name of a file that has been loaded into Emacs.
4594 The file name is absolute and true (i.e. it doesn't contain symlinks).
4595 As an exception, one of the alist elements may have FILE-NAME nil,
4596 for symbols and features not associated with any file.
4598 The remaining ENTRIES in the alist element describe the functions and
4599 variables defined in that file, the features provided, and the
4600 features required. Each entry has the form `(provide . FEATURE)',
4601 `(require . FEATURE)', `(defun . FUNCTION)', `(autoload . SYMBOL)',
4602 `(defface . SYMBOL)', or `(t . SYMBOL)'. Entries like `(t . SYMBOL)'
4603 may precede a `(defun . FUNCTION)' entry, and means that SYMBOL was an
4604 autoload before this file redefined it as a function. In addition,
4605 entries may also be single symbols, which means that SYMBOL was
4606 defined by `defvar' or `defconst'.
4608 During preloading, the file name recorded is relative to the main Lisp
4609 directory. These file names are converted to absolute at startup. */);
4610 Vload_history = Qnil;
4612 DEFVAR_LISP ("load-file-name", Vload_file_name,
4613 doc: /* Full name of file being loaded by `load'. */);
4614 Vload_file_name = Qnil;
4616 DEFVAR_LISP ("user-init-file", Vuser_init_file,
4617 doc: /* File name, including directory, of user's initialization file.
4618 If the file loaded had extension `.elc', and the corresponding source file
4619 exists, this variable contains the name of source file, suitable for use
4620 by functions like `custom-save-all' which edit the init file.
4621 While Emacs loads and evaluates the init file, value is the real name
4622 of the file, regardless of whether or not it has the `.elc' extension. */);
4623 Vuser_init_file = Qnil;
4625 DEFVAR_LISP ("current-load-list", Vcurrent_load_list,
4626 doc: /* Used for internal purposes by `load'. */);
4627 Vcurrent_load_list = Qnil;
4629 DEFVAR_LISP ("load-read-function", Vload_read_function,
4630 doc: /* Function used by `load' and `eval-region' for reading expressions.
4631 The default is nil, which means use the function `read'. */);
4632 Vload_read_function = Qnil;
4634 DEFVAR_LISP ("load-source-file-function", Vload_source_file_function,
4635 doc: /* Function called in `load' to load an Emacs Lisp source file.
4636 The value should be a function for doing code conversion before
4637 reading a source file. It can also be nil, in which case loading is
4638 done without any code conversion.
4640 If the value is a function, it is called with four arguments,
4641 FULLNAME, FILE, NOERROR, NOMESSAGE. FULLNAME is the absolute name of
4642 the file to load, FILE is the non-absolute name (for messages etc.),
4643 and NOERROR and NOMESSAGE are the corresponding arguments passed to
4644 `load'. The function should return t if the file was loaded. */);
4645 Vload_source_file_function = Qnil;
4647 DEFVAR_BOOL ("load-force-doc-strings", load_force_doc_strings,
4648 doc: /* Non-nil means `load' should force-load all dynamic doc strings.
4649 This is useful when the file being loaded is a temporary copy. */);
4650 load_force_doc_strings = 0;
4652 DEFVAR_BOOL ("load-convert-to-unibyte", load_convert_to_unibyte,
4653 doc: /* Non-nil means `read' converts strings to unibyte whenever possible.
4654 This is normally bound by `load' and `eval-buffer' to control `read',
4655 and is not meant for users to change. */);
4656 load_convert_to_unibyte = 0;
4658 DEFVAR_LISP ("source-directory", Vsource_directory,
4659 doc: /* Directory in which Emacs sources were found when Emacs was built.
4660 You cannot count on them to still be there! */);
4661 Vsource_directory
4662 = Fexpand_file_name (build_string ("../"),
4663 Fcar (decode_env_path (0, PATH_DUMPLOADSEARCH, 0)));
4665 DEFVAR_LISP ("preloaded-file-list", Vpreloaded_file_list,
4666 doc: /* List of files that were preloaded (when dumping Emacs). */);
4667 Vpreloaded_file_list = Qnil;
4669 DEFVAR_LISP ("byte-boolean-vars", Vbyte_boolean_vars,
4670 doc: /* List of all DEFVAR_BOOL variables, used by the byte code optimizer. */);
4671 Vbyte_boolean_vars = Qnil;
4673 DEFVAR_BOOL ("load-dangerous-libraries", load_dangerous_libraries,
4674 doc: /* Non-nil means load dangerous compiled Lisp files.
4675 Some versions of XEmacs use different byte codes than Emacs. These
4676 incompatible byte codes can make Emacs crash when it tries to execute
4677 them. */);
4678 load_dangerous_libraries = 0;
4680 DEFVAR_BOOL ("force-load-messages", force_load_messages,
4681 doc: /* Non-nil means force printing messages when loading Lisp files.
4682 This overrides the value of the NOMESSAGE argument to `load'. */);
4683 force_load_messages = 0;
4685 DEFVAR_LISP ("bytecomp-version-regexp", Vbytecomp_version_regexp,
4686 doc: /* Regular expression matching safe to load compiled Lisp files.
4687 When Emacs loads a compiled Lisp file, it reads the first 512 bytes
4688 from the file, and matches them against this regular expression.
4689 When the regular expression matches, the file is considered to be safe
4690 to load. See also `load-dangerous-libraries'. */);
4691 Vbytecomp_version_regexp
4692 = build_pure_c_string ("^;;;.\\(in Emacs version\\|bytecomp version FSF\\)");
4694 DEFSYM (Qlexical_binding, "lexical-binding");
4695 DEFVAR_LISP ("lexical-binding", Vlexical_binding,
4696 doc: /* Whether to use lexical binding when evaluating code.
4697 Non-nil means that the code in the current buffer should be evaluated
4698 with lexical binding.
4699 This variable is automatically set from the file variables of an
4700 interpreted Lisp file read using `load'. Unlike other file local
4701 variables, this must be set in the first line of a file. */);
4702 Vlexical_binding = Qnil;
4703 Fmake_variable_buffer_local (Qlexical_binding);
4705 DEFVAR_LISP ("eval-buffer-list", Veval_buffer_list,
4706 doc: /* List of buffers being read from by calls to `eval-buffer' and `eval-region'. */);
4707 Veval_buffer_list = Qnil;
4709 DEFVAR_LISP ("old-style-backquotes", Vold_style_backquotes,
4710 doc: /* Set to non-nil when `read' encounters an old-style backquote. */);
4711 Vold_style_backquotes = Qnil;
4712 DEFSYM (Qold_style_backquotes, "old-style-backquotes");
4714 DEFVAR_BOOL ("load-prefer-newer", load_prefer_newer,
4715 doc: /* Non-nil means `load' prefers the newest version of a file.
4716 This applies when a filename suffix is not explicitly specified and
4717 `load' is trying various possible suffixes (see `load-suffixes' and
4718 `load-file-rep-suffixes'). Normally, it stops at the first file
4719 that exists unless you explicitly specify one or the other. If this
4720 option is non-nil, it checks all suffixes and uses whichever file is
4721 newest.
4722 Note that if you customize this, obviously it will not affect files
4723 that are loaded before your customizations are read! */);
4724 load_prefer_newer = 0;
4726 /* Vsource_directory was initialized in init_lread. */
4728 DEFSYM (Qcurrent_load_list, "current-load-list");
4729 DEFSYM (Qstandard_input, "standard-input");
4730 DEFSYM (Qread_char, "read-char");
4731 DEFSYM (Qget_file_char, "get-file-char");
4732 DEFSYM (Qget_emacs_mule_file_char, "get-emacs-mule-file-char");
4733 DEFSYM (Qload_force_doc_strings, "load-force-doc-strings");
4735 DEFSYM (Qbackquote, "`");
4736 DEFSYM (Qcomma, ",");
4737 DEFSYM (Qcomma_at, ",@");
4738 DEFSYM (Qcomma_dot, ",.");
4740 DEFSYM (Qinhibit_file_name_operation, "inhibit-file-name-operation");
4741 DEFSYM (Qascii_character, "ascii-character");
4742 DEFSYM (Qfunction, "function");
4743 DEFSYM (Qload, "load");
4744 DEFSYM (Qload_file_name, "load-file-name");
4745 DEFSYM (Qeval_buffer_list, "eval-buffer-list");
4746 DEFSYM (Qfile_truename, "file-truename");
4747 DEFSYM (Qdir_ok, "dir-ok");
4748 DEFSYM (Qdo_after_load_evaluation, "do-after-load-evaluation");
4750 staticpro (&read_objects);
4751 read_objects = Qnil;
4752 staticpro (&seen_list);
4753 seen_list = Qnil;
4755 Vloads_in_progress = Qnil;
4756 staticpro (&Vloads_in_progress);
4758 DEFSYM (Qhash_table, "hash-table");
4759 DEFSYM (Qdata, "data");
4760 DEFSYM (Qtest, "test");
4761 DEFSYM (Qsize, "size");
4762 DEFSYM (Qweakness, "weakness");
4763 DEFSYM (Qrehash_size, "rehash-size");
4764 DEFSYM (Qrehash_threshold, "rehash-threshold");