]> code.delx.au - gnu-emacs/blob - src/fns.c
e891fdbf1d5ac4251820867a6e16c9a0e5b17d40
[gnu-emacs] / src / fns.c
1 /* Random utility Lisp functions.
2
3 Copyright (C) 1985-1987, 1993-1995, 1997-2014 Free Software Foundation,
4 Inc.
5
6 This file is part of GNU Emacs.
7
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.
12
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.
17
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/>. */
20
21 #include <config.h>
22
23 #include <unistd.h>
24 #include <time.h>
25
26 #include <intprops.h>
27 #include <vla.h>
28
29 #include "lisp.h"
30 #include "commands.h"
31 #include "character.h"
32 #include "coding.h"
33 #include "buffer.h"
34 #include "keyboard.h"
35 #include "keymap.h"
36 #include "intervals.h"
37 #include "frame.h"
38 #include "window.h"
39 #include "blockinput.h"
40 #if defined (HAVE_X_WINDOWS)
41 #include "xterm.h"
42 #endif
43
44 Lisp_Object Qstring_lessp;
45 static Lisp_Object Qstring_collate_lessp, Qstring_collate_equalp;
46 static Lisp_Object Qprovide, Qrequire;
47 static Lisp_Object Qyes_or_no_p_history;
48 Lisp_Object Qcursor_in_echo_area;
49 static Lisp_Object Qwidget_type;
50 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
51
52 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
53
54 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
55 Lisp_Object [restrict], Lisp_Object [restrict]);
56 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
57
58 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
59 doc: /* Return the argument unchanged. */)
60 (Lisp_Object arg)
61 {
62 return arg;
63 }
64
65 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
66 doc: /* Return a pseudo-random number.
67 All integers representable in Lisp, i.e. between `most-negative-fixnum'
68 and `most-positive-fixnum', inclusive, are equally likely.
69
70 With positive integer LIMIT, return random number in interval [0,LIMIT).
71 With argument t, set the random number seed from the current time and pid.
72 With a string argument, set the seed based on the string's contents.
73 Other values of LIMIT are ignored.
74
75 See Info node `(elisp)Random Numbers' for more details. */)
76 (Lisp_Object limit)
77 {
78 EMACS_INT val;
79
80 if (EQ (limit, Qt))
81 init_random ();
82 else if (STRINGP (limit))
83 seed_random (SSDATA (limit), SBYTES (limit));
84
85 val = get_random ();
86 if (INTEGERP (limit) && 0 < XINT (limit))
87 while (true)
88 {
89 /* Return the remainder, except reject the rare case where
90 get_random returns a number so close to INTMASK that the
91 remainder isn't random. */
92 EMACS_INT remainder = val % XINT (limit);
93 if (val - remainder <= INTMASK - XINT (limit) + 1)
94 return make_number (remainder);
95 val = get_random ();
96 }
97 return make_number (val);
98 }
99 \f
100 /* Heuristic on how many iterations of a tight loop can be safely done
101 before it's time to do a QUIT. This must be a power of 2. */
102 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
103
104 /* Random data-structure functions. */
105
106 static void
107 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
108 {
109 CHECK_TYPE (NILP (x), Qlistp, y);
110 }
111
112 DEFUN ("length", Flength, Slength, 1, 1, 0,
113 doc: /* Return the length of vector, list or string SEQUENCE.
114 A byte-code function object is also allowed.
115 If the string contains multibyte characters, this is not necessarily
116 the number of bytes in the string; it is the number of characters.
117 To get the number of bytes, use `string-bytes'. */)
118 (register Lisp_Object sequence)
119 {
120 register Lisp_Object val;
121
122 if (STRINGP (sequence))
123 XSETFASTINT (val, SCHARS (sequence));
124 else if (VECTORP (sequence))
125 XSETFASTINT (val, ASIZE (sequence));
126 else if (CHAR_TABLE_P (sequence))
127 XSETFASTINT (val, MAX_CHAR);
128 else if (BOOL_VECTOR_P (sequence))
129 XSETFASTINT (val, bool_vector_size (sequence));
130 else if (COMPILEDP (sequence))
131 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
132 else if (CONSP (sequence))
133 {
134 EMACS_INT i = 0;
135
136 do
137 {
138 ++i;
139 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
140 {
141 if (MOST_POSITIVE_FIXNUM < i)
142 error ("List too long");
143 QUIT;
144 }
145 sequence = XCDR (sequence);
146 }
147 while (CONSP (sequence));
148
149 CHECK_LIST_END (sequence, sequence);
150
151 val = make_number (i);
152 }
153 else if (NILP (sequence))
154 XSETFASTINT (val, 0);
155 else
156 wrong_type_argument (Qsequencep, sequence);
157
158 return val;
159 }
160
161 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
162 doc: /* Return the length of a list, but avoid error or infinite loop.
163 This function never gets an error. If LIST is not really a list,
164 it returns 0. If LIST is circular, it returns a finite value
165 which is at least the number of distinct elements. */)
166 (Lisp_Object list)
167 {
168 Lisp_Object tail, halftail;
169 double hilen = 0;
170 uintmax_t lolen = 1;
171
172 if (! CONSP (list))
173 return make_number (0);
174
175 /* halftail is used to detect circular lists. */
176 for (tail = halftail = list; ; )
177 {
178 tail = XCDR (tail);
179 if (! CONSP (tail))
180 break;
181 if (EQ (tail, halftail))
182 break;
183 lolen++;
184 if ((lolen & 1) == 0)
185 {
186 halftail = XCDR (halftail);
187 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
188 {
189 QUIT;
190 if (lolen == 0)
191 hilen += UINTMAX_MAX + 1.0;
192 }
193 }
194 }
195
196 /* If the length does not fit into a fixnum, return a float.
197 On all known practical machines this returns an upper bound on
198 the true length. */
199 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
200 }
201
202 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
203 doc: /* Return the number of bytes in STRING.
204 If STRING is multibyte, this may be greater than the length of STRING. */)
205 (Lisp_Object string)
206 {
207 CHECK_STRING (string);
208 return make_number (SBYTES (string));
209 }
210
211 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
212 doc: /* Return t if two strings have identical contents.
213 Case is significant, but text properties are ignored.
214 Symbols are also allowed; their print names are used instead. */)
215 (register Lisp_Object s1, Lisp_Object s2)
216 {
217 if (SYMBOLP (s1))
218 s1 = SYMBOL_NAME (s1);
219 if (SYMBOLP (s2))
220 s2 = SYMBOL_NAME (s2);
221 CHECK_STRING (s1);
222 CHECK_STRING (s2);
223
224 if (SCHARS (s1) != SCHARS (s2)
225 || SBYTES (s1) != SBYTES (s2)
226 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
227 return Qnil;
228 return Qt;
229 }
230
231 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
232 doc: /* Compare the contents of two strings, converting to multibyte if needed.
233 The arguments START1, END1, START2, and END2, if non-nil, are
234 positions specifying which parts of STR1 or STR2 to compare. In
235 string STR1, compare the part between START1 (inclusive) and END1
236 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
237 the string; if END1 is nil, it defaults to the length of the string.
238 Likewise, in string STR2, compare the part between START2 and END2.
239 Like in `substring', negative values are counted from the end.
240
241 The strings are compared by the numeric values of their characters.
242 For instance, STR1 is "less than" STR2 if its first differing
243 character has a smaller numeric value. If IGNORE-CASE is non-nil,
244 characters are converted to lower-case before comparing them. Unibyte
245 strings are converted to multibyte for comparison.
246
247 The value is t if the strings (or specified portions) match.
248 If string STR1 is less, the value is a negative number N;
249 - 1 - N is the number of characters that match at the beginning.
250 If string STR1 is greater, the value is a positive number N;
251 N - 1 is the number of characters that match at the beginning. */)
252 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
253 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
254 {
255 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
256
257 CHECK_STRING (str1);
258 CHECK_STRING (str2);
259
260 /* For backward compatibility, silently bring too-large positive end
261 values into range. */
262 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
263 end1 = make_number (SCHARS (str1));
264 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
265 end2 = make_number (SCHARS (str2));
266
267 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
268 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
269
270 i1 = from1;
271 i2 = from2;
272
273 i1_byte = string_char_to_byte (str1, i1);
274 i2_byte = string_char_to_byte (str2, i2);
275
276 while (i1 < to1 && i2 < to2)
277 {
278 /* When we find a mismatch, we must compare the
279 characters, not just the bytes. */
280 int c1, c2;
281
282 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
283 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
284
285 if (c1 == c2)
286 continue;
287
288 if (! NILP (ignore_case))
289 {
290 c1 = XINT (Fupcase (make_number (c1)));
291 c2 = XINT (Fupcase (make_number (c2)));
292 }
293
294 if (c1 == c2)
295 continue;
296
297 /* Note that I1 has already been incremented
298 past the character that we are comparing;
299 hence we don't add or subtract 1 here. */
300 if (c1 < c2)
301 return make_number (- i1 + from1);
302 else
303 return make_number (i1 - from1);
304 }
305
306 if (i1 < to1)
307 return make_number (i1 - from1 + 1);
308 if (i2 < to2)
309 return make_number (- i1 + from1 - 1);
310
311 return Qt;
312 }
313
314 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
315 doc: /* Return t if first arg string is less than second in lexicographic order.
316 Case is significant.
317 Symbols are also allowed; their print names are used instead. */)
318 (register Lisp_Object s1, Lisp_Object s2)
319 {
320 register ptrdiff_t end;
321 register ptrdiff_t i1, i1_byte, i2, i2_byte;
322
323 if (SYMBOLP (s1))
324 s1 = SYMBOL_NAME (s1);
325 if (SYMBOLP (s2))
326 s2 = SYMBOL_NAME (s2);
327 CHECK_STRING (s1);
328 CHECK_STRING (s2);
329
330 i1 = i1_byte = i2 = i2_byte = 0;
331
332 end = SCHARS (s1);
333 if (end > SCHARS (s2))
334 end = SCHARS (s2);
335
336 while (i1 < end)
337 {
338 /* When we find a mismatch, we must compare the
339 characters, not just the bytes. */
340 int c1, c2;
341
342 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
343 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
344
345 if (c1 != c2)
346 return c1 < c2 ? Qt : Qnil;
347 }
348 return i1 < SCHARS (s2) ? Qt : Qnil;
349 }
350
351 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
352 doc: /* Return t if first arg string is less than second in collation order.
353 Symbols are also allowed; their print names are used instead.
354
355 This function obeys the conventions for collation order in your
356 locale settings. For example, punctuation and whitespace characters
357 might be considered less significant for sorting:
358
359 \(sort '\("11" "12" "1 1" "1 2" "1.1" "1.2") 'string-collate-lessp)
360 => \("11" "1 1" "1.1" "12" "1 2" "1.2")
361
362 The optional argument LOCALE, a string, overrides the setting of your
363 current locale identifier for collation. The value is system
364 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
365 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
366
367 If IGNORE-CASE is non-nil, characters are converted to lower-case
368 before comparing them.
369
370 To emulate Unicode-compliant collation on MS-Windows systems,
371 bind `w32-collate-ignore-punctuation' to a non-nil value, since
372 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
373
374 If your system does not support a locale environment, this function
375 behaves like `string-lessp'. */)
376 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
377 {
378 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
379 /* Check parameters. */
380 if (SYMBOLP (s1))
381 s1 = SYMBOL_NAME (s1);
382 if (SYMBOLP (s2))
383 s2 = SYMBOL_NAME (s2);
384 CHECK_STRING (s1);
385 CHECK_STRING (s2);
386 if (!NILP (locale))
387 CHECK_STRING (locale);
388
389 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
390
391 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
392 return Fstring_lessp (s1, s2);
393 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
394 }
395
396 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
397 doc: /* Return t if two strings have identical contents.
398 Symbols are also allowed; their print names are used instead.
399
400 This function obeys the conventions for collation order in your locale
401 settings. For example, characters with different coding points but
402 the same meaning might be considered as equal, like different grave
403 accent Unicode characters:
404
405 \(string-collate-equalp \(string ?\\uFF40) \(string ?\\u1FEF))
406 => t
407
408 The optional argument LOCALE, a string, overrides the setting of your
409 current locale identifier for collation. The value is system
410 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
411 while it would be \"enu_USA.1252\" on MS Windows systems.
412
413 If IGNORE-CASE is non-nil, characters are converted to lower-case
414 before comparing them.
415
416 To emulate Unicode-compliant collation on MS-Windows systems,
417 bind `w32-collate-ignore-punctuation' to a non-nil value, since
418 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
419
420 If your system does not support a locale environment, this function
421 behaves like `string-equal'.
422
423 Do NOT use this function to compare file names for equality, only
424 for sorting them. */)
425 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
426 {
427 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
428 /* Check parameters. */
429 if (SYMBOLP (s1))
430 s1 = SYMBOL_NAME (s1);
431 if (SYMBOLP (s2))
432 s2 = SYMBOL_NAME (s2);
433 CHECK_STRING (s1);
434 CHECK_STRING (s2);
435 if (!NILP (locale))
436 CHECK_STRING (locale);
437
438 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
439
440 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
441 return Fstring_equal (s1, s2);
442 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
443 }
444 \f
445 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
446 enum Lisp_Type target_type, bool last_special);
447
448 /* ARGSUSED */
449 Lisp_Object
450 concat2 (Lisp_Object s1, Lisp_Object s2)
451 {
452 Lisp_Object args[2];
453 args[0] = s1;
454 args[1] = s2;
455 return concat (2, args, Lisp_String, 0);
456 }
457
458 /* ARGSUSED */
459 Lisp_Object
460 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
461 {
462 Lisp_Object args[3];
463 args[0] = s1;
464 args[1] = s2;
465 args[2] = s3;
466 return concat (3, args, Lisp_String, 0);
467 }
468
469 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
470 doc: /* Concatenate all the arguments and make the result a list.
471 The result is a list whose elements are the elements of all the arguments.
472 Each argument may be a list, vector or string.
473 The last argument is not copied, just used as the tail of the new list.
474 usage: (append &rest SEQUENCES) */)
475 (ptrdiff_t nargs, Lisp_Object *args)
476 {
477 return concat (nargs, args, Lisp_Cons, 1);
478 }
479
480 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
481 doc: /* Concatenate all the arguments and make the result a string.
482 The result is a string whose elements are the elements of all the arguments.
483 Each argument may be a string or a list or vector of characters (integers).
484 usage: (concat &rest SEQUENCES) */)
485 (ptrdiff_t nargs, Lisp_Object *args)
486 {
487 return concat (nargs, args, Lisp_String, 0);
488 }
489
490 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
491 doc: /* Concatenate all the arguments and make the result a vector.
492 The result is a vector whose elements are the elements of all the arguments.
493 Each argument may be a list, vector or string.
494 usage: (vconcat &rest SEQUENCES) */)
495 (ptrdiff_t nargs, Lisp_Object *args)
496 {
497 return concat (nargs, args, Lisp_Vectorlike, 0);
498 }
499
500
501 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
502 doc: /* Return a copy of a list, vector, string or char-table.
503 The elements of a list or vector are not copied; they are shared
504 with the original. */)
505 (Lisp_Object arg)
506 {
507 if (NILP (arg)) return arg;
508
509 if (CHAR_TABLE_P (arg))
510 {
511 return copy_char_table (arg);
512 }
513
514 if (BOOL_VECTOR_P (arg))
515 {
516 EMACS_INT nbits = bool_vector_size (arg);
517 ptrdiff_t nbytes = bool_vector_bytes (nbits);
518 Lisp_Object val = make_uninit_bool_vector (nbits);
519 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
520 return val;
521 }
522
523 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
524 wrong_type_argument (Qsequencep, arg);
525
526 return concat (1, &arg, XTYPE (arg), 0);
527 }
528
529 /* This structure holds information of an argument of `concat' that is
530 a string and has text properties to be copied. */
531 struct textprop_rec
532 {
533 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
534 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
535 ptrdiff_t to; /* refer to VAL (the target string) */
536 };
537
538 static Lisp_Object
539 concat (ptrdiff_t nargs, Lisp_Object *args,
540 enum Lisp_Type target_type, bool last_special)
541 {
542 Lisp_Object val;
543 Lisp_Object tail;
544 Lisp_Object this;
545 ptrdiff_t toindex;
546 ptrdiff_t toindex_byte = 0;
547 EMACS_INT result_len;
548 EMACS_INT result_len_byte;
549 ptrdiff_t argnum;
550 Lisp_Object last_tail;
551 Lisp_Object prev;
552 bool some_multibyte;
553 /* When we make a multibyte string, we can't copy text properties
554 while concatenating each string because the length of resulting
555 string can't be decided until we finish the whole concatenation.
556 So, we record strings that have text properties to be copied
557 here, and copy the text properties after the concatenation. */
558 struct textprop_rec *textprops = NULL;
559 /* Number of elements in textprops. */
560 ptrdiff_t num_textprops = 0;
561 USE_SAFE_ALLOCA;
562
563 tail = Qnil;
564
565 /* In append, the last arg isn't treated like the others */
566 if (last_special && nargs > 0)
567 {
568 nargs--;
569 last_tail = args[nargs];
570 }
571 else
572 last_tail = Qnil;
573
574 /* Check each argument. */
575 for (argnum = 0; argnum < nargs; argnum++)
576 {
577 this = args[argnum];
578 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
579 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
580 wrong_type_argument (Qsequencep, this);
581 }
582
583 /* Compute total length in chars of arguments in RESULT_LEN.
584 If desired output is a string, also compute length in bytes
585 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
586 whether the result should be a multibyte string. */
587 result_len_byte = 0;
588 result_len = 0;
589 some_multibyte = 0;
590 for (argnum = 0; argnum < nargs; argnum++)
591 {
592 EMACS_INT len;
593 this = args[argnum];
594 len = XFASTINT (Flength (this));
595 if (target_type == Lisp_String)
596 {
597 /* We must count the number of bytes needed in the string
598 as well as the number of characters. */
599 ptrdiff_t i;
600 Lisp_Object ch;
601 int c;
602 ptrdiff_t this_len_byte;
603
604 if (VECTORP (this) || COMPILEDP (this))
605 for (i = 0; i < len; i++)
606 {
607 ch = AREF (this, i);
608 CHECK_CHARACTER (ch);
609 c = XFASTINT (ch);
610 this_len_byte = CHAR_BYTES (c);
611 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
612 string_overflow ();
613 result_len_byte += this_len_byte;
614 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
615 some_multibyte = 1;
616 }
617 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
618 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
619 else if (CONSP (this))
620 for (; CONSP (this); this = XCDR (this))
621 {
622 ch = XCAR (this);
623 CHECK_CHARACTER (ch);
624 c = XFASTINT (ch);
625 this_len_byte = CHAR_BYTES (c);
626 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
627 string_overflow ();
628 result_len_byte += this_len_byte;
629 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
630 some_multibyte = 1;
631 }
632 else if (STRINGP (this))
633 {
634 if (STRING_MULTIBYTE (this))
635 {
636 some_multibyte = 1;
637 this_len_byte = SBYTES (this);
638 }
639 else
640 this_len_byte = count_size_as_multibyte (SDATA (this),
641 SCHARS (this));
642 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
643 string_overflow ();
644 result_len_byte += this_len_byte;
645 }
646 }
647
648 result_len += len;
649 if (MOST_POSITIVE_FIXNUM < result_len)
650 memory_full (SIZE_MAX);
651 }
652
653 if (! some_multibyte)
654 result_len_byte = result_len;
655
656 /* Create the output object. */
657 if (target_type == Lisp_Cons)
658 val = Fmake_list (make_number (result_len), Qnil);
659 else if (target_type == Lisp_Vectorlike)
660 val = Fmake_vector (make_number (result_len), Qnil);
661 else if (some_multibyte)
662 val = make_uninit_multibyte_string (result_len, result_len_byte);
663 else
664 val = make_uninit_string (result_len);
665
666 /* In `append', if all but last arg are nil, return last arg. */
667 if (target_type == Lisp_Cons && EQ (val, Qnil))
668 return last_tail;
669
670 /* Copy the contents of the args into the result. */
671 if (CONSP (val))
672 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
673 else
674 toindex = 0, toindex_byte = 0;
675
676 prev = Qnil;
677 if (STRINGP (val))
678 SAFE_NALLOCA (textprops, 1, nargs);
679
680 for (argnum = 0; argnum < nargs; argnum++)
681 {
682 Lisp_Object thislen;
683 ptrdiff_t thisleni = 0;
684 register ptrdiff_t thisindex = 0;
685 register ptrdiff_t thisindex_byte = 0;
686
687 this = args[argnum];
688 if (!CONSP (this))
689 thislen = Flength (this), thisleni = XINT (thislen);
690
691 /* Between strings of the same kind, copy fast. */
692 if (STRINGP (this) && STRINGP (val)
693 && STRING_MULTIBYTE (this) == some_multibyte)
694 {
695 ptrdiff_t thislen_byte = SBYTES (this);
696
697 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
698 if (string_intervals (this))
699 {
700 textprops[num_textprops].argnum = argnum;
701 textprops[num_textprops].from = 0;
702 textprops[num_textprops++].to = toindex;
703 }
704 toindex_byte += thislen_byte;
705 toindex += thisleni;
706 }
707 /* Copy a single-byte string to a multibyte string. */
708 else if (STRINGP (this) && STRINGP (val))
709 {
710 if (string_intervals (this))
711 {
712 textprops[num_textprops].argnum = argnum;
713 textprops[num_textprops].from = 0;
714 textprops[num_textprops++].to = toindex;
715 }
716 toindex_byte += copy_text (SDATA (this),
717 SDATA (val) + toindex_byte,
718 SCHARS (this), 0, 1);
719 toindex += thisleni;
720 }
721 else
722 /* Copy element by element. */
723 while (1)
724 {
725 register Lisp_Object elt;
726
727 /* Fetch next element of `this' arg into `elt', or break if
728 `this' is exhausted. */
729 if (NILP (this)) break;
730 if (CONSP (this))
731 elt = XCAR (this), this = XCDR (this);
732 else if (thisindex >= thisleni)
733 break;
734 else if (STRINGP (this))
735 {
736 int c;
737 if (STRING_MULTIBYTE (this))
738 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
739 thisindex,
740 thisindex_byte);
741 else
742 {
743 c = SREF (this, thisindex); thisindex++;
744 if (some_multibyte && !ASCII_CHAR_P (c))
745 c = BYTE8_TO_CHAR (c);
746 }
747 XSETFASTINT (elt, c);
748 }
749 else if (BOOL_VECTOR_P (this))
750 {
751 elt = bool_vector_ref (this, thisindex);
752 thisindex++;
753 }
754 else
755 {
756 elt = AREF (this, thisindex);
757 thisindex++;
758 }
759
760 /* Store this element into the result. */
761 if (toindex < 0)
762 {
763 XSETCAR (tail, elt);
764 prev = tail;
765 tail = XCDR (tail);
766 }
767 else if (VECTORP (val))
768 {
769 ASET (val, toindex, elt);
770 toindex++;
771 }
772 else
773 {
774 int c;
775 CHECK_CHARACTER (elt);
776 c = XFASTINT (elt);
777 if (some_multibyte)
778 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
779 else
780 SSET (val, toindex_byte++, c);
781 toindex++;
782 }
783 }
784 }
785 if (!NILP (prev))
786 XSETCDR (prev, last_tail);
787
788 if (num_textprops > 0)
789 {
790 Lisp_Object props;
791 ptrdiff_t last_to_end = -1;
792
793 for (argnum = 0; argnum < num_textprops; argnum++)
794 {
795 this = args[textprops[argnum].argnum];
796 props = text_property_list (this,
797 make_number (0),
798 make_number (SCHARS (this)),
799 Qnil);
800 /* If successive arguments have properties, be sure that the
801 value of `composition' property be the copy. */
802 if (last_to_end == textprops[argnum].to)
803 make_composition_value_copy (props);
804 add_text_properties_from_list (val, props,
805 make_number (textprops[argnum].to));
806 last_to_end = textprops[argnum].to + SCHARS (this);
807 }
808 }
809
810 SAFE_FREE ();
811 return val;
812 }
813 \f
814 static Lisp_Object string_char_byte_cache_string;
815 static ptrdiff_t string_char_byte_cache_charpos;
816 static ptrdiff_t string_char_byte_cache_bytepos;
817
818 void
819 clear_string_char_byte_cache (void)
820 {
821 string_char_byte_cache_string = Qnil;
822 }
823
824 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
825
826 ptrdiff_t
827 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
828 {
829 ptrdiff_t i_byte;
830 ptrdiff_t best_below, best_below_byte;
831 ptrdiff_t best_above, best_above_byte;
832
833 best_below = best_below_byte = 0;
834 best_above = SCHARS (string);
835 best_above_byte = SBYTES (string);
836 if (best_above == best_above_byte)
837 return char_index;
838
839 if (EQ (string, string_char_byte_cache_string))
840 {
841 if (string_char_byte_cache_charpos < char_index)
842 {
843 best_below = string_char_byte_cache_charpos;
844 best_below_byte = string_char_byte_cache_bytepos;
845 }
846 else
847 {
848 best_above = string_char_byte_cache_charpos;
849 best_above_byte = string_char_byte_cache_bytepos;
850 }
851 }
852
853 if (char_index - best_below < best_above - char_index)
854 {
855 unsigned char *p = SDATA (string) + best_below_byte;
856
857 while (best_below < char_index)
858 {
859 p += BYTES_BY_CHAR_HEAD (*p);
860 best_below++;
861 }
862 i_byte = p - SDATA (string);
863 }
864 else
865 {
866 unsigned char *p = SDATA (string) + best_above_byte;
867
868 while (best_above > char_index)
869 {
870 p--;
871 while (!CHAR_HEAD_P (*p)) p--;
872 best_above--;
873 }
874 i_byte = p - SDATA (string);
875 }
876
877 string_char_byte_cache_bytepos = i_byte;
878 string_char_byte_cache_charpos = char_index;
879 string_char_byte_cache_string = string;
880
881 return i_byte;
882 }
883 \f
884 /* Return the character index corresponding to BYTE_INDEX in STRING. */
885
886 ptrdiff_t
887 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
888 {
889 ptrdiff_t i, i_byte;
890 ptrdiff_t best_below, best_below_byte;
891 ptrdiff_t best_above, best_above_byte;
892
893 best_below = best_below_byte = 0;
894 best_above = SCHARS (string);
895 best_above_byte = SBYTES (string);
896 if (best_above == best_above_byte)
897 return byte_index;
898
899 if (EQ (string, string_char_byte_cache_string))
900 {
901 if (string_char_byte_cache_bytepos < byte_index)
902 {
903 best_below = string_char_byte_cache_charpos;
904 best_below_byte = string_char_byte_cache_bytepos;
905 }
906 else
907 {
908 best_above = string_char_byte_cache_charpos;
909 best_above_byte = string_char_byte_cache_bytepos;
910 }
911 }
912
913 if (byte_index - best_below_byte < best_above_byte - byte_index)
914 {
915 unsigned char *p = SDATA (string) + best_below_byte;
916 unsigned char *pend = SDATA (string) + byte_index;
917
918 while (p < pend)
919 {
920 p += BYTES_BY_CHAR_HEAD (*p);
921 best_below++;
922 }
923 i = best_below;
924 i_byte = p - SDATA (string);
925 }
926 else
927 {
928 unsigned char *p = SDATA (string) + best_above_byte;
929 unsigned char *pbeg = SDATA (string) + byte_index;
930
931 while (p > pbeg)
932 {
933 p--;
934 while (!CHAR_HEAD_P (*p)) p--;
935 best_above--;
936 }
937 i = best_above;
938 i_byte = p - SDATA (string);
939 }
940
941 string_char_byte_cache_bytepos = i_byte;
942 string_char_byte_cache_charpos = i;
943 string_char_byte_cache_string = string;
944
945 return i;
946 }
947 \f
948 /* Convert STRING to a multibyte string. */
949
950 static Lisp_Object
951 string_make_multibyte (Lisp_Object string)
952 {
953 unsigned char *buf;
954 ptrdiff_t nbytes;
955 Lisp_Object ret;
956 USE_SAFE_ALLOCA;
957
958 if (STRING_MULTIBYTE (string))
959 return string;
960
961 nbytes = count_size_as_multibyte (SDATA (string),
962 SCHARS (string));
963 /* If all the chars are ASCII, they won't need any more bytes
964 once converted. In that case, we can return STRING itself. */
965 if (nbytes == SBYTES (string))
966 return string;
967
968 buf = SAFE_ALLOCA (nbytes);
969 copy_text (SDATA (string), buf, SBYTES (string),
970 0, 1);
971
972 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
973 SAFE_FREE ();
974
975 return ret;
976 }
977
978
979 /* Convert STRING (if unibyte) to a multibyte string without changing
980 the number of characters. Characters 0200 trough 0237 are
981 converted to eight-bit characters. */
982
983 Lisp_Object
984 string_to_multibyte (Lisp_Object string)
985 {
986 unsigned char *buf;
987 ptrdiff_t nbytes;
988 Lisp_Object ret;
989 USE_SAFE_ALLOCA;
990
991 if (STRING_MULTIBYTE (string))
992 return string;
993
994 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
995 /* If all the chars are ASCII, they won't need any more bytes once
996 converted. */
997 if (nbytes == SBYTES (string))
998 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
999
1000 buf = SAFE_ALLOCA (nbytes);
1001 memcpy (buf, SDATA (string), SBYTES (string));
1002 str_to_multibyte (buf, nbytes, SBYTES (string));
1003
1004 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1005 SAFE_FREE ();
1006
1007 return ret;
1008 }
1009
1010
1011 /* Convert STRING to a single-byte string. */
1012
1013 Lisp_Object
1014 string_make_unibyte (Lisp_Object string)
1015 {
1016 ptrdiff_t nchars;
1017 unsigned char *buf;
1018 Lisp_Object ret;
1019 USE_SAFE_ALLOCA;
1020
1021 if (! STRING_MULTIBYTE (string))
1022 return string;
1023
1024 nchars = SCHARS (string);
1025
1026 buf = SAFE_ALLOCA (nchars);
1027 copy_text (SDATA (string), buf, SBYTES (string),
1028 1, 0);
1029
1030 ret = make_unibyte_string ((char *) buf, nchars);
1031 SAFE_FREE ();
1032
1033 return ret;
1034 }
1035
1036 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1037 1, 1, 0,
1038 doc: /* Return the multibyte equivalent of STRING.
1039 If STRING is unibyte and contains non-ASCII characters, the function
1040 `unibyte-char-to-multibyte' is used to convert each unibyte character
1041 to a multibyte character. In this case, the returned string is a
1042 newly created string with no text properties. If STRING is multibyte
1043 or entirely ASCII, it is returned unchanged. In particular, when
1044 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1045 \(When the characters are all ASCII, Emacs primitives will treat the
1046 string the same way whether it is unibyte or multibyte.) */)
1047 (Lisp_Object string)
1048 {
1049 CHECK_STRING (string);
1050
1051 return string_make_multibyte (string);
1052 }
1053
1054 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1055 1, 1, 0,
1056 doc: /* Return the unibyte equivalent of STRING.
1057 Multibyte character codes are converted to unibyte according to
1058 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1059 If the lookup in the translation table fails, this function takes just
1060 the low 8 bits of each character. */)
1061 (Lisp_Object string)
1062 {
1063 CHECK_STRING (string);
1064
1065 return string_make_unibyte (string);
1066 }
1067
1068 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1069 1, 1, 0,
1070 doc: /* Return a unibyte string with the same individual bytes as STRING.
1071 If STRING is unibyte, the result is STRING itself.
1072 Otherwise it is a newly created string, with no text properties.
1073 If STRING is multibyte and contains a character of charset
1074 `eight-bit', it is converted to the corresponding single byte. */)
1075 (Lisp_Object string)
1076 {
1077 CHECK_STRING (string);
1078
1079 if (STRING_MULTIBYTE (string))
1080 {
1081 unsigned char *str = (unsigned char *) xlispstrdup (string);
1082 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1083
1084 string = make_unibyte_string ((char *) str, bytes);
1085 xfree (str);
1086 }
1087 return string;
1088 }
1089
1090 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1091 1, 1, 0,
1092 doc: /* Return a multibyte string with the same individual bytes as STRING.
1093 If STRING is multibyte, the result is STRING itself.
1094 Otherwise it is a newly created string, with no text properties.
1095
1096 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1097 part of a correct utf-8 sequence), it is converted to the corresponding
1098 multibyte character of charset `eight-bit'.
1099 See also `string-to-multibyte'.
1100
1101 Beware, this often doesn't really do what you think it does.
1102 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1103 If you're not sure, whether to use `string-as-multibyte' or
1104 `string-to-multibyte', use `string-to-multibyte'. */)
1105 (Lisp_Object string)
1106 {
1107 CHECK_STRING (string);
1108
1109 if (! STRING_MULTIBYTE (string))
1110 {
1111 Lisp_Object new_string;
1112 ptrdiff_t nchars, nbytes;
1113
1114 parse_str_as_multibyte (SDATA (string),
1115 SBYTES (string),
1116 &nchars, &nbytes);
1117 new_string = make_uninit_multibyte_string (nchars, nbytes);
1118 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1119 if (nbytes != SBYTES (string))
1120 str_as_multibyte (SDATA (new_string), nbytes,
1121 SBYTES (string), NULL);
1122 string = new_string;
1123 set_string_intervals (string, NULL);
1124 }
1125 return string;
1126 }
1127
1128 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1129 1, 1, 0,
1130 doc: /* Return a multibyte string with the same individual chars as STRING.
1131 If STRING is multibyte, the result is STRING itself.
1132 Otherwise it is a newly created string, with no text properties.
1133
1134 If STRING is unibyte and contains an 8-bit byte, it is converted to
1135 the corresponding multibyte character of charset `eight-bit'.
1136
1137 This differs from `string-as-multibyte' by converting each byte of a correct
1138 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1139 correct sequence. */)
1140 (Lisp_Object string)
1141 {
1142 CHECK_STRING (string);
1143
1144 return string_to_multibyte (string);
1145 }
1146
1147 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1148 1, 1, 0,
1149 doc: /* Return a unibyte string with the same individual chars as STRING.
1150 If STRING is unibyte, the result is STRING itself.
1151 Otherwise it is a newly created string, with no text properties,
1152 where each `eight-bit' character is converted to the corresponding byte.
1153 If STRING contains a non-ASCII, non-`eight-bit' character,
1154 an error is signaled. */)
1155 (Lisp_Object string)
1156 {
1157 CHECK_STRING (string);
1158
1159 if (STRING_MULTIBYTE (string))
1160 {
1161 ptrdiff_t chars = SCHARS (string);
1162 unsigned char *str = xmalloc (chars);
1163 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1164
1165 if (converted < chars)
1166 error ("Can't convert the %"pD"dth character to unibyte", converted);
1167 string = make_unibyte_string ((char *) str, chars);
1168 xfree (str);
1169 }
1170 return string;
1171 }
1172
1173 \f
1174 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1175 doc: /* Return a copy of ALIST.
1176 This is an alist which represents the same mapping from objects to objects,
1177 but does not share the alist structure with ALIST.
1178 The objects mapped (cars and cdrs of elements of the alist)
1179 are shared, however.
1180 Elements of ALIST that are not conses are also shared. */)
1181 (Lisp_Object alist)
1182 {
1183 register Lisp_Object tem;
1184
1185 CHECK_LIST (alist);
1186 if (NILP (alist))
1187 return alist;
1188 alist = concat (1, &alist, Lisp_Cons, 0);
1189 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1190 {
1191 register Lisp_Object car;
1192 car = XCAR (tem);
1193
1194 if (CONSP (car))
1195 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1196 }
1197 return alist;
1198 }
1199
1200 /* Check that ARRAY can have a valid subarray [FROM..TO),
1201 given that its size is SIZE.
1202 If FROM is nil, use 0; if TO is nil, use SIZE.
1203 Count negative values backwards from the end.
1204 Set *IFROM and *ITO to the two indexes used. */
1205
1206 void
1207 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1208 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1209 {
1210 EMACS_INT f, t;
1211
1212 if (INTEGERP (from))
1213 {
1214 f = XINT (from);
1215 if (f < 0)
1216 f += size;
1217 }
1218 else if (NILP (from))
1219 f = 0;
1220 else
1221 wrong_type_argument (Qintegerp, from);
1222
1223 if (INTEGERP (to))
1224 {
1225 t = XINT (to);
1226 if (t < 0)
1227 t += size;
1228 }
1229 else if (NILP (to))
1230 t = size;
1231 else
1232 wrong_type_argument (Qintegerp, to);
1233
1234 if (! (0 <= f && f <= t && t <= size))
1235 args_out_of_range_3 (array, from, to);
1236
1237 *ifrom = f;
1238 *ito = t;
1239 }
1240
1241 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1242 doc: /* Return a new string whose contents are a substring of STRING.
1243 The returned string consists of the characters between index FROM
1244 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1245 zero-indexed: 0 means the first character of STRING. Negative values
1246 are counted from the end of STRING. If TO is nil, the substring runs
1247 to the end of STRING.
1248
1249 The STRING argument may also be a vector. In that case, the return
1250 value is a new vector that contains the elements between index FROM
1251 \(inclusive) and index TO (exclusive) of that vector argument.
1252
1253 With one argument, just copy STRING (with properties, if any). */)
1254 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1255 {
1256 Lisp_Object res;
1257 ptrdiff_t size, ifrom, ito;
1258
1259 size = CHECK_VECTOR_OR_STRING (string);
1260 validate_subarray (string, from, to, size, &ifrom, &ito);
1261
1262 if (STRINGP (string))
1263 {
1264 ptrdiff_t from_byte
1265 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1266 ptrdiff_t to_byte
1267 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1268 res = make_specified_string (SSDATA (string) + from_byte,
1269 ito - ifrom, to_byte - from_byte,
1270 STRING_MULTIBYTE (string));
1271 copy_text_properties (make_number (ifrom), make_number (ito),
1272 string, make_number (0), res, Qnil);
1273 }
1274 else
1275 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1276
1277 return res;
1278 }
1279
1280
1281 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1282 doc: /* Return a substring of STRING, without text properties.
1283 It starts at index FROM and ends before TO.
1284 TO may be nil or omitted; then the substring runs to the end of STRING.
1285 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1286 If FROM or TO is negative, it counts from the end.
1287
1288 With one argument, just copy STRING without its properties. */)
1289 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1290 {
1291 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1292
1293 CHECK_STRING (string);
1294
1295 size = SCHARS (string);
1296 validate_subarray (string, from, to, size, &from_char, &to_char);
1297
1298 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1299 to_byte =
1300 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1301 return make_specified_string (SSDATA (string) + from_byte,
1302 to_char - from_char, to_byte - from_byte,
1303 STRING_MULTIBYTE (string));
1304 }
1305
1306 /* Extract a substring of STRING, giving start and end positions
1307 both in characters and in bytes. */
1308
1309 Lisp_Object
1310 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1311 ptrdiff_t to, ptrdiff_t to_byte)
1312 {
1313 Lisp_Object res;
1314 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1315
1316 if (!(0 <= from && from <= to && to <= size))
1317 args_out_of_range_3 (string, make_number (from), make_number (to));
1318
1319 if (STRINGP (string))
1320 {
1321 res = make_specified_string (SSDATA (string) + from_byte,
1322 to - from, to_byte - from_byte,
1323 STRING_MULTIBYTE (string));
1324 copy_text_properties (make_number (from), make_number (to),
1325 string, make_number (0), res, Qnil);
1326 }
1327 else
1328 res = Fvector (to - from, aref_addr (string, from));
1329
1330 return res;
1331 }
1332 \f
1333 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1334 doc: /* Take cdr N times on LIST, return the result. */)
1335 (Lisp_Object n, Lisp_Object list)
1336 {
1337 EMACS_INT i, num;
1338 CHECK_NUMBER (n);
1339 num = XINT (n);
1340 for (i = 0; i < num && !NILP (list); i++)
1341 {
1342 QUIT;
1343 CHECK_LIST_CONS (list, list);
1344 list = XCDR (list);
1345 }
1346 return list;
1347 }
1348
1349 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1350 doc: /* Return the Nth element of LIST.
1351 N counts from zero. If LIST is not that long, nil is returned. */)
1352 (Lisp_Object n, Lisp_Object list)
1353 {
1354 return Fcar (Fnthcdr (n, list));
1355 }
1356
1357 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1358 doc: /* Return element of SEQUENCE at index N. */)
1359 (register Lisp_Object sequence, Lisp_Object n)
1360 {
1361 CHECK_NUMBER (n);
1362 if (CONSP (sequence) || NILP (sequence))
1363 return Fcar (Fnthcdr (n, sequence));
1364
1365 /* Faref signals a "not array" error, so check here. */
1366 CHECK_ARRAY (sequence, Qsequencep);
1367 return Faref (sequence, n);
1368 }
1369
1370 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1371 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1372 The value is actually the tail of LIST whose car is ELT. */)
1373 (register Lisp_Object elt, Lisp_Object list)
1374 {
1375 register Lisp_Object tail;
1376 for (tail = list; CONSP (tail); tail = XCDR (tail))
1377 {
1378 register Lisp_Object tem;
1379 CHECK_LIST_CONS (tail, list);
1380 tem = XCAR (tail);
1381 if (! NILP (Fequal (elt, tem)))
1382 return tail;
1383 QUIT;
1384 }
1385 return Qnil;
1386 }
1387
1388 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1389 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1390 The value is actually the tail of LIST whose car is ELT. */)
1391 (register Lisp_Object elt, Lisp_Object list)
1392 {
1393 while (1)
1394 {
1395 if (!CONSP (list) || EQ (XCAR (list), elt))
1396 break;
1397
1398 list = XCDR (list);
1399 if (!CONSP (list) || EQ (XCAR (list), elt))
1400 break;
1401
1402 list = XCDR (list);
1403 if (!CONSP (list) || EQ (XCAR (list), elt))
1404 break;
1405
1406 list = XCDR (list);
1407 QUIT;
1408 }
1409
1410 CHECK_LIST (list);
1411 return list;
1412 }
1413
1414 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1415 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1416 The value is actually the tail of LIST whose car is ELT. */)
1417 (register Lisp_Object elt, Lisp_Object list)
1418 {
1419 register Lisp_Object tail;
1420
1421 if (!FLOATP (elt))
1422 return Fmemq (elt, list);
1423
1424 for (tail = list; CONSP (tail); tail = XCDR (tail))
1425 {
1426 register Lisp_Object tem;
1427 CHECK_LIST_CONS (tail, list);
1428 tem = XCAR (tail);
1429 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1430 return tail;
1431 QUIT;
1432 }
1433 return Qnil;
1434 }
1435
1436 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1437 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1438 The value is actually the first element of LIST whose car is KEY.
1439 Elements of LIST that are not conses are ignored. */)
1440 (Lisp_Object key, Lisp_Object list)
1441 {
1442 while (1)
1443 {
1444 if (!CONSP (list)
1445 || (CONSP (XCAR (list))
1446 && EQ (XCAR (XCAR (list)), key)))
1447 break;
1448
1449 list = XCDR (list);
1450 if (!CONSP (list)
1451 || (CONSP (XCAR (list))
1452 && EQ (XCAR (XCAR (list)), key)))
1453 break;
1454
1455 list = XCDR (list);
1456 if (!CONSP (list)
1457 || (CONSP (XCAR (list))
1458 && EQ (XCAR (XCAR (list)), key)))
1459 break;
1460
1461 list = XCDR (list);
1462 QUIT;
1463 }
1464
1465 return CAR (list);
1466 }
1467
1468 /* Like Fassq but never report an error and do not allow quits.
1469 Use only on lists known never to be circular. */
1470
1471 Lisp_Object
1472 assq_no_quit (Lisp_Object key, Lisp_Object list)
1473 {
1474 while (CONSP (list)
1475 && (!CONSP (XCAR (list))
1476 || !EQ (XCAR (XCAR (list)), key)))
1477 list = XCDR (list);
1478
1479 return CAR_SAFE (list);
1480 }
1481
1482 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1483 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1484 The value is actually the first element of LIST whose car equals KEY. */)
1485 (Lisp_Object key, Lisp_Object list)
1486 {
1487 Lisp_Object car;
1488
1489 while (1)
1490 {
1491 if (!CONSP (list)
1492 || (CONSP (XCAR (list))
1493 && (car = XCAR (XCAR (list)),
1494 EQ (car, key) || !NILP (Fequal (car, key)))))
1495 break;
1496
1497 list = XCDR (list);
1498 if (!CONSP (list)
1499 || (CONSP (XCAR (list))
1500 && (car = XCAR (XCAR (list)),
1501 EQ (car, key) || !NILP (Fequal (car, key)))))
1502 break;
1503
1504 list = XCDR (list);
1505 if (!CONSP (list)
1506 || (CONSP (XCAR (list))
1507 && (car = XCAR (XCAR (list)),
1508 EQ (car, key) || !NILP (Fequal (car, key)))))
1509 break;
1510
1511 list = XCDR (list);
1512 QUIT;
1513 }
1514
1515 return CAR (list);
1516 }
1517
1518 /* Like Fassoc but never report an error and do not allow quits.
1519 Use only on lists known never to be circular. */
1520
1521 Lisp_Object
1522 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1523 {
1524 while (CONSP (list)
1525 && (!CONSP (XCAR (list))
1526 || (!EQ (XCAR (XCAR (list)), key)
1527 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1528 list = XCDR (list);
1529
1530 return CONSP (list) ? XCAR (list) : Qnil;
1531 }
1532
1533 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1534 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1535 The value is actually the first element of LIST whose cdr is KEY. */)
1536 (register Lisp_Object key, Lisp_Object list)
1537 {
1538 while (1)
1539 {
1540 if (!CONSP (list)
1541 || (CONSP (XCAR (list))
1542 && EQ (XCDR (XCAR (list)), key)))
1543 break;
1544
1545 list = XCDR (list);
1546 if (!CONSP (list)
1547 || (CONSP (XCAR (list))
1548 && EQ (XCDR (XCAR (list)), key)))
1549 break;
1550
1551 list = XCDR (list);
1552 if (!CONSP (list)
1553 || (CONSP (XCAR (list))
1554 && EQ (XCDR (XCAR (list)), key)))
1555 break;
1556
1557 list = XCDR (list);
1558 QUIT;
1559 }
1560
1561 return CAR (list);
1562 }
1563
1564 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1565 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1566 The value is actually the first element of LIST whose cdr equals KEY. */)
1567 (Lisp_Object key, Lisp_Object list)
1568 {
1569 Lisp_Object cdr;
1570
1571 while (1)
1572 {
1573 if (!CONSP (list)
1574 || (CONSP (XCAR (list))
1575 && (cdr = XCDR (XCAR (list)),
1576 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1577 break;
1578
1579 list = XCDR (list);
1580 if (!CONSP (list)
1581 || (CONSP (XCAR (list))
1582 && (cdr = XCDR (XCAR (list)),
1583 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1584 break;
1585
1586 list = XCDR (list);
1587 if (!CONSP (list)
1588 || (CONSP (XCAR (list))
1589 && (cdr = XCDR (XCAR (list)),
1590 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1591 break;
1592
1593 list = XCDR (list);
1594 QUIT;
1595 }
1596
1597 return CAR (list);
1598 }
1599 \f
1600 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1601 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1602 More precisely, this function skips any members `eq' to ELT at the
1603 front of LIST, then removes members `eq' to ELT from the remaining
1604 sublist by modifying its list structure, then returns the resulting
1605 list.
1606
1607 Write `(setq foo (delq element foo))' to be sure of correctly changing
1608 the value of a list `foo'. */)
1609 (register Lisp_Object elt, Lisp_Object list)
1610 {
1611 Lisp_Object tail, tortoise, prev = Qnil;
1612 bool skip;
1613
1614 FOR_EACH_TAIL (tail, list, tortoise, skip)
1615 {
1616 Lisp_Object tem = XCAR (tail);
1617 if (EQ (elt, tem))
1618 {
1619 if (NILP (prev))
1620 list = XCDR (tail);
1621 else
1622 Fsetcdr (prev, XCDR (tail));
1623 }
1624 else
1625 prev = tail;
1626 }
1627 return list;
1628 }
1629
1630 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1631 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1632 SEQ must be a sequence (i.e. a list, a vector, or a string).
1633 The return value is a sequence of the same type.
1634
1635 If SEQ is a list, this behaves like `delq', except that it compares
1636 with `equal' instead of `eq'. In particular, it may remove elements
1637 by altering the list structure.
1638
1639 If SEQ is not a list, deletion is never performed destructively;
1640 instead this function creates and returns a new vector or string.
1641
1642 Write `(setq foo (delete element foo))' to be sure of correctly
1643 changing the value of a sequence `foo'. */)
1644 (Lisp_Object elt, Lisp_Object seq)
1645 {
1646 if (VECTORP (seq))
1647 {
1648 ptrdiff_t i, n;
1649
1650 for (i = n = 0; i < ASIZE (seq); ++i)
1651 if (NILP (Fequal (AREF (seq, i), elt)))
1652 ++n;
1653
1654 if (n != ASIZE (seq))
1655 {
1656 struct Lisp_Vector *p = allocate_vector (n);
1657
1658 for (i = n = 0; i < ASIZE (seq); ++i)
1659 if (NILP (Fequal (AREF (seq, i), elt)))
1660 p->contents[n++] = AREF (seq, i);
1661
1662 XSETVECTOR (seq, p);
1663 }
1664 }
1665 else if (STRINGP (seq))
1666 {
1667 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1668 int c;
1669
1670 for (i = nchars = nbytes = ibyte = 0;
1671 i < SCHARS (seq);
1672 ++i, ibyte += cbytes)
1673 {
1674 if (STRING_MULTIBYTE (seq))
1675 {
1676 c = STRING_CHAR (SDATA (seq) + ibyte);
1677 cbytes = CHAR_BYTES (c);
1678 }
1679 else
1680 {
1681 c = SREF (seq, i);
1682 cbytes = 1;
1683 }
1684
1685 if (!INTEGERP (elt) || c != XINT (elt))
1686 {
1687 ++nchars;
1688 nbytes += cbytes;
1689 }
1690 }
1691
1692 if (nchars != SCHARS (seq))
1693 {
1694 Lisp_Object tem;
1695
1696 tem = make_uninit_multibyte_string (nchars, nbytes);
1697 if (!STRING_MULTIBYTE (seq))
1698 STRING_SET_UNIBYTE (tem);
1699
1700 for (i = nchars = nbytes = ibyte = 0;
1701 i < SCHARS (seq);
1702 ++i, ibyte += cbytes)
1703 {
1704 if (STRING_MULTIBYTE (seq))
1705 {
1706 c = STRING_CHAR (SDATA (seq) + ibyte);
1707 cbytes = CHAR_BYTES (c);
1708 }
1709 else
1710 {
1711 c = SREF (seq, i);
1712 cbytes = 1;
1713 }
1714
1715 if (!INTEGERP (elt) || c != XINT (elt))
1716 {
1717 unsigned char *from = SDATA (seq) + ibyte;
1718 unsigned char *to = SDATA (tem) + nbytes;
1719 ptrdiff_t n;
1720
1721 ++nchars;
1722 nbytes += cbytes;
1723
1724 for (n = cbytes; n--; )
1725 *to++ = *from++;
1726 }
1727 }
1728
1729 seq = tem;
1730 }
1731 }
1732 else
1733 {
1734 Lisp_Object tail, prev;
1735
1736 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1737 {
1738 CHECK_LIST_CONS (tail, seq);
1739
1740 if (!NILP (Fequal (elt, XCAR (tail))))
1741 {
1742 if (NILP (prev))
1743 seq = XCDR (tail);
1744 else
1745 Fsetcdr (prev, XCDR (tail));
1746 }
1747 else
1748 prev = tail;
1749 QUIT;
1750 }
1751 }
1752
1753 return seq;
1754 }
1755
1756 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1757 doc: /* Reverse order of items in a list, vector or string SEQ.
1758 If SEQ is a list, it should be nil-terminated.
1759 This function may destructively modify SEQ to produce the value. */)
1760 (Lisp_Object seq)
1761 {
1762 if (NILP (seq))
1763 return seq;
1764 else if (STRINGP (seq))
1765 return Freverse (seq);
1766 else if (CONSP (seq))
1767 {
1768 Lisp_Object prev, tail, next;
1769
1770 for (prev = Qnil, tail = seq; !NILP (tail); tail = next)
1771 {
1772 QUIT;
1773 CHECK_LIST_CONS (tail, tail);
1774 next = XCDR (tail);
1775 Fsetcdr (tail, prev);
1776 prev = tail;
1777 }
1778 seq = prev;
1779 }
1780 else if (VECTORP (seq))
1781 {
1782 ptrdiff_t i, size = ASIZE (seq);
1783
1784 for (i = 0; i < size / 2; i++)
1785 {
1786 Lisp_Object tem = AREF (seq, i);
1787 ASET (seq, i, AREF (seq, size - i - 1));
1788 ASET (seq, size - i - 1, tem);
1789 }
1790 }
1791 else if (BOOL_VECTOR_P (seq))
1792 {
1793 ptrdiff_t i, size = bool_vector_size (seq);
1794
1795 for (i = 0; i < size / 2; i++)
1796 {
1797 bool tem = bool_vector_bitref (seq, i);
1798 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1799 bool_vector_set (seq, size - i - 1, tem);
1800 }
1801 }
1802 else
1803 wrong_type_argument (Qarrayp, seq);
1804 return seq;
1805 }
1806
1807 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1808 doc: /* Return the reversed copy of list, vector, or string SEQ.
1809 See also the function `nreverse', which is used more often. */)
1810 (Lisp_Object seq)
1811 {
1812 Lisp_Object new;
1813
1814 if (NILP (seq))
1815 return Qnil;
1816 else if (CONSP (seq))
1817 {
1818 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1819 {
1820 QUIT;
1821 new = Fcons (XCAR (seq), new);
1822 }
1823 CHECK_LIST_END (seq, seq);
1824 }
1825 else if (VECTORP (seq))
1826 {
1827 ptrdiff_t i, size = ASIZE (seq);
1828
1829 new = make_uninit_vector (size);
1830 for (i = 0; i < size; i++)
1831 ASET (new, i, AREF (seq, size - i - 1));
1832 }
1833 else if (BOOL_VECTOR_P (seq))
1834 {
1835 ptrdiff_t i;
1836 EMACS_INT nbits = bool_vector_size (seq);
1837
1838 new = make_uninit_bool_vector (nbits);
1839 for (i = 0; i < nbits; i++)
1840 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1841 }
1842 else if (STRINGP (seq))
1843 {
1844 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1845
1846 if (size == bytes)
1847 {
1848 ptrdiff_t i;
1849
1850 new = make_uninit_string (size);
1851 for (i = 0; i < size; i++)
1852 SSET (new, i, SREF (seq, size - i - 1));
1853 }
1854 else
1855 {
1856 unsigned char *p, *q;
1857
1858 new = make_uninit_multibyte_string (size, bytes);
1859 p = SDATA (seq), q = SDATA (new) + bytes;
1860 while (q > SDATA (new))
1861 {
1862 int ch, len;
1863
1864 ch = STRING_CHAR_AND_LENGTH (p, len);
1865 p += len, q -= len;
1866 CHAR_STRING (ch, q);
1867 }
1868 }
1869 }
1870 else
1871 wrong_type_argument (Qsequencep, seq);
1872 return new;
1873 }
1874
1875 /* Sort LIST using PREDICATE, preserving original order of elements
1876 considered as equal. */
1877
1878 static Lisp_Object
1879 sort_list (Lisp_Object list, Lisp_Object predicate)
1880 {
1881 Lisp_Object front, back;
1882 register Lisp_Object len, tem;
1883 struct gcpro gcpro1, gcpro2;
1884 EMACS_INT length;
1885
1886 front = list;
1887 len = Flength (list);
1888 length = XINT (len);
1889 if (length < 2)
1890 return list;
1891
1892 XSETINT (len, (length / 2) - 1);
1893 tem = Fnthcdr (len, list);
1894 back = Fcdr (tem);
1895 Fsetcdr (tem, Qnil);
1896
1897 GCPRO2 (front, back);
1898 front = Fsort (front, predicate);
1899 back = Fsort (back, predicate);
1900 UNGCPRO;
1901 return merge (front, back, predicate);
1902 }
1903
1904 /* Using PRED to compare, return whether A and B are in order.
1905 Compare stably when A appeared before B in the input. */
1906 static bool
1907 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1908 {
1909 return NILP (call2 (pred, b, a));
1910 }
1911
1912 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1913 into DEST. Argument arrays must be nonempty and must not overlap,
1914 except that B might be the last part of DEST. */
1915 static void
1916 merge_vectors (Lisp_Object pred,
1917 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1918 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1919 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1920 {
1921 eassume (0 < alen && 0 < blen);
1922 Lisp_Object const *alim = a + alen;
1923 Lisp_Object const *blim = b + blen;
1924
1925 while (true)
1926 {
1927 if (inorder (pred, a[0], b[0]))
1928 {
1929 *dest++ = *a++;
1930 if (a == alim)
1931 {
1932 if (dest != b)
1933 memcpy (dest, b, (blim - b) * sizeof *dest);
1934 return;
1935 }
1936 }
1937 else
1938 {
1939 *dest++ = *b++;
1940 if (b == blim)
1941 {
1942 memcpy (dest, a, (alim - a) * sizeof *dest);
1943 return;
1944 }
1945 }
1946 }
1947 }
1948
1949 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1950 temporary storage. LEN must be at least 2. */
1951 static void
1952 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1953 Lisp_Object vec[restrict VLA_ELEMS (len)],
1954 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1955 {
1956 eassume (2 <= len);
1957 ptrdiff_t halflen = len >> 1;
1958 sort_vector_copy (pred, halflen, vec, tmp);
1959 if (1 < len - halflen)
1960 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1961 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1962 }
1963
1964 /* Using PRED to compare, sort from LEN-length SRC into DST.
1965 Len must be positive. */
1966 static void
1967 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1968 Lisp_Object src[restrict VLA_ELEMS (len)],
1969 Lisp_Object dest[restrict VLA_ELEMS (len)])
1970 {
1971 eassume (0 < len);
1972 ptrdiff_t halflen = len >> 1;
1973 if (halflen < 1)
1974 dest[0] = src[0];
1975 else
1976 {
1977 if (1 < halflen)
1978 sort_vector_inplace (pred, halflen, src, dest);
1979 if (1 < len - halflen)
1980 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
1981 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
1982 }
1983 }
1984
1985 /* Sort VECTOR in place using PREDICATE, preserving original order of
1986 elements considered as equal. */
1987
1988 static void
1989 sort_vector (Lisp_Object vector, Lisp_Object predicate)
1990 {
1991 ptrdiff_t len = ASIZE (vector);
1992 if (len < 2)
1993 return;
1994 ptrdiff_t halflen = len >> 1;
1995 Lisp_Object *tmp;
1996 struct gcpro gcpro1, gcpro2;
1997 GCPRO2 (vector, predicate);
1998 USE_SAFE_ALLOCA;
1999 SAFE_ALLOCA_LISP (tmp, halflen);
2000 for (ptrdiff_t i = 0; i < halflen; i++)
2001 tmp[i] = make_number (0);
2002 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
2003 SAFE_FREE ();
2004 UNGCPRO;
2005 }
2006
2007 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
2008 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
2009 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
2010 modified by side effects. PREDICATE is called with two elements of
2011 SEQ, and should return non-nil if the first element should sort before
2012 the second. */)
2013 (Lisp_Object seq, Lisp_Object predicate)
2014 {
2015 if (CONSP (seq))
2016 seq = sort_list (seq, predicate);
2017 else if (VECTORP (seq))
2018 sort_vector (seq, predicate);
2019 else if (!NILP (seq))
2020 wrong_type_argument (Qsequencep, seq);
2021 return seq;
2022 }
2023
2024 Lisp_Object
2025 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
2026 {
2027 Lisp_Object value;
2028 register Lisp_Object tail;
2029 Lisp_Object tem;
2030 register Lisp_Object l1, l2;
2031 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2032
2033 l1 = org_l1;
2034 l2 = org_l2;
2035 tail = Qnil;
2036 value = Qnil;
2037
2038 /* It is sufficient to protect org_l1 and org_l2.
2039 When l1 and l2 are updated, we copy the new values
2040 back into the org_ vars. */
2041 GCPRO4 (org_l1, org_l2, pred, value);
2042
2043 while (1)
2044 {
2045 if (NILP (l1))
2046 {
2047 UNGCPRO;
2048 if (NILP (tail))
2049 return l2;
2050 Fsetcdr (tail, l2);
2051 return value;
2052 }
2053 if (NILP (l2))
2054 {
2055 UNGCPRO;
2056 if (NILP (tail))
2057 return l1;
2058 Fsetcdr (tail, l1);
2059 return value;
2060 }
2061 if (inorder (pred, Fcar (l1), Fcar (l2)))
2062 {
2063 tem = l1;
2064 l1 = Fcdr (l1);
2065 org_l1 = l1;
2066 }
2067 else
2068 {
2069 tem = l2;
2070 l2 = Fcdr (l2);
2071 org_l2 = l2;
2072 }
2073 if (NILP (tail))
2074 value = tem;
2075 else
2076 Fsetcdr (tail, tem);
2077 tail = tem;
2078 }
2079 }
2080
2081 \f
2082 /* This does not check for quits. That is safe since it must terminate. */
2083
2084 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2085 doc: /* Extract a value from a property list.
2086 PLIST is a property list, which is a list of the form
2087 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2088 corresponding to the given PROP, or nil if PROP is not one of the
2089 properties on the list. This function never signals an error. */)
2090 (Lisp_Object plist, Lisp_Object prop)
2091 {
2092 Lisp_Object tail, halftail;
2093
2094 /* halftail is used to detect circular lists. */
2095 tail = halftail = plist;
2096 while (CONSP (tail) && CONSP (XCDR (tail)))
2097 {
2098 if (EQ (prop, XCAR (tail)))
2099 return XCAR (XCDR (tail));
2100
2101 tail = XCDR (XCDR (tail));
2102 halftail = XCDR (halftail);
2103 if (EQ (tail, halftail))
2104 break;
2105 }
2106
2107 return Qnil;
2108 }
2109
2110 DEFUN ("get", Fget, Sget, 2, 2, 0,
2111 doc: /* Return the value of SYMBOL's PROPNAME property.
2112 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2113 (Lisp_Object symbol, Lisp_Object propname)
2114 {
2115 CHECK_SYMBOL (symbol);
2116 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2117 }
2118
2119 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2120 doc: /* Change value in PLIST of PROP to VAL.
2121 PLIST is a property list, which is a list of the form
2122 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2123 If PROP is already a property on the list, its value is set to VAL,
2124 otherwise the new PROP VAL pair is added. The new plist is returned;
2125 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2126 The PLIST is modified by side effects. */)
2127 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2128 {
2129 register Lisp_Object tail, prev;
2130 Lisp_Object newcell;
2131 prev = Qnil;
2132 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2133 tail = XCDR (XCDR (tail)))
2134 {
2135 if (EQ (prop, XCAR (tail)))
2136 {
2137 Fsetcar (XCDR (tail), val);
2138 return plist;
2139 }
2140
2141 prev = tail;
2142 QUIT;
2143 }
2144 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2145 if (NILP (prev))
2146 return newcell;
2147 else
2148 Fsetcdr (XCDR (prev), newcell);
2149 return plist;
2150 }
2151
2152 DEFUN ("put", Fput, Sput, 3, 3, 0,
2153 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2154 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2155 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2156 {
2157 CHECK_SYMBOL (symbol);
2158 set_symbol_plist
2159 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2160 return value;
2161 }
2162 \f
2163 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2164 doc: /* Extract a value from a property list, comparing with `equal'.
2165 PLIST is a property list, which is a list of the form
2166 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2167 corresponding to the given PROP, or nil if PROP is not
2168 one of the properties on the list. */)
2169 (Lisp_Object plist, Lisp_Object prop)
2170 {
2171 Lisp_Object tail;
2172
2173 for (tail = plist;
2174 CONSP (tail) && CONSP (XCDR (tail));
2175 tail = XCDR (XCDR (tail)))
2176 {
2177 if (! NILP (Fequal (prop, XCAR (tail))))
2178 return XCAR (XCDR (tail));
2179
2180 QUIT;
2181 }
2182
2183 CHECK_LIST_END (tail, prop);
2184
2185 return Qnil;
2186 }
2187
2188 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2189 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2190 PLIST is a property list, which is a list of the form
2191 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2192 If PROP is already a property on the list, its value is set to VAL,
2193 otherwise the new PROP VAL pair is added. The new plist is returned;
2194 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2195 The PLIST is modified by side effects. */)
2196 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2197 {
2198 register Lisp_Object tail, prev;
2199 Lisp_Object newcell;
2200 prev = Qnil;
2201 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2202 tail = XCDR (XCDR (tail)))
2203 {
2204 if (! NILP (Fequal (prop, XCAR (tail))))
2205 {
2206 Fsetcar (XCDR (tail), val);
2207 return plist;
2208 }
2209
2210 prev = tail;
2211 QUIT;
2212 }
2213 newcell = list2 (prop, val);
2214 if (NILP (prev))
2215 return newcell;
2216 else
2217 Fsetcdr (XCDR (prev), newcell);
2218 return plist;
2219 }
2220 \f
2221 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2222 doc: /* Return t if the two args are the same Lisp object.
2223 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2224 (Lisp_Object obj1, Lisp_Object obj2)
2225 {
2226 if (FLOATP (obj1))
2227 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2228 else
2229 return EQ (obj1, obj2) ? Qt : Qnil;
2230 }
2231
2232 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2233 doc: /* Return t if two Lisp objects have similar structure and contents.
2234 They must have the same data type.
2235 Conses are compared by comparing the cars and the cdrs.
2236 Vectors and strings are compared element by element.
2237 Numbers are compared by value, but integers cannot equal floats.
2238 (Use `=' if you want integers and floats to be able to be equal.)
2239 Symbols must match exactly. */)
2240 (register Lisp_Object o1, Lisp_Object o2)
2241 {
2242 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2243 }
2244
2245 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2246 doc: /* Return t if two Lisp objects have similar structure and contents.
2247 This is like `equal' except that it compares the text properties
2248 of strings. (`equal' ignores text properties.) */)
2249 (register Lisp_Object o1, Lisp_Object o2)
2250 {
2251 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2252 }
2253
2254 /* DEPTH is current depth of recursion. Signal an error if it
2255 gets too deep.
2256 PROPS means compare string text properties too. */
2257
2258 static bool
2259 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2260 Lisp_Object ht)
2261 {
2262 if (depth > 10)
2263 {
2264 if (depth > 200)
2265 error ("Stack overflow in equal");
2266 if (NILP (ht))
2267 {
2268 Lisp_Object args[2];
2269 args[0] = QCtest;
2270 args[1] = Qeq;
2271 ht = Fmake_hash_table (2, args);
2272 }
2273 switch (XTYPE (o1))
2274 {
2275 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2276 {
2277 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2278 EMACS_UINT hash;
2279 ptrdiff_t i = hash_lookup (h, o1, &hash);
2280 if (i >= 0)
2281 { /* `o1' was seen already. */
2282 Lisp_Object o2s = HASH_VALUE (h, i);
2283 if (!NILP (Fmemq (o2, o2s)))
2284 return 1;
2285 else
2286 set_hash_value_slot (h, i, Fcons (o2, o2s));
2287 }
2288 else
2289 hash_put (h, o1, Fcons (o2, Qnil), hash);
2290 }
2291 default: ;
2292 }
2293 }
2294
2295 tail_recurse:
2296 QUIT;
2297 if (EQ (o1, o2))
2298 return 1;
2299 if (XTYPE (o1) != XTYPE (o2))
2300 return 0;
2301
2302 switch (XTYPE (o1))
2303 {
2304 case Lisp_Float:
2305 {
2306 double d1, d2;
2307
2308 d1 = extract_float (o1);
2309 d2 = extract_float (o2);
2310 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2311 though they are not =. */
2312 return d1 == d2 || (d1 != d1 && d2 != d2);
2313 }
2314
2315 case Lisp_Cons:
2316 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2317 return 0;
2318 o1 = XCDR (o1);
2319 o2 = XCDR (o2);
2320 /* FIXME: This inf-loops in a circular list! */
2321 goto tail_recurse;
2322
2323 case Lisp_Misc:
2324 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2325 return 0;
2326 if (OVERLAYP (o1))
2327 {
2328 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2329 depth + 1, props, ht)
2330 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2331 depth + 1, props, ht))
2332 return 0;
2333 o1 = XOVERLAY (o1)->plist;
2334 o2 = XOVERLAY (o2)->plist;
2335 goto tail_recurse;
2336 }
2337 if (MARKERP (o1))
2338 {
2339 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2340 && (XMARKER (o1)->buffer == 0
2341 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2342 }
2343 break;
2344
2345 case Lisp_Vectorlike:
2346 {
2347 register int i;
2348 ptrdiff_t size = ASIZE (o1);
2349 /* Pseudovectors have the type encoded in the size field, so this test
2350 actually checks that the objects have the same type as well as the
2351 same size. */
2352 if (ASIZE (o2) != size)
2353 return 0;
2354 /* Boolvectors are compared much like strings. */
2355 if (BOOL_VECTOR_P (o1))
2356 {
2357 EMACS_INT size = bool_vector_size (o1);
2358 if (size != bool_vector_size (o2))
2359 return 0;
2360 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2361 bool_vector_bytes (size)))
2362 return 0;
2363 return 1;
2364 }
2365 if (WINDOW_CONFIGURATIONP (o1))
2366 return compare_window_configurations (o1, o2, 0);
2367
2368 /* Aside from them, only true vectors, char-tables, compiled
2369 functions, and fonts (font-spec, font-entity, font-object)
2370 are sensible to compare, so eliminate the others now. */
2371 if (size & PSEUDOVECTOR_FLAG)
2372 {
2373 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2374 < PVEC_COMPILED)
2375 return 0;
2376 size &= PSEUDOVECTOR_SIZE_MASK;
2377 }
2378 for (i = 0; i < size; i++)
2379 {
2380 Lisp_Object v1, v2;
2381 v1 = AREF (o1, i);
2382 v2 = AREF (o2, i);
2383 if (!internal_equal (v1, v2, depth + 1, props, ht))
2384 return 0;
2385 }
2386 return 1;
2387 }
2388 break;
2389
2390 case Lisp_String:
2391 if (SCHARS (o1) != SCHARS (o2))
2392 return 0;
2393 if (SBYTES (o1) != SBYTES (o2))
2394 return 0;
2395 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2396 return 0;
2397 if (props && !compare_string_intervals (o1, o2))
2398 return 0;
2399 return 1;
2400
2401 default:
2402 break;
2403 }
2404
2405 return 0;
2406 }
2407 \f
2408
2409 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2410 doc: /* Store each element of ARRAY with ITEM.
2411 ARRAY is a vector, string, char-table, or bool-vector. */)
2412 (Lisp_Object array, Lisp_Object item)
2413 {
2414 register ptrdiff_t size, idx;
2415
2416 if (VECTORP (array))
2417 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2418 ASET (array, idx, item);
2419 else if (CHAR_TABLE_P (array))
2420 {
2421 int i;
2422
2423 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2424 set_char_table_contents (array, i, item);
2425 set_char_table_defalt (array, item);
2426 }
2427 else if (STRINGP (array))
2428 {
2429 register unsigned char *p = SDATA (array);
2430 int charval;
2431 CHECK_CHARACTER (item);
2432 charval = XFASTINT (item);
2433 size = SCHARS (array);
2434 if (STRING_MULTIBYTE (array))
2435 {
2436 unsigned char str[MAX_MULTIBYTE_LENGTH];
2437 int len = CHAR_STRING (charval, str);
2438 ptrdiff_t size_byte = SBYTES (array);
2439
2440 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2441 || SCHARS (array) * len != size_byte)
2442 error ("Attempt to change byte length of a string");
2443 for (idx = 0; idx < size_byte; idx++)
2444 *p++ = str[idx % len];
2445 }
2446 else
2447 for (idx = 0; idx < size; idx++)
2448 p[idx] = charval;
2449 }
2450 else if (BOOL_VECTOR_P (array))
2451 return bool_vector_fill (array, item);
2452 else
2453 wrong_type_argument (Qarrayp, array);
2454 return array;
2455 }
2456
2457 DEFUN ("clear-string", Fclear_string, Sclear_string,
2458 1, 1, 0,
2459 doc: /* Clear the contents of STRING.
2460 This makes STRING unibyte and may change its length. */)
2461 (Lisp_Object string)
2462 {
2463 ptrdiff_t len;
2464 CHECK_STRING (string);
2465 len = SBYTES (string);
2466 memset (SDATA (string), 0, len);
2467 STRING_SET_CHARS (string, len);
2468 STRING_SET_UNIBYTE (string);
2469 return Qnil;
2470 }
2471 \f
2472 /* ARGSUSED */
2473 Lisp_Object
2474 nconc2 (Lisp_Object s1, Lisp_Object s2)
2475 {
2476 Lisp_Object args[2];
2477 args[0] = s1;
2478 args[1] = s2;
2479 return Fnconc (2, args);
2480 }
2481
2482 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2483 doc: /* Concatenate any number of lists by altering them.
2484 Only the last argument is not altered, and need not be a list.
2485 usage: (nconc &rest LISTS) */)
2486 (ptrdiff_t nargs, Lisp_Object *args)
2487 {
2488 ptrdiff_t argnum;
2489 register Lisp_Object tail, tem, val;
2490
2491 val = tail = Qnil;
2492
2493 for (argnum = 0; argnum < nargs; argnum++)
2494 {
2495 tem = args[argnum];
2496 if (NILP (tem)) continue;
2497
2498 if (NILP (val))
2499 val = tem;
2500
2501 if (argnum + 1 == nargs) break;
2502
2503 CHECK_LIST_CONS (tem, tem);
2504
2505 while (CONSP (tem))
2506 {
2507 tail = tem;
2508 tem = XCDR (tail);
2509 QUIT;
2510 }
2511
2512 tem = args[argnum + 1];
2513 Fsetcdr (tail, tem);
2514 if (NILP (tem))
2515 args[argnum + 1] = tail;
2516 }
2517
2518 return val;
2519 }
2520 \f
2521 /* This is the guts of all mapping functions.
2522 Apply FN to each element of SEQ, one by one,
2523 storing the results into elements of VALS, a C vector of Lisp_Objects.
2524 LENI is the length of VALS, which should also be the length of SEQ. */
2525
2526 static void
2527 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2528 {
2529 register Lisp_Object tail;
2530 Lisp_Object dummy;
2531 register EMACS_INT i;
2532 struct gcpro gcpro1, gcpro2, gcpro3;
2533
2534 if (vals)
2535 {
2536 /* Don't let vals contain any garbage when GC happens. */
2537 for (i = 0; i < leni; i++)
2538 vals[i] = Qnil;
2539
2540 GCPRO3 (dummy, fn, seq);
2541 gcpro1.var = vals;
2542 gcpro1.nvars = leni;
2543 }
2544 else
2545 GCPRO2 (fn, seq);
2546 /* We need not explicitly protect `tail' because it is used only on lists, and
2547 1) lists are not relocated and 2) the list is marked via `seq' so will not
2548 be freed */
2549
2550 if (VECTORP (seq) || COMPILEDP (seq))
2551 {
2552 for (i = 0; i < leni; i++)
2553 {
2554 dummy = call1 (fn, AREF (seq, i));
2555 if (vals)
2556 vals[i] = dummy;
2557 }
2558 }
2559 else if (BOOL_VECTOR_P (seq))
2560 {
2561 for (i = 0; i < leni; i++)
2562 {
2563 dummy = call1 (fn, bool_vector_ref (seq, i));
2564 if (vals)
2565 vals[i] = dummy;
2566 }
2567 }
2568 else if (STRINGP (seq))
2569 {
2570 ptrdiff_t i_byte;
2571
2572 for (i = 0, i_byte = 0; i < leni;)
2573 {
2574 int c;
2575 ptrdiff_t i_before = i;
2576
2577 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2578 XSETFASTINT (dummy, c);
2579 dummy = call1 (fn, dummy);
2580 if (vals)
2581 vals[i_before] = dummy;
2582 }
2583 }
2584 else /* Must be a list, since Flength did not get an error */
2585 {
2586 tail = seq;
2587 for (i = 0; i < leni && CONSP (tail); i++)
2588 {
2589 dummy = call1 (fn, XCAR (tail));
2590 if (vals)
2591 vals[i] = dummy;
2592 tail = XCDR (tail);
2593 }
2594 }
2595
2596 UNGCPRO;
2597 }
2598
2599 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2600 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2601 In between each pair of results, stick in SEPARATOR. Thus, " " as
2602 SEPARATOR results in spaces between the values returned by FUNCTION.
2603 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2604 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2605 {
2606 Lisp_Object len;
2607 register EMACS_INT leni;
2608 EMACS_INT nargs;
2609 ptrdiff_t i;
2610 register Lisp_Object *args;
2611 struct gcpro gcpro1;
2612 Lisp_Object ret;
2613 USE_SAFE_ALLOCA;
2614
2615 len = Flength (sequence);
2616 if (CHAR_TABLE_P (sequence))
2617 wrong_type_argument (Qlistp, sequence);
2618 leni = XINT (len);
2619 nargs = leni + leni - 1;
2620 if (nargs < 0) return empty_unibyte_string;
2621
2622 SAFE_ALLOCA_LISP (args, nargs);
2623
2624 GCPRO1 (separator);
2625 mapcar1 (leni, args, function, sequence);
2626 UNGCPRO;
2627
2628 for (i = leni - 1; i > 0; i--)
2629 args[i + i] = args[i];
2630
2631 for (i = 1; i < nargs; i += 2)
2632 args[i] = separator;
2633
2634 ret = Fconcat (nargs, args);
2635 SAFE_FREE ();
2636
2637 return ret;
2638 }
2639
2640 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2641 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2642 The result is a list just as long as SEQUENCE.
2643 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2644 (Lisp_Object function, Lisp_Object sequence)
2645 {
2646 register Lisp_Object len;
2647 register EMACS_INT leni;
2648 register Lisp_Object *args;
2649 Lisp_Object ret;
2650 USE_SAFE_ALLOCA;
2651
2652 len = Flength (sequence);
2653 if (CHAR_TABLE_P (sequence))
2654 wrong_type_argument (Qlistp, sequence);
2655 leni = XFASTINT (len);
2656
2657 SAFE_ALLOCA_LISP (args, leni);
2658
2659 mapcar1 (leni, args, function, sequence);
2660
2661 ret = Flist (leni, args);
2662 SAFE_FREE ();
2663
2664 return ret;
2665 }
2666
2667 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2668 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2669 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2670 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2671 (Lisp_Object function, Lisp_Object sequence)
2672 {
2673 register EMACS_INT leni;
2674
2675 leni = XFASTINT (Flength (sequence));
2676 if (CHAR_TABLE_P (sequence))
2677 wrong_type_argument (Qlistp, sequence);
2678 mapcar1 (leni, 0, function, sequence);
2679
2680 return sequence;
2681 }
2682 \f
2683 /* This is how C code calls `yes-or-no-p' and allows the user
2684 to redefined it.
2685
2686 Anything that calls this function must protect from GC! */
2687
2688 Lisp_Object
2689 do_yes_or_no_p (Lisp_Object prompt)
2690 {
2691 return call1 (intern ("yes-or-no-p"), prompt);
2692 }
2693
2694 /* Anything that calls this function must protect from GC! */
2695
2696 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2697 doc: /* Ask user a yes-or-no question.
2698 Return t if answer is yes, and nil if the answer is no.
2699 PROMPT is the string to display to ask the question. It should end in
2700 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2701
2702 The user must confirm the answer with RET, and can edit it until it
2703 has been confirmed.
2704
2705 If dialog boxes are supported, a dialog box will be used
2706 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2707 (Lisp_Object prompt)
2708 {
2709 Lisp_Object ans;
2710 struct gcpro gcpro1;
2711
2712 CHECK_STRING (prompt);
2713
2714 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2715 && use_dialog_box)
2716 {
2717 Lisp_Object pane, menu, obj;
2718 redisplay_preserve_echo_area (4);
2719 pane = list2 (Fcons (build_string ("Yes"), Qt),
2720 Fcons (build_string ("No"), Qnil));
2721 GCPRO1 (pane);
2722 menu = Fcons (prompt, pane);
2723 obj = Fx_popup_dialog (Qt, menu, Qnil);
2724 UNGCPRO;
2725 return obj;
2726 }
2727
2728 AUTO_STRING (yes_or_no, "(yes or no) ");
2729 prompt = Fconcat (2, (Lisp_Object []) {prompt, yes_or_no});
2730 GCPRO1 (prompt);
2731
2732 while (1)
2733 {
2734 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2735 Qyes_or_no_p_history, Qnil,
2736 Qnil));
2737 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2738 {
2739 UNGCPRO;
2740 return Qt;
2741 }
2742 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2743 {
2744 UNGCPRO;
2745 return Qnil;
2746 }
2747
2748 Fding (Qnil);
2749 Fdiscard_input ();
2750 message1 ("Please answer yes or no.");
2751 Fsleep_for (make_number (2), Qnil);
2752 }
2753 }
2754 \f
2755 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2756 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2757
2758 Each of the three load averages is multiplied by 100, then converted
2759 to integer.
2760
2761 When USE-FLOATS is non-nil, floats will be used instead of integers.
2762 These floats are not multiplied by 100.
2763
2764 If the 5-minute or 15-minute load averages are not available, return a
2765 shortened list, containing only those averages which are available.
2766
2767 An error is thrown if the load average can't be obtained. In some
2768 cases making it work would require Emacs being installed setuid or
2769 setgid so that it can read kernel information, and that usually isn't
2770 advisable. */)
2771 (Lisp_Object use_floats)
2772 {
2773 double load_ave[3];
2774 int loads = getloadavg (load_ave, 3);
2775 Lisp_Object ret = Qnil;
2776
2777 if (loads < 0)
2778 error ("load-average not implemented for this operating system");
2779
2780 while (loads-- > 0)
2781 {
2782 Lisp_Object load = (NILP (use_floats)
2783 ? make_number (100.0 * load_ave[loads])
2784 : make_float (load_ave[loads]));
2785 ret = Fcons (load, ret);
2786 }
2787
2788 return ret;
2789 }
2790 \f
2791 static Lisp_Object Qsubfeatures;
2792
2793 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2794 doc: /* Return t if FEATURE is present in this Emacs.
2795
2796 Use this to conditionalize execution of lisp code based on the
2797 presence or absence of Emacs or environment extensions.
2798 Use `provide' to declare that a feature is available. This function
2799 looks at the value of the variable `features'. The optional argument
2800 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2801 (Lisp_Object feature, Lisp_Object subfeature)
2802 {
2803 register Lisp_Object tem;
2804 CHECK_SYMBOL (feature);
2805 tem = Fmemq (feature, Vfeatures);
2806 if (!NILP (tem) && !NILP (subfeature))
2807 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2808 return (NILP (tem)) ? Qnil : Qt;
2809 }
2810
2811 static Lisp_Object Qfuncall;
2812
2813 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2814 doc: /* Announce that FEATURE is a feature of the current Emacs.
2815 The optional argument SUBFEATURES should be a list of symbols listing
2816 particular subfeatures supported in this version of FEATURE. */)
2817 (Lisp_Object feature, Lisp_Object subfeatures)
2818 {
2819 register Lisp_Object tem;
2820 CHECK_SYMBOL (feature);
2821 CHECK_LIST (subfeatures);
2822 if (!NILP (Vautoload_queue))
2823 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2824 Vautoload_queue);
2825 tem = Fmemq (feature, Vfeatures);
2826 if (NILP (tem))
2827 Vfeatures = Fcons (feature, Vfeatures);
2828 if (!NILP (subfeatures))
2829 Fput (feature, Qsubfeatures, subfeatures);
2830 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2831
2832 /* Run any load-hooks for this file. */
2833 tem = Fassq (feature, Vafter_load_alist);
2834 if (CONSP (tem))
2835 Fmapc (Qfuncall, XCDR (tem));
2836
2837 return feature;
2838 }
2839 \f
2840 /* `require' and its subroutines. */
2841
2842 /* List of features currently being require'd, innermost first. */
2843
2844 static Lisp_Object require_nesting_list;
2845
2846 static void
2847 require_unwind (Lisp_Object old_value)
2848 {
2849 require_nesting_list = old_value;
2850 }
2851
2852 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2853 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2854 If FEATURE is not a member of the list `features', then the feature
2855 is not loaded; so load the file FILENAME.
2856 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2857 and `load' will try to load this name appended with the suffix `.elc' or
2858 `.el', in that order. The name without appended suffix will not be used.
2859 See `get-load-suffixes' for the complete list of suffixes.
2860 If the optional third argument NOERROR is non-nil,
2861 then return nil if the file is not found instead of signaling an error.
2862 Normally the return value is FEATURE.
2863 The normal messages at start and end of loading FILENAME are suppressed. */)
2864 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2865 {
2866 Lisp_Object tem;
2867 struct gcpro gcpro1, gcpro2;
2868 bool from_file = load_in_progress;
2869
2870 CHECK_SYMBOL (feature);
2871
2872 /* Record the presence of `require' in this file
2873 even if the feature specified is already loaded.
2874 But not more than once in any file,
2875 and not when we aren't loading or reading from a file. */
2876 if (!from_file)
2877 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2878 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2879 from_file = 1;
2880
2881 if (from_file)
2882 {
2883 tem = Fcons (Qrequire, feature);
2884 if (NILP (Fmember (tem, Vcurrent_load_list)))
2885 LOADHIST_ATTACH (tem);
2886 }
2887 tem = Fmemq (feature, Vfeatures);
2888
2889 if (NILP (tem))
2890 {
2891 ptrdiff_t count = SPECPDL_INDEX ();
2892 int nesting = 0;
2893
2894 /* This is to make sure that loadup.el gives a clear picture
2895 of what files are preloaded and when. */
2896 if (! NILP (Vpurify_flag))
2897 error ("(require %s) while preparing to dump",
2898 SDATA (SYMBOL_NAME (feature)));
2899
2900 /* A certain amount of recursive `require' is legitimate,
2901 but if we require the same feature recursively 3 times,
2902 signal an error. */
2903 tem = require_nesting_list;
2904 while (! NILP (tem))
2905 {
2906 if (! NILP (Fequal (feature, XCAR (tem))))
2907 nesting++;
2908 tem = XCDR (tem);
2909 }
2910 if (nesting > 3)
2911 error ("Recursive `require' for feature `%s'",
2912 SDATA (SYMBOL_NAME (feature)));
2913
2914 /* Update the list for any nested `require's that occur. */
2915 record_unwind_protect (require_unwind, require_nesting_list);
2916 require_nesting_list = Fcons (feature, require_nesting_list);
2917
2918 /* Value saved here is to be restored into Vautoload_queue */
2919 record_unwind_protect (un_autoload, Vautoload_queue);
2920 Vautoload_queue = Qt;
2921
2922 /* Load the file. */
2923 GCPRO2 (feature, filename);
2924 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2925 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2926 UNGCPRO;
2927
2928 /* If load failed entirely, return nil. */
2929 if (NILP (tem))
2930 return unbind_to (count, Qnil);
2931
2932 tem = Fmemq (feature, Vfeatures);
2933 if (NILP (tem))
2934 error ("Required feature `%s' was not provided",
2935 SDATA (SYMBOL_NAME (feature)));
2936
2937 /* Once loading finishes, don't undo it. */
2938 Vautoload_queue = Qt;
2939 feature = unbind_to (count, feature);
2940 }
2941
2942 return feature;
2943 }
2944 \f
2945 /* Primitives for work of the "widget" library.
2946 In an ideal world, this section would not have been necessary.
2947 However, lisp function calls being as slow as they are, it turns
2948 out that some functions in the widget library (wid-edit.el) are the
2949 bottleneck of Widget operation. Here is their translation to C,
2950 for the sole reason of efficiency. */
2951
2952 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2953 doc: /* Return non-nil if PLIST has the property PROP.
2954 PLIST is a property list, which is a list of the form
2955 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2956 Unlike `plist-get', this allows you to distinguish between a missing
2957 property and a property with the value nil.
2958 The value is actually the tail of PLIST whose car is PROP. */)
2959 (Lisp_Object plist, Lisp_Object prop)
2960 {
2961 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2962 {
2963 QUIT;
2964 plist = XCDR (plist);
2965 plist = CDR (plist);
2966 }
2967 return plist;
2968 }
2969
2970 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2971 doc: /* In WIDGET, set PROPERTY to VALUE.
2972 The value can later be retrieved with `widget-get'. */)
2973 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2974 {
2975 CHECK_CONS (widget);
2976 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2977 return value;
2978 }
2979
2980 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2981 doc: /* In WIDGET, get the value of PROPERTY.
2982 The value could either be specified when the widget was created, or
2983 later with `widget-put'. */)
2984 (Lisp_Object widget, Lisp_Object property)
2985 {
2986 Lisp_Object tmp;
2987
2988 while (1)
2989 {
2990 if (NILP (widget))
2991 return Qnil;
2992 CHECK_CONS (widget);
2993 tmp = Fplist_member (XCDR (widget), property);
2994 if (CONSP (tmp))
2995 {
2996 tmp = XCDR (tmp);
2997 return CAR (tmp);
2998 }
2999 tmp = XCAR (widget);
3000 if (NILP (tmp))
3001 return Qnil;
3002 widget = Fget (tmp, Qwidget_type);
3003 }
3004 }
3005
3006 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
3007 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
3008 ARGS are passed as extra arguments to the function.
3009 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
3010 (ptrdiff_t nargs, Lisp_Object *args)
3011 {
3012 /* This function can GC. */
3013 Lisp_Object newargs[3];
3014 struct gcpro gcpro1, gcpro2;
3015 Lisp_Object result;
3016
3017 newargs[0] = Fwidget_get (args[0], args[1]);
3018 newargs[1] = args[0];
3019 newargs[2] = Flist (nargs - 2, args + 2);
3020 GCPRO2 (newargs[0], newargs[2]);
3021 result = Fapply (3, newargs);
3022 UNGCPRO;
3023 return result;
3024 }
3025
3026 #ifdef HAVE_LANGINFO_CODESET
3027 #include <langinfo.h>
3028 #endif
3029
3030 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
3031 doc: /* Access locale data ITEM for the current C locale, if available.
3032 ITEM should be one of the following:
3033
3034 `codeset', returning the character set as a string (locale item CODESET);
3035
3036 `days', returning a 7-element vector of day names (locale items DAY_n);
3037
3038 `months', returning a 12-element vector of month names (locale items MON_n);
3039
3040 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3041 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3042
3043 If the system can't provide such information through a call to
3044 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3045
3046 See also Info node `(libc)Locales'.
3047
3048 The data read from the system are decoded using `locale-coding-system'. */)
3049 (Lisp_Object item)
3050 {
3051 char *str = NULL;
3052 #ifdef HAVE_LANGINFO_CODESET
3053 Lisp_Object val;
3054 if (EQ (item, Qcodeset))
3055 {
3056 str = nl_langinfo (CODESET);
3057 return build_string (str);
3058 }
3059 #ifdef DAY_1
3060 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3061 {
3062 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3063 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3064 int i;
3065 struct gcpro gcpro1;
3066 GCPRO1 (v);
3067 synchronize_system_time_locale ();
3068 for (i = 0; i < 7; i++)
3069 {
3070 str = nl_langinfo (days[i]);
3071 val = build_unibyte_string (str);
3072 /* Fixme: Is this coding system necessarily right, even if
3073 it is consistent with CODESET? If not, what to do? */
3074 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3075 0));
3076 }
3077 UNGCPRO;
3078 return v;
3079 }
3080 #endif /* DAY_1 */
3081 #ifdef MON_1
3082 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3083 {
3084 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3085 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3086 MON_8, MON_9, MON_10, MON_11, MON_12};
3087 int i;
3088 struct gcpro gcpro1;
3089 GCPRO1 (v);
3090 synchronize_system_time_locale ();
3091 for (i = 0; i < 12; i++)
3092 {
3093 str = nl_langinfo (months[i]);
3094 val = build_unibyte_string (str);
3095 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3096 0));
3097 }
3098 UNGCPRO;
3099 return v;
3100 }
3101 #endif /* MON_1 */
3102 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3103 but is in the locale files. This could be used by ps-print. */
3104 #ifdef PAPER_WIDTH
3105 else if (EQ (item, Qpaper))
3106 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
3107 #endif /* PAPER_WIDTH */
3108 #endif /* HAVE_LANGINFO_CODESET*/
3109 return Qnil;
3110 }
3111 \f
3112 /* base64 encode/decode functions (RFC 2045).
3113 Based on code from GNU recode. */
3114
3115 #define MIME_LINE_LENGTH 76
3116
3117 #define IS_ASCII(Character) \
3118 ((Character) < 128)
3119 #define IS_BASE64(Character) \
3120 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3121 #define IS_BASE64_IGNORABLE(Character) \
3122 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3123 || (Character) == '\f' || (Character) == '\r')
3124
3125 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3126 character or return retval if there are no characters left to
3127 process. */
3128 #define READ_QUADRUPLET_BYTE(retval) \
3129 do \
3130 { \
3131 if (i == length) \
3132 { \
3133 if (nchars_return) \
3134 *nchars_return = nchars; \
3135 return (retval); \
3136 } \
3137 c = from[i++]; \
3138 } \
3139 while (IS_BASE64_IGNORABLE (c))
3140
3141 /* Table of characters coding the 64 values. */
3142 static const char base64_value_to_char[64] =
3143 {
3144 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3145 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3146 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3147 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3148 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3149 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3150 '8', '9', '+', '/' /* 60-63 */
3151 };
3152
3153 /* Table of base64 values for first 128 characters. */
3154 static const short base64_char_to_value[128] =
3155 {
3156 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3157 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3158 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3159 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3160 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3161 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3162 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3163 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3164 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3165 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3166 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3167 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3168 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3169 };
3170
3171 /* The following diagram shows the logical steps by which three octets
3172 get transformed into four base64 characters.
3173
3174 .--------. .--------. .--------.
3175 |aaaaaabb| |bbbbcccc| |ccdddddd|
3176 `--------' `--------' `--------'
3177 6 2 4 4 2 6
3178 .--------+--------+--------+--------.
3179 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3180 `--------+--------+--------+--------'
3181
3182 .--------+--------+--------+--------.
3183 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3184 `--------+--------+--------+--------'
3185
3186 The octets are divided into 6 bit chunks, which are then encoded into
3187 base64 characters. */
3188
3189
3190 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3191 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3192 ptrdiff_t *);
3193
3194 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3195 2, 3, "r",
3196 doc: /* Base64-encode the region between BEG and END.
3197 Return the length of the encoded text.
3198 Optional third argument NO-LINE-BREAK means do not break long lines
3199 into shorter lines. */)
3200 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3201 {
3202 char *encoded;
3203 ptrdiff_t allength, length;
3204 ptrdiff_t ibeg, iend, encoded_length;
3205 ptrdiff_t old_pos = PT;
3206 USE_SAFE_ALLOCA;
3207
3208 validate_region (&beg, &end);
3209
3210 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3211 iend = CHAR_TO_BYTE (XFASTINT (end));
3212 move_gap_both (XFASTINT (beg), ibeg);
3213
3214 /* We need to allocate enough room for encoding the text.
3215 We need 33 1/3% more space, plus a newline every 76
3216 characters, and then we round up. */
3217 length = iend - ibeg;
3218 allength = length + length/3 + 1;
3219 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3220
3221 encoded = SAFE_ALLOCA (allength);
3222 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3223 encoded, length, NILP (no_line_break),
3224 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3225 if (encoded_length > allength)
3226 emacs_abort ();
3227
3228 if (encoded_length < 0)
3229 {
3230 /* The encoding wasn't possible. */
3231 SAFE_FREE ();
3232 error ("Multibyte character in data for base64 encoding");
3233 }
3234
3235 /* Now we have encoded the region, so we insert the new contents
3236 and delete the old. (Insert first in order to preserve markers.) */
3237 SET_PT_BOTH (XFASTINT (beg), ibeg);
3238 insert (encoded, encoded_length);
3239 SAFE_FREE ();
3240 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3241
3242 /* If point was outside of the region, restore it exactly; else just
3243 move to the beginning of the region. */
3244 if (old_pos >= XFASTINT (end))
3245 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3246 else if (old_pos > XFASTINT (beg))
3247 old_pos = XFASTINT (beg);
3248 SET_PT (old_pos);
3249
3250 /* We return the length of the encoded text. */
3251 return make_number (encoded_length);
3252 }
3253
3254 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3255 1, 2, 0,
3256 doc: /* Base64-encode STRING and return the result.
3257 Optional second argument NO-LINE-BREAK means do not break long lines
3258 into shorter lines. */)
3259 (Lisp_Object string, Lisp_Object no_line_break)
3260 {
3261 ptrdiff_t allength, length, encoded_length;
3262 char *encoded;
3263 Lisp_Object encoded_string;
3264 USE_SAFE_ALLOCA;
3265
3266 CHECK_STRING (string);
3267
3268 /* We need to allocate enough room for encoding the text.
3269 We need 33 1/3% more space, plus a newline every 76
3270 characters, and then we round up. */
3271 length = SBYTES (string);
3272 allength = length + length/3 + 1;
3273 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3274
3275 /* We need to allocate enough room for decoding the text. */
3276 encoded = SAFE_ALLOCA (allength);
3277
3278 encoded_length = base64_encode_1 (SSDATA (string),
3279 encoded, length, NILP (no_line_break),
3280 STRING_MULTIBYTE (string));
3281 if (encoded_length > allength)
3282 emacs_abort ();
3283
3284 if (encoded_length < 0)
3285 {
3286 /* The encoding wasn't possible. */
3287 error ("Multibyte character in data for base64 encoding");
3288 }
3289
3290 encoded_string = make_unibyte_string (encoded, encoded_length);
3291 SAFE_FREE ();
3292
3293 return encoded_string;
3294 }
3295
3296 static ptrdiff_t
3297 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3298 bool line_break, bool multibyte)
3299 {
3300 int counter = 0;
3301 ptrdiff_t i = 0;
3302 char *e = to;
3303 int c;
3304 unsigned int value;
3305 int bytes;
3306
3307 while (i < length)
3308 {
3309 if (multibyte)
3310 {
3311 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3312 if (CHAR_BYTE8_P (c))
3313 c = CHAR_TO_BYTE8 (c);
3314 else if (c >= 256)
3315 return -1;
3316 i += bytes;
3317 }
3318 else
3319 c = from[i++];
3320
3321 /* Wrap line every 76 characters. */
3322
3323 if (line_break)
3324 {
3325 if (counter < MIME_LINE_LENGTH / 4)
3326 counter++;
3327 else
3328 {
3329 *e++ = '\n';
3330 counter = 1;
3331 }
3332 }
3333
3334 /* Process first byte of a triplet. */
3335
3336 *e++ = base64_value_to_char[0x3f & c >> 2];
3337 value = (0x03 & c) << 4;
3338
3339 /* Process second byte of a triplet. */
3340
3341 if (i == length)
3342 {
3343 *e++ = base64_value_to_char[value];
3344 *e++ = '=';
3345 *e++ = '=';
3346 break;
3347 }
3348
3349 if (multibyte)
3350 {
3351 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3352 if (CHAR_BYTE8_P (c))
3353 c = CHAR_TO_BYTE8 (c);
3354 else if (c >= 256)
3355 return -1;
3356 i += bytes;
3357 }
3358 else
3359 c = from[i++];
3360
3361 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3362 value = (0x0f & c) << 2;
3363
3364 /* Process third byte of a triplet. */
3365
3366 if (i == length)
3367 {
3368 *e++ = base64_value_to_char[value];
3369 *e++ = '=';
3370 break;
3371 }
3372
3373 if (multibyte)
3374 {
3375 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3376 if (CHAR_BYTE8_P (c))
3377 c = CHAR_TO_BYTE8 (c);
3378 else if (c >= 256)
3379 return -1;
3380 i += bytes;
3381 }
3382 else
3383 c = from[i++];
3384
3385 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3386 *e++ = base64_value_to_char[0x3f & c];
3387 }
3388
3389 return e - to;
3390 }
3391
3392
3393 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3394 2, 2, "r",
3395 doc: /* Base64-decode the region between BEG and END.
3396 Return the length of the decoded text.
3397 If the region can't be decoded, signal an error and don't modify the buffer. */)
3398 (Lisp_Object beg, Lisp_Object end)
3399 {
3400 ptrdiff_t ibeg, iend, length, allength;
3401 char *decoded;
3402 ptrdiff_t old_pos = PT;
3403 ptrdiff_t decoded_length;
3404 ptrdiff_t inserted_chars;
3405 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3406 USE_SAFE_ALLOCA;
3407
3408 validate_region (&beg, &end);
3409
3410 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3411 iend = CHAR_TO_BYTE (XFASTINT (end));
3412
3413 length = iend - ibeg;
3414
3415 /* We need to allocate enough room for decoding the text. If we are
3416 working on a multibyte buffer, each decoded code may occupy at
3417 most two bytes. */
3418 allength = multibyte ? length * 2 : length;
3419 decoded = SAFE_ALLOCA (allength);
3420
3421 move_gap_both (XFASTINT (beg), ibeg);
3422 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3423 decoded, length,
3424 multibyte, &inserted_chars);
3425 if (decoded_length > allength)
3426 emacs_abort ();
3427
3428 if (decoded_length < 0)
3429 {
3430 /* The decoding wasn't possible. */
3431 error ("Invalid base64 data");
3432 }
3433
3434 /* Now we have decoded the region, so we insert the new contents
3435 and delete the old. (Insert first in order to preserve markers.) */
3436 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3437 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3438 SAFE_FREE ();
3439
3440 /* Delete the original text. */
3441 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3442 iend + decoded_length, 1);
3443
3444 /* If point was outside of the region, restore it exactly; else just
3445 move to the beginning of the region. */
3446 if (old_pos >= XFASTINT (end))
3447 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3448 else if (old_pos > XFASTINT (beg))
3449 old_pos = XFASTINT (beg);
3450 SET_PT (old_pos > ZV ? ZV : old_pos);
3451
3452 return make_number (inserted_chars);
3453 }
3454
3455 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3456 1, 1, 0,
3457 doc: /* Base64-decode STRING and return the result. */)
3458 (Lisp_Object string)
3459 {
3460 char *decoded;
3461 ptrdiff_t length, decoded_length;
3462 Lisp_Object decoded_string;
3463 USE_SAFE_ALLOCA;
3464
3465 CHECK_STRING (string);
3466
3467 length = SBYTES (string);
3468 /* We need to allocate enough room for decoding the text. */
3469 decoded = SAFE_ALLOCA (length);
3470
3471 /* The decoded result should be unibyte. */
3472 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3473 0, NULL);
3474 if (decoded_length > length)
3475 emacs_abort ();
3476 else if (decoded_length >= 0)
3477 decoded_string = make_unibyte_string (decoded, decoded_length);
3478 else
3479 decoded_string = Qnil;
3480
3481 SAFE_FREE ();
3482 if (!STRINGP (decoded_string))
3483 error ("Invalid base64 data");
3484
3485 return decoded_string;
3486 }
3487
3488 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3489 MULTIBYTE, the decoded result should be in multibyte
3490 form. If NCHARS_RETURN is not NULL, store the number of produced
3491 characters in *NCHARS_RETURN. */
3492
3493 static ptrdiff_t
3494 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3495 bool multibyte, ptrdiff_t *nchars_return)
3496 {
3497 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3498 char *e = to;
3499 unsigned char c;
3500 unsigned long value;
3501 ptrdiff_t nchars = 0;
3502
3503 while (1)
3504 {
3505 /* Process first byte of a quadruplet. */
3506
3507 READ_QUADRUPLET_BYTE (e-to);
3508
3509 if (!IS_BASE64 (c))
3510 return -1;
3511 value = base64_char_to_value[c] << 18;
3512
3513 /* Process second byte of a quadruplet. */
3514
3515 READ_QUADRUPLET_BYTE (-1);
3516
3517 if (!IS_BASE64 (c))
3518 return -1;
3519 value |= base64_char_to_value[c] << 12;
3520
3521 c = (unsigned char) (value >> 16);
3522 if (multibyte && c >= 128)
3523 e += BYTE8_STRING (c, e);
3524 else
3525 *e++ = c;
3526 nchars++;
3527
3528 /* Process third byte of a quadruplet. */
3529
3530 READ_QUADRUPLET_BYTE (-1);
3531
3532 if (c == '=')
3533 {
3534 READ_QUADRUPLET_BYTE (-1);
3535
3536 if (c != '=')
3537 return -1;
3538 continue;
3539 }
3540
3541 if (!IS_BASE64 (c))
3542 return -1;
3543 value |= base64_char_to_value[c] << 6;
3544
3545 c = (unsigned char) (0xff & value >> 8);
3546 if (multibyte && c >= 128)
3547 e += BYTE8_STRING (c, e);
3548 else
3549 *e++ = c;
3550 nchars++;
3551
3552 /* Process fourth byte of a quadruplet. */
3553
3554 READ_QUADRUPLET_BYTE (-1);
3555
3556 if (c == '=')
3557 continue;
3558
3559 if (!IS_BASE64 (c))
3560 return -1;
3561 value |= base64_char_to_value[c];
3562
3563 c = (unsigned char) (0xff & value);
3564 if (multibyte && c >= 128)
3565 e += BYTE8_STRING (c, e);
3566 else
3567 *e++ = c;
3568 nchars++;
3569 }
3570 }
3571
3572
3573 \f
3574 /***********************************************************************
3575 ***** *****
3576 ***** Hash Tables *****
3577 ***** *****
3578 ***********************************************************************/
3579
3580 /* Implemented by gerd@gnu.org. This hash table implementation was
3581 inspired by CMUCL hash tables. */
3582
3583 /* Ideas:
3584
3585 1. For small tables, association lists are probably faster than
3586 hash tables because they have lower overhead.
3587
3588 For uses of hash tables where the O(1) behavior of table
3589 operations is not a requirement, it might therefore be a good idea
3590 not to hash. Instead, we could just do a linear search in the
3591 key_and_value vector of the hash table. This could be done
3592 if a `:linear-search t' argument is given to make-hash-table. */
3593
3594
3595 /* The list of all weak hash tables. Don't staticpro this one. */
3596
3597 static struct Lisp_Hash_Table *weak_hash_tables;
3598
3599 /* Various symbols. */
3600
3601 static Lisp_Object Qhash_table_p;
3602 static Lisp_Object Qkey, Qvalue, Qeql;
3603 Lisp_Object Qeq, Qequal;
3604 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3605 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3606
3607 \f
3608 /***********************************************************************
3609 Utilities
3610 ***********************************************************************/
3611
3612 static void
3613 CHECK_HASH_TABLE (Lisp_Object x)
3614 {
3615 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3616 }
3617
3618 static void
3619 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3620 {
3621 h->key_and_value = key_and_value;
3622 }
3623 static void
3624 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3625 {
3626 h->next = next;
3627 }
3628 static void
3629 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3630 {
3631 gc_aset (h->next, idx, val);
3632 }
3633 static void
3634 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3635 {
3636 h->hash = hash;
3637 }
3638 static void
3639 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3640 {
3641 gc_aset (h->hash, idx, val);
3642 }
3643 static void
3644 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3645 {
3646 h->index = index;
3647 }
3648 static void
3649 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3650 {
3651 gc_aset (h->index, idx, val);
3652 }
3653
3654 /* If OBJ is a Lisp hash table, return a pointer to its struct
3655 Lisp_Hash_Table. Otherwise, signal an error. */
3656
3657 static struct Lisp_Hash_Table *
3658 check_hash_table (Lisp_Object obj)
3659 {
3660 CHECK_HASH_TABLE (obj);
3661 return XHASH_TABLE (obj);
3662 }
3663
3664
3665 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3666 number. A number is "almost" a prime number if it is not divisible
3667 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3668
3669 EMACS_INT
3670 next_almost_prime (EMACS_INT n)
3671 {
3672 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3673 for (n |= 1; ; n += 2)
3674 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3675 return n;
3676 }
3677
3678
3679 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3680 which USED[I] is non-zero. If found at index I in ARGS, set
3681 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3682 0. This function is used to extract a keyword/argument pair from
3683 a DEFUN parameter list. */
3684
3685 static ptrdiff_t
3686 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3687 {
3688 ptrdiff_t i;
3689
3690 for (i = 1; i < nargs; i++)
3691 if (!used[i - 1] && EQ (args[i - 1], key))
3692 {
3693 used[i - 1] = 1;
3694 used[i] = 1;
3695 return i;
3696 }
3697
3698 return 0;
3699 }
3700
3701
3702 /* Return a Lisp vector which has the same contents as VEC but has
3703 at least INCR_MIN more entries, where INCR_MIN is positive.
3704 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3705 than NITEMS_MAX. Entries in the resulting
3706 vector that are not copied from VEC are set to nil. */
3707
3708 Lisp_Object
3709 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3710 {
3711 struct Lisp_Vector *v;
3712 ptrdiff_t i, incr, incr_max, old_size, new_size;
3713 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3714 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3715 ? nitems_max : C_language_max);
3716 eassert (VECTORP (vec));
3717 eassert (0 < incr_min && -1 <= nitems_max);
3718 old_size = ASIZE (vec);
3719 incr_max = n_max - old_size;
3720 incr = max (incr_min, min (old_size >> 1, incr_max));
3721 if (incr_max < incr)
3722 memory_full (SIZE_MAX);
3723 new_size = old_size + incr;
3724 v = allocate_vector (new_size);
3725 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3726 for (i = old_size; i < new_size; ++i)
3727 v->contents[i] = Qnil;
3728 XSETVECTOR (vec, v);
3729 return vec;
3730 }
3731
3732
3733 /***********************************************************************
3734 Low-level Functions
3735 ***********************************************************************/
3736
3737 static struct hash_table_test hashtest_eq;
3738 struct hash_table_test hashtest_eql, hashtest_equal;
3739
3740 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3741 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3742 KEY2 are the same. */
3743
3744 static bool
3745 cmpfn_eql (struct hash_table_test *ht,
3746 Lisp_Object key1,
3747 Lisp_Object key2)
3748 {
3749 return (FLOATP (key1)
3750 && FLOATP (key2)
3751 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3752 }
3753
3754
3755 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3756 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3757 KEY2 are the same. */
3758
3759 static bool
3760 cmpfn_equal (struct hash_table_test *ht,
3761 Lisp_Object key1,
3762 Lisp_Object key2)
3763 {
3764 return !NILP (Fequal (key1, key2));
3765 }
3766
3767
3768 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3769 HASH2 in hash table H using H->user_cmp_function. Value is true
3770 if KEY1 and KEY2 are the same. */
3771
3772 static bool
3773 cmpfn_user_defined (struct hash_table_test *ht,
3774 Lisp_Object key1,
3775 Lisp_Object key2)
3776 {
3777 Lisp_Object args[3];
3778
3779 args[0] = ht->user_cmp_function;
3780 args[1] = key1;
3781 args[2] = key2;
3782 return !NILP (Ffuncall (3, args));
3783 }
3784
3785
3786 /* Value is a hash code for KEY for use in hash table H which uses
3787 `eq' to compare keys. The hash code returned is guaranteed to fit
3788 in a Lisp integer. */
3789
3790 static EMACS_UINT
3791 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3792 {
3793 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3794 return hash;
3795 }
3796
3797 /* Value is a hash code for KEY for use in hash table H which uses
3798 `eql' to compare keys. The hash code returned is guaranteed to fit
3799 in a Lisp integer. */
3800
3801 static EMACS_UINT
3802 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3803 {
3804 EMACS_UINT hash;
3805 if (FLOATP (key))
3806 hash = sxhash (key, 0);
3807 else
3808 hash = XHASH (key) ^ XTYPE (key);
3809 return hash;
3810 }
3811
3812 /* Value is a hash code for KEY for use in hash table H which uses
3813 `equal' to compare keys. The hash code returned is guaranteed to fit
3814 in a Lisp integer. */
3815
3816 static EMACS_UINT
3817 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3818 {
3819 EMACS_UINT hash = sxhash (key, 0);
3820 return hash;
3821 }
3822
3823 /* Value is a hash code for KEY for use in hash table H which uses as
3824 user-defined function to compare keys. The hash code returned is
3825 guaranteed to fit in a Lisp integer. */
3826
3827 static EMACS_UINT
3828 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3829 {
3830 Lisp_Object args[2], hash;
3831
3832 args[0] = ht->user_hash_function;
3833 args[1] = key;
3834 hash = Ffuncall (2, args);
3835 return hashfn_eq (ht, hash);
3836 }
3837
3838 /* An upper bound on the size of a hash table index. It must fit in
3839 ptrdiff_t and be a valid Emacs fixnum. */
3840 #define INDEX_SIZE_BOUND \
3841 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3842
3843 /* Create and initialize a new hash table.
3844
3845 TEST specifies the test the hash table will use to compare keys.
3846 It must be either one of the predefined tests `eq', `eql' or
3847 `equal' or a symbol denoting a user-defined test named TEST with
3848 test and hash functions USER_TEST and USER_HASH.
3849
3850 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3851
3852 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3853 new size when it becomes full is computed by adding REHASH_SIZE to
3854 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3855 table's new size is computed by multiplying its old size with
3856 REHASH_SIZE.
3857
3858 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3859 be resized when the ratio of (number of entries in the table) /
3860 (table size) is >= REHASH_THRESHOLD.
3861
3862 WEAK specifies the weakness of the table. If non-nil, it must be
3863 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3864
3865 Lisp_Object
3866 make_hash_table (struct hash_table_test test,
3867 Lisp_Object size, Lisp_Object rehash_size,
3868 Lisp_Object rehash_threshold, Lisp_Object weak)
3869 {
3870 struct Lisp_Hash_Table *h;
3871 Lisp_Object table;
3872 EMACS_INT index_size, sz;
3873 ptrdiff_t i;
3874 double index_float;
3875
3876 /* Preconditions. */
3877 eassert (SYMBOLP (test.name));
3878 eassert (INTEGERP (size) && XINT (size) >= 0);
3879 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3880 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3881 eassert (FLOATP (rehash_threshold)
3882 && 0 < XFLOAT_DATA (rehash_threshold)
3883 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3884
3885 if (XFASTINT (size) == 0)
3886 size = make_number (1);
3887
3888 sz = XFASTINT (size);
3889 index_float = sz / XFLOAT_DATA (rehash_threshold);
3890 index_size = (index_float < INDEX_SIZE_BOUND + 1
3891 ? next_almost_prime (index_float)
3892 : INDEX_SIZE_BOUND + 1);
3893 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3894 error ("Hash table too large");
3895
3896 /* Allocate a table and initialize it. */
3897 h = allocate_hash_table ();
3898
3899 /* Initialize hash table slots. */
3900 h->test = test;
3901 h->weak = weak;
3902 h->rehash_threshold = rehash_threshold;
3903 h->rehash_size = rehash_size;
3904 h->count = 0;
3905 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3906 h->hash = Fmake_vector (size, Qnil);
3907 h->next = Fmake_vector (size, Qnil);
3908 h->index = Fmake_vector (make_number (index_size), Qnil);
3909
3910 /* Set up the free list. */
3911 for (i = 0; i < sz - 1; ++i)
3912 set_hash_next_slot (h, i, make_number (i + 1));
3913 h->next_free = make_number (0);
3914
3915 XSET_HASH_TABLE (table, h);
3916 eassert (HASH_TABLE_P (table));
3917 eassert (XHASH_TABLE (table) == h);
3918
3919 /* Maybe add this hash table to the list of all weak hash tables. */
3920 if (NILP (h->weak))
3921 h->next_weak = NULL;
3922 else
3923 {
3924 h->next_weak = weak_hash_tables;
3925 weak_hash_tables = h;
3926 }
3927
3928 return table;
3929 }
3930
3931
3932 /* Return a copy of hash table H1. Keys and values are not copied,
3933 only the table itself is. */
3934
3935 static Lisp_Object
3936 copy_hash_table (struct Lisp_Hash_Table *h1)
3937 {
3938 Lisp_Object table;
3939 struct Lisp_Hash_Table *h2;
3940
3941 h2 = allocate_hash_table ();
3942 *h2 = *h1;
3943 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3944 h2->hash = Fcopy_sequence (h1->hash);
3945 h2->next = Fcopy_sequence (h1->next);
3946 h2->index = Fcopy_sequence (h1->index);
3947 XSET_HASH_TABLE (table, h2);
3948
3949 /* Maybe add this hash table to the list of all weak hash tables. */
3950 if (!NILP (h2->weak))
3951 {
3952 h2->next_weak = weak_hash_tables;
3953 weak_hash_tables = h2;
3954 }
3955
3956 return table;
3957 }
3958
3959
3960 /* Resize hash table H if it's too full. If H cannot be resized
3961 because it's already too large, throw an error. */
3962
3963 static void
3964 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3965 {
3966 if (NILP (h->next_free))
3967 {
3968 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3969 EMACS_INT new_size, index_size, nsize;
3970 ptrdiff_t i;
3971 double index_float;
3972
3973 if (INTEGERP (h->rehash_size))
3974 new_size = old_size + XFASTINT (h->rehash_size);
3975 else
3976 {
3977 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3978 if (float_new_size < INDEX_SIZE_BOUND + 1)
3979 {
3980 new_size = float_new_size;
3981 if (new_size <= old_size)
3982 new_size = old_size + 1;
3983 }
3984 else
3985 new_size = INDEX_SIZE_BOUND + 1;
3986 }
3987 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3988 index_size = (index_float < INDEX_SIZE_BOUND + 1
3989 ? next_almost_prime (index_float)
3990 : INDEX_SIZE_BOUND + 1);
3991 nsize = max (index_size, 2 * new_size);
3992 if (INDEX_SIZE_BOUND < nsize)
3993 error ("Hash table too large to resize");
3994
3995 #ifdef ENABLE_CHECKING
3996 if (HASH_TABLE_P (Vpurify_flag)
3997 && XHASH_TABLE (Vpurify_flag) == h)
3998 Fmessage (2, ((Lisp_Object [])
3999 { build_string ("Growing hash table to: %d"),
4000 make_number (new_size) }));
4001 #endif
4002
4003 set_hash_key_and_value (h, larger_vector (h->key_and_value,
4004 2 * (new_size - old_size), -1));
4005 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
4006 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
4007 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
4008
4009 /* Update the free list. Do it so that new entries are added at
4010 the end of the free list. This makes some operations like
4011 maphash faster. */
4012 for (i = old_size; i < new_size - 1; ++i)
4013 set_hash_next_slot (h, i, make_number (i + 1));
4014
4015 if (!NILP (h->next_free))
4016 {
4017 Lisp_Object last, next;
4018
4019 last = h->next_free;
4020 while (next = HASH_NEXT (h, XFASTINT (last)),
4021 !NILP (next))
4022 last = next;
4023
4024 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
4025 }
4026 else
4027 XSETFASTINT (h->next_free, old_size);
4028
4029 /* Rehash. */
4030 for (i = 0; i < old_size; ++i)
4031 if (!NILP (HASH_HASH (h, i)))
4032 {
4033 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
4034 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
4035 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4036 set_hash_index_slot (h, start_of_bucket, make_number (i));
4037 }
4038 }
4039 }
4040
4041
4042 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4043 the hash code of KEY. Value is the index of the entry in H
4044 matching KEY, or -1 if not found. */
4045
4046 ptrdiff_t
4047 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
4048 {
4049 EMACS_UINT hash_code;
4050 ptrdiff_t start_of_bucket;
4051 Lisp_Object idx;
4052
4053 hash_code = h->test.hashfn (&h->test, key);
4054 eassert ((hash_code & ~INTMASK) == 0);
4055 if (hash)
4056 *hash = hash_code;
4057
4058 start_of_bucket = hash_code % ASIZE (h->index);
4059 idx = HASH_INDEX (h, start_of_bucket);
4060
4061 /* We need not gcpro idx since it's either an integer or nil. */
4062 while (!NILP (idx))
4063 {
4064 ptrdiff_t i = XFASTINT (idx);
4065 if (EQ (key, HASH_KEY (h, i))
4066 || (h->test.cmpfn
4067 && hash_code == XUINT (HASH_HASH (h, i))
4068 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4069 break;
4070 idx = HASH_NEXT (h, i);
4071 }
4072
4073 return NILP (idx) ? -1 : XFASTINT (idx);
4074 }
4075
4076
4077 /* Put an entry into hash table H that associates KEY with VALUE.
4078 HASH is a previously computed hash code of KEY.
4079 Value is the index of the entry in H matching KEY. */
4080
4081 ptrdiff_t
4082 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
4083 EMACS_UINT hash)
4084 {
4085 ptrdiff_t start_of_bucket, i;
4086
4087 eassert ((hash & ~INTMASK) == 0);
4088
4089 /* Increment count after resizing because resizing may fail. */
4090 maybe_resize_hash_table (h);
4091 h->count++;
4092
4093 /* Store key/value in the key_and_value vector. */
4094 i = XFASTINT (h->next_free);
4095 h->next_free = HASH_NEXT (h, i);
4096 set_hash_key_slot (h, i, key);
4097 set_hash_value_slot (h, i, value);
4098
4099 /* Remember its hash code. */
4100 set_hash_hash_slot (h, i, make_number (hash));
4101
4102 /* Add new entry to its collision chain. */
4103 start_of_bucket = hash % ASIZE (h->index);
4104 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4105 set_hash_index_slot (h, start_of_bucket, make_number (i));
4106 return i;
4107 }
4108
4109
4110 /* Remove the entry matching KEY from hash table H, if there is one. */
4111
4112 static void
4113 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4114 {
4115 EMACS_UINT hash_code;
4116 ptrdiff_t start_of_bucket;
4117 Lisp_Object idx, prev;
4118
4119 hash_code = h->test.hashfn (&h->test, key);
4120 eassert ((hash_code & ~INTMASK) == 0);
4121 start_of_bucket = hash_code % ASIZE (h->index);
4122 idx = HASH_INDEX (h, start_of_bucket);
4123 prev = Qnil;
4124
4125 /* We need not gcpro idx, prev since they're either integers or nil. */
4126 while (!NILP (idx))
4127 {
4128 ptrdiff_t i = XFASTINT (idx);
4129
4130 if (EQ (key, HASH_KEY (h, i))
4131 || (h->test.cmpfn
4132 && hash_code == XUINT (HASH_HASH (h, i))
4133 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4134 {
4135 /* Take entry out of collision chain. */
4136 if (NILP (prev))
4137 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4138 else
4139 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4140
4141 /* Clear slots in key_and_value and add the slots to
4142 the free list. */
4143 set_hash_key_slot (h, i, Qnil);
4144 set_hash_value_slot (h, i, Qnil);
4145 set_hash_hash_slot (h, i, Qnil);
4146 set_hash_next_slot (h, i, h->next_free);
4147 h->next_free = make_number (i);
4148 h->count--;
4149 eassert (h->count >= 0);
4150 break;
4151 }
4152 else
4153 {
4154 prev = idx;
4155 idx = HASH_NEXT (h, i);
4156 }
4157 }
4158 }
4159
4160
4161 /* Clear hash table H. */
4162
4163 static void
4164 hash_clear (struct Lisp_Hash_Table *h)
4165 {
4166 if (h->count > 0)
4167 {
4168 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4169
4170 for (i = 0; i < size; ++i)
4171 {
4172 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4173 set_hash_key_slot (h, i, Qnil);
4174 set_hash_value_slot (h, i, Qnil);
4175 set_hash_hash_slot (h, i, Qnil);
4176 }
4177
4178 for (i = 0; i < ASIZE (h->index); ++i)
4179 ASET (h->index, i, Qnil);
4180
4181 h->next_free = make_number (0);
4182 h->count = 0;
4183 }
4184 }
4185
4186
4187 \f
4188 /************************************************************************
4189 Weak Hash Tables
4190 ************************************************************************/
4191
4192 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4193 entries from the table that don't survive the current GC.
4194 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4195 true if anything was marked. */
4196
4197 static bool
4198 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4199 {
4200 ptrdiff_t bucket, n;
4201 bool marked;
4202
4203 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
4204 marked = 0;
4205
4206 for (bucket = 0; bucket < n; ++bucket)
4207 {
4208 Lisp_Object idx, next, prev;
4209
4210 /* Follow collision chain, removing entries that
4211 don't survive this garbage collection. */
4212 prev = Qnil;
4213 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4214 {
4215 ptrdiff_t i = XFASTINT (idx);
4216 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4217 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4218 bool remove_p;
4219
4220 if (EQ (h->weak, Qkey))
4221 remove_p = !key_known_to_survive_p;
4222 else if (EQ (h->weak, Qvalue))
4223 remove_p = !value_known_to_survive_p;
4224 else if (EQ (h->weak, Qkey_or_value))
4225 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4226 else if (EQ (h->weak, Qkey_and_value))
4227 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4228 else
4229 emacs_abort ();
4230
4231 next = HASH_NEXT (h, i);
4232
4233 if (remove_entries_p)
4234 {
4235 if (remove_p)
4236 {
4237 /* Take out of collision chain. */
4238 if (NILP (prev))
4239 set_hash_index_slot (h, bucket, next);
4240 else
4241 set_hash_next_slot (h, XFASTINT (prev), next);
4242
4243 /* Add to free list. */
4244 set_hash_next_slot (h, i, h->next_free);
4245 h->next_free = idx;
4246
4247 /* Clear key, value, and hash. */
4248 set_hash_key_slot (h, i, Qnil);
4249 set_hash_value_slot (h, i, Qnil);
4250 set_hash_hash_slot (h, i, Qnil);
4251
4252 h->count--;
4253 }
4254 else
4255 {
4256 prev = idx;
4257 }
4258 }
4259 else
4260 {
4261 if (!remove_p)
4262 {
4263 /* Make sure key and value survive. */
4264 if (!key_known_to_survive_p)
4265 {
4266 mark_object (HASH_KEY (h, i));
4267 marked = 1;
4268 }
4269
4270 if (!value_known_to_survive_p)
4271 {
4272 mark_object (HASH_VALUE (h, i));
4273 marked = 1;
4274 }
4275 }
4276 }
4277 }
4278 }
4279
4280 return marked;
4281 }
4282
4283 /* Remove elements from weak hash tables that don't survive the
4284 current garbage collection. Remove weak tables that don't survive
4285 from Vweak_hash_tables. Called from gc_sweep. */
4286
4287 NO_INLINE /* For better stack traces */
4288 void
4289 sweep_weak_hash_tables (void)
4290 {
4291 struct Lisp_Hash_Table *h, *used, *next;
4292 bool marked;
4293
4294 /* Mark all keys and values that are in use. Keep on marking until
4295 there is no more change. This is necessary for cases like
4296 value-weak table A containing an entry X -> Y, where Y is used in a
4297 key-weak table B, Z -> Y. If B comes after A in the list of weak
4298 tables, X -> Y might be removed from A, although when looking at B
4299 one finds that it shouldn't. */
4300 do
4301 {
4302 marked = 0;
4303 for (h = weak_hash_tables; h; h = h->next_weak)
4304 {
4305 if (h->header.size & ARRAY_MARK_FLAG)
4306 marked |= sweep_weak_table (h, 0);
4307 }
4308 }
4309 while (marked);
4310
4311 /* Remove tables and entries that aren't used. */
4312 for (h = weak_hash_tables, used = NULL; h; h = next)
4313 {
4314 next = h->next_weak;
4315
4316 if (h->header.size & ARRAY_MARK_FLAG)
4317 {
4318 /* TABLE is marked as used. Sweep its contents. */
4319 if (h->count > 0)
4320 sweep_weak_table (h, 1);
4321
4322 /* Add table to the list of used weak hash tables. */
4323 h->next_weak = used;
4324 used = h;
4325 }
4326 }
4327
4328 weak_hash_tables = used;
4329 }
4330
4331
4332 \f
4333 /***********************************************************************
4334 Hash Code Computation
4335 ***********************************************************************/
4336
4337 /* Maximum depth up to which to dive into Lisp structures. */
4338
4339 #define SXHASH_MAX_DEPTH 3
4340
4341 /* Maximum length up to which to take list and vector elements into
4342 account. */
4343
4344 #define SXHASH_MAX_LEN 7
4345
4346 /* Return a hash for string PTR which has length LEN. The hash value
4347 can be any EMACS_UINT value. */
4348
4349 EMACS_UINT
4350 hash_string (char const *ptr, ptrdiff_t len)
4351 {
4352 char const *p = ptr;
4353 char const *end = p + len;
4354 unsigned char c;
4355 EMACS_UINT hash = 0;
4356
4357 while (p != end)
4358 {
4359 c = *p++;
4360 hash = sxhash_combine (hash, c);
4361 }
4362
4363 return hash;
4364 }
4365
4366 /* Return a hash for string PTR which has length LEN. The hash
4367 code returned is guaranteed to fit in a Lisp integer. */
4368
4369 static EMACS_UINT
4370 sxhash_string (char const *ptr, ptrdiff_t len)
4371 {
4372 EMACS_UINT hash = hash_string (ptr, len);
4373 return SXHASH_REDUCE (hash);
4374 }
4375
4376 /* Return a hash for the floating point value VAL. */
4377
4378 static EMACS_UINT
4379 sxhash_float (double val)
4380 {
4381 EMACS_UINT hash = 0;
4382 enum {
4383 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4384 + (sizeof val % sizeof hash != 0))
4385 };
4386 union {
4387 double val;
4388 EMACS_UINT word[WORDS_PER_DOUBLE];
4389 } u;
4390 int i;
4391 u.val = val;
4392 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4393 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4394 hash = sxhash_combine (hash, u.word[i]);
4395 return SXHASH_REDUCE (hash);
4396 }
4397
4398 /* Return a hash for list LIST. DEPTH is the current depth in the
4399 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4400
4401 static EMACS_UINT
4402 sxhash_list (Lisp_Object list, int depth)
4403 {
4404 EMACS_UINT hash = 0;
4405 int i;
4406
4407 if (depth < SXHASH_MAX_DEPTH)
4408 for (i = 0;
4409 CONSP (list) && i < SXHASH_MAX_LEN;
4410 list = XCDR (list), ++i)
4411 {
4412 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4413 hash = sxhash_combine (hash, hash2);
4414 }
4415
4416 if (!NILP (list))
4417 {
4418 EMACS_UINT hash2 = sxhash (list, depth + 1);
4419 hash = sxhash_combine (hash, hash2);
4420 }
4421
4422 return SXHASH_REDUCE (hash);
4423 }
4424
4425
4426 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4427 the Lisp structure. */
4428
4429 static EMACS_UINT
4430 sxhash_vector (Lisp_Object vec, int depth)
4431 {
4432 EMACS_UINT hash = ASIZE (vec);
4433 int i, n;
4434
4435 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4436 for (i = 0; i < n; ++i)
4437 {
4438 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4439 hash = sxhash_combine (hash, hash2);
4440 }
4441
4442 return SXHASH_REDUCE (hash);
4443 }
4444
4445 /* Return a hash for bool-vector VECTOR. */
4446
4447 static EMACS_UINT
4448 sxhash_bool_vector (Lisp_Object vec)
4449 {
4450 EMACS_INT size = bool_vector_size (vec);
4451 EMACS_UINT hash = size;
4452 int i, n;
4453
4454 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4455 for (i = 0; i < n; ++i)
4456 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4457
4458 return SXHASH_REDUCE (hash);
4459 }
4460
4461
4462 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4463 structure. Value is an unsigned integer clipped to INTMASK. */
4464
4465 EMACS_UINT
4466 sxhash (Lisp_Object obj, int depth)
4467 {
4468 EMACS_UINT hash;
4469
4470 if (depth > SXHASH_MAX_DEPTH)
4471 return 0;
4472
4473 switch (XTYPE (obj))
4474 {
4475 case_Lisp_Int:
4476 hash = XUINT (obj);
4477 break;
4478
4479 case Lisp_Misc:
4480 case Lisp_Symbol:
4481 hash = XHASH (obj);
4482 break;
4483
4484 case Lisp_String:
4485 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4486 break;
4487
4488 /* This can be everything from a vector to an overlay. */
4489 case Lisp_Vectorlike:
4490 if (VECTORP (obj))
4491 /* According to the CL HyperSpec, two arrays are equal only if
4492 they are `eq', except for strings and bit-vectors. In
4493 Emacs, this works differently. We have to compare element
4494 by element. */
4495 hash = sxhash_vector (obj, depth);
4496 else if (BOOL_VECTOR_P (obj))
4497 hash = sxhash_bool_vector (obj);
4498 else
4499 /* Others are `equal' if they are `eq', so let's take their
4500 address as hash. */
4501 hash = XHASH (obj);
4502 break;
4503
4504 case Lisp_Cons:
4505 hash = sxhash_list (obj, depth);
4506 break;
4507
4508 case Lisp_Float:
4509 hash = sxhash_float (XFLOAT_DATA (obj));
4510 break;
4511
4512 default:
4513 emacs_abort ();
4514 }
4515
4516 return hash;
4517 }
4518
4519
4520 \f
4521 /***********************************************************************
4522 Lisp Interface
4523 ***********************************************************************/
4524
4525
4526 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4527 doc: /* Compute a hash code for OBJ and return it as integer. */)
4528 (Lisp_Object obj)
4529 {
4530 EMACS_UINT hash = sxhash (obj, 0);
4531 return make_number (hash);
4532 }
4533
4534
4535 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4536 doc: /* Create and return a new hash table.
4537
4538 Arguments are specified as keyword/argument pairs. The following
4539 arguments are defined:
4540
4541 :test TEST -- TEST must be a symbol that specifies how to compare
4542 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4543 `equal'. User-supplied test and hash functions can be specified via
4544 `define-hash-table-test'.
4545
4546 :size SIZE -- A hint as to how many elements will be put in the table.
4547 Default is 65.
4548
4549 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4550 fills up. If REHASH-SIZE is an integer, increase the size by that
4551 amount. If it is a float, it must be > 1.0, and the new size is the
4552 old size multiplied by that factor. Default is 1.5.
4553
4554 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4555 Resize the hash table when the ratio (number of entries / table size)
4556 is greater than or equal to THRESHOLD. Default is 0.8.
4557
4558 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4559 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4560 returned is a weak table. Key/value pairs are removed from a weak
4561 hash table when there are no non-weak references pointing to their
4562 key, value, one of key or value, or both key and value, depending on
4563 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4564 is nil.
4565
4566 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4567 (ptrdiff_t nargs, Lisp_Object *args)
4568 {
4569 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4570 struct hash_table_test testdesc;
4571 ptrdiff_t i;
4572 USE_SAFE_ALLOCA;
4573
4574 /* The vector `used' is used to keep track of arguments that
4575 have been consumed. */
4576 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4577 memset (used, 0, nargs * sizeof *used);
4578
4579 /* See if there's a `:test TEST' among the arguments. */
4580 i = get_key_arg (QCtest, nargs, args, used);
4581 test = i ? args[i] : Qeql;
4582 if (EQ (test, Qeq))
4583 testdesc = hashtest_eq;
4584 else if (EQ (test, Qeql))
4585 testdesc = hashtest_eql;
4586 else if (EQ (test, Qequal))
4587 testdesc = hashtest_equal;
4588 else
4589 {
4590 /* See if it is a user-defined test. */
4591 Lisp_Object prop;
4592
4593 prop = Fget (test, Qhash_table_test);
4594 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4595 signal_error ("Invalid hash table test", test);
4596 testdesc.name = test;
4597 testdesc.user_cmp_function = XCAR (prop);
4598 testdesc.user_hash_function = XCAR (XCDR (prop));
4599 testdesc.hashfn = hashfn_user_defined;
4600 testdesc.cmpfn = cmpfn_user_defined;
4601 }
4602
4603 /* See if there's a `:size SIZE' argument. */
4604 i = get_key_arg (QCsize, nargs, args, used);
4605 size = i ? args[i] : Qnil;
4606 if (NILP (size))
4607 size = make_number (DEFAULT_HASH_SIZE);
4608 else if (!INTEGERP (size) || XINT (size) < 0)
4609 signal_error ("Invalid hash table size", size);
4610
4611 /* Look for `:rehash-size SIZE'. */
4612 i = get_key_arg (QCrehash_size, nargs, args, used);
4613 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4614 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4615 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4616 signal_error ("Invalid hash table rehash size", rehash_size);
4617
4618 /* Look for `:rehash-threshold THRESHOLD'. */
4619 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4620 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4621 if (! (FLOATP (rehash_threshold)
4622 && 0 < XFLOAT_DATA (rehash_threshold)
4623 && XFLOAT_DATA (rehash_threshold) <= 1))
4624 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4625
4626 /* Look for `:weakness WEAK'. */
4627 i = get_key_arg (QCweakness, nargs, args, used);
4628 weak = i ? args[i] : Qnil;
4629 if (EQ (weak, Qt))
4630 weak = Qkey_and_value;
4631 if (!NILP (weak)
4632 && !EQ (weak, Qkey)
4633 && !EQ (weak, Qvalue)
4634 && !EQ (weak, Qkey_or_value)
4635 && !EQ (weak, Qkey_and_value))
4636 signal_error ("Invalid hash table weakness", weak);
4637
4638 /* Now, all args should have been used up, or there's a problem. */
4639 for (i = 0; i < nargs; ++i)
4640 if (!used[i])
4641 signal_error ("Invalid argument list", args[i]);
4642
4643 SAFE_FREE ();
4644 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4645 }
4646
4647
4648 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4649 doc: /* Return a copy of hash table TABLE. */)
4650 (Lisp_Object table)
4651 {
4652 return copy_hash_table (check_hash_table (table));
4653 }
4654
4655
4656 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4657 doc: /* Return the number of elements in TABLE. */)
4658 (Lisp_Object table)
4659 {
4660 return make_number (check_hash_table (table)->count);
4661 }
4662
4663
4664 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4665 Shash_table_rehash_size, 1, 1, 0,
4666 doc: /* Return the current rehash size of TABLE. */)
4667 (Lisp_Object table)
4668 {
4669 return check_hash_table (table)->rehash_size;
4670 }
4671
4672
4673 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4674 Shash_table_rehash_threshold, 1, 1, 0,
4675 doc: /* Return the current rehash threshold of TABLE. */)
4676 (Lisp_Object table)
4677 {
4678 return check_hash_table (table)->rehash_threshold;
4679 }
4680
4681
4682 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4683 doc: /* Return the size of TABLE.
4684 The size can be used as an argument to `make-hash-table' to create
4685 a hash table than can hold as many elements as TABLE holds
4686 without need for resizing. */)
4687 (Lisp_Object table)
4688 {
4689 struct Lisp_Hash_Table *h = check_hash_table (table);
4690 return make_number (HASH_TABLE_SIZE (h));
4691 }
4692
4693
4694 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4695 doc: /* Return the test TABLE uses. */)
4696 (Lisp_Object table)
4697 {
4698 return check_hash_table (table)->test.name;
4699 }
4700
4701
4702 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4703 1, 1, 0,
4704 doc: /* Return the weakness of TABLE. */)
4705 (Lisp_Object table)
4706 {
4707 return check_hash_table (table)->weak;
4708 }
4709
4710
4711 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4712 doc: /* Return t if OBJ is a Lisp hash table object. */)
4713 (Lisp_Object obj)
4714 {
4715 return HASH_TABLE_P (obj) ? Qt : Qnil;
4716 }
4717
4718
4719 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4720 doc: /* Clear hash table TABLE and return it. */)
4721 (Lisp_Object table)
4722 {
4723 hash_clear (check_hash_table (table));
4724 /* Be compatible with XEmacs. */
4725 return table;
4726 }
4727
4728
4729 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4730 doc: /* Look up KEY in TABLE and return its associated value.
4731 If KEY is not found, return DFLT which defaults to nil. */)
4732 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4733 {
4734 struct Lisp_Hash_Table *h = check_hash_table (table);
4735 ptrdiff_t i = hash_lookup (h, key, NULL);
4736 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4737 }
4738
4739
4740 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4741 doc: /* Associate KEY with VALUE in hash table TABLE.
4742 If KEY is already present in table, replace its current value with
4743 VALUE. In any case, return VALUE. */)
4744 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4745 {
4746 struct Lisp_Hash_Table *h = check_hash_table (table);
4747 ptrdiff_t i;
4748 EMACS_UINT hash;
4749
4750 i = hash_lookup (h, key, &hash);
4751 if (i >= 0)
4752 set_hash_value_slot (h, i, value);
4753 else
4754 hash_put (h, key, value, hash);
4755
4756 return value;
4757 }
4758
4759
4760 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4761 doc: /* Remove KEY from TABLE. */)
4762 (Lisp_Object key, Lisp_Object table)
4763 {
4764 struct Lisp_Hash_Table *h = check_hash_table (table);
4765 hash_remove_from_table (h, key);
4766 return Qnil;
4767 }
4768
4769
4770 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4771 doc: /* Call FUNCTION for all entries in hash table TABLE.
4772 FUNCTION is called with two arguments, KEY and VALUE.
4773 `maphash' always returns nil. */)
4774 (Lisp_Object function, Lisp_Object table)
4775 {
4776 struct Lisp_Hash_Table *h = check_hash_table (table);
4777 Lisp_Object args[3];
4778 ptrdiff_t i;
4779
4780 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4781 if (!NILP (HASH_HASH (h, i)))
4782 {
4783 args[0] = function;
4784 args[1] = HASH_KEY (h, i);
4785 args[2] = HASH_VALUE (h, i);
4786 Ffuncall (3, args);
4787 }
4788
4789 return Qnil;
4790 }
4791
4792
4793 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4794 Sdefine_hash_table_test, 3, 3, 0,
4795 doc: /* Define a new hash table test with name NAME, a symbol.
4796
4797 In hash tables created with NAME specified as test, use TEST to
4798 compare keys, and HASH for computing hash codes of keys.
4799
4800 TEST must be a function taking two arguments and returning non-nil if
4801 both arguments are the same. HASH must be a function taking one
4802 argument and returning an object that is the hash code of the argument.
4803 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4804 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4805 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4806 {
4807 return Fput (name, Qhash_table_test, list2 (test, hash));
4808 }
4809
4810
4811 \f
4812 /************************************************************************
4813 MD5, SHA-1, and SHA-2
4814 ************************************************************************/
4815
4816 #include "md5.h"
4817 #include "sha1.h"
4818 #include "sha256.h"
4819 #include "sha512.h"
4820
4821 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4822
4823 static Lisp_Object
4824 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4825 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4826 Lisp_Object binary)
4827 {
4828 int i;
4829 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4830 register EMACS_INT b, e;
4831 register struct buffer *bp;
4832 EMACS_INT temp;
4833 int digest_size;
4834 void *(*hash_func) (const char *, size_t, void *);
4835 Lisp_Object digest;
4836
4837 CHECK_SYMBOL (algorithm);
4838
4839 if (STRINGP (object))
4840 {
4841 if (NILP (coding_system))
4842 {
4843 /* Decide the coding-system to encode the data with. */
4844
4845 if (STRING_MULTIBYTE (object))
4846 /* use default, we can't guess correct value */
4847 coding_system = preferred_coding_system ();
4848 else
4849 coding_system = Qraw_text;
4850 }
4851
4852 if (NILP (Fcoding_system_p (coding_system)))
4853 {
4854 /* Invalid coding system. */
4855
4856 if (!NILP (noerror))
4857 coding_system = Qraw_text;
4858 else
4859 xsignal1 (Qcoding_system_error, coding_system);
4860 }
4861
4862 if (STRING_MULTIBYTE (object))
4863 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4864
4865 size = SCHARS (object);
4866 validate_subarray (object, start, end, size, &start_char, &end_char);
4867
4868 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4869 end_byte = (end_char == size
4870 ? SBYTES (object)
4871 : string_char_to_byte (object, end_char));
4872 }
4873 else
4874 {
4875 struct buffer *prev = current_buffer;
4876
4877 record_unwind_current_buffer ();
4878
4879 CHECK_BUFFER (object);
4880
4881 bp = XBUFFER (object);
4882 set_buffer_internal (bp);
4883
4884 if (NILP (start))
4885 b = BEGV;
4886 else
4887 {
4888 CHECK_NUMBER_COERCE_MARKER (start);
4889 b = XINT (start);
4890 }
4891
4892 if (NILP (end))
4893 e = ZV;
4894 else
4895 {
4896 CHECK_NUMBER_COERCE_MARKER (end);
4897 e = XINT (end);
4898 }
4899
4900 if (b > e)
4901 temp = b, b = e, e = temp;
4902
4903 if (!(BEGV <= b && e <= ZV))
4904 args_out_of_range (start, end);
4905
4906 if (NILP (coding_system))
4907 {
4908 /* Decide the coding-system to encode the data with.
4909 See fileio.c:Fwrite-region */
4910
4911 if (!NILP (Vcoding_system_for_write))
4912 coding_system = Vcoding_system_for_write;
4913 else
4914 {
4915 bool force_raw_text = 0;
4916
4917 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4918 if (NILP (coding_system)
4919 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4920 {
4921 coding_system = Qnil;
4922 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4923 force_raw_text = 1;
4924 }
4925
4926 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4927 {
4928 /* Check file-coding-system-alist. */
4929 Lisp_Object args[4], val;
4930
4931 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4932 args[3] = Fbuffer_file_name (object);
4933 val = Ffind_operation_coding_system (4, args);
4934 if (CONSP (val) && !NILP (XCDR (val)))
4935 coding_system = XCDR (val);
4936 }
4937
4938 if (NILP (coding_system)
4939 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4940 {
4941 /* If we still have not decided a coding system, use the
4942 default value of buffer-file-coding-system. */
4943 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4944 }
4945
4946 if (!force_raw_text
4947 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4948 /* Confirm that VAL can surely encode the current region. */
4949 coding_system = call4 (Vselect_safe_coding_system_function,
4950 make_number (b), make_number (e),
4951 coding_system, Qnil);
4952
4953 if (force_raw_text)
4954 coding_system = Qraw_text;
4955 }
4956
4957 if (NILP (Fcoding_system_p (coding_system)))
4958 {
4959 /* Invalid coding system. */
4960
4961 if (!NILP (noerror))
4962 coding_system = Qraw_text;
4963 else
4964 xsignal1 (Qcoding_system_error, coding_system);
4965 }
4966 }
4967
4968 object = make_buffer_string (b, e, 0);
4969 set_buffer_internal (prev);
4970 /* Discard the unwind protect for recovering the current
4971 buffer. */
4972 specpdl_ptr--;
4973
4974 if (STRING_MULTIBYTE (object))
4975 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4976 start_byte = 0;
4977 end_byte = SBYTES (object);
4978 }
4979
4980 if (EQ (algorithm, Qmd5))
4981 {
4982 digest_size = MD5_DIGEST_SIZE;
4983 hash_func = md5_buffer;
4984 }
4985 else if (EQ (algorithm, Qsha1))
4986 {
4987 digest_size = SHA1_DIGEST_SIZE;
4988 hash_func = sha1_buffer;
4989 }
4990 else if (EQ (algorithm, Qsha224))
4991 {
4992 digest_size = SHA224_DIGEST_SIZE;
4993 hash_func = sha224_buffer;
4994 }
4995 else if (EQ (algorithm, Qsha256))
4996 {
4997 digest_size = SHA256_DIGEST_SIZE;
4998 hash_func = sha256_buffer;
4999 }
5000 else if (EQ (algorithm, Qsha384))
5001 {
5002 digest_size = SHA384_DIGEST_SIZE;
5003 hash_func = sha384_buffer;
5004 }
5005 else if (EQ (algorithm, Qsha512))
5006 {
5007 digest_size = SHA512_DIGEST_SIZE;
5008 hash_func = sha512_buffer;
5009 }
5010 else
5011 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
5012
5013 /* allocate 2 x digest_size so that it can be re-used to hold the
5014 hexified value */
5015 digest = make_uninit_string (digest_size * 2);
5016
5017 hash_func (SSDATA (object) + start_byte,
5018 end_byte - start_byte,
5019 SSDATA (digest));
5020
5021 if (NILP (binary))
5022 {
5023 unsigned char *p = SDATA (digest);
5024 for (i = digest_size - 1; i >= 0; i--)
5025 {
5026 static char const hexdigit[16] = "0123456789abcdef";
5027 int p_i = p[i];
5028 p[2 * i] = hexdigit[p_i >> 4];
5029 p[2 * i + 1] = hexdigit[p_i & 0xf];
5030 }
5031 return digest;
5032 }
5033 else
5034 return make_unibyte_string (SSDATA (digest), digest_size);
5035 }
5036
5037 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
5038 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
5039
5040 A message digest is a cryptographic checksum of a document, and the
5041 algorithm to calculate it is defined in RFC 1321.
5042
5043 The two optional arguments START and END are character positions
5044 specifying for which part of OBJECT the message digest should be
5045 computed. If nil or omitted, the digest is computed for the whole
5046 OBJECT.
5047
5048 The MD5 message digest is computed from the result of encoding the
5049 text in a coding system, not directly from the internal Emacs form of
5050 the text. The optional fourth argument CODING-SYSTEM specifies which
5051 coding system to encode the text with. It should be the same coding
5052 system that you used or will use when actually writing the text into a
5053 file.
5054
5055 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5056 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5057 system would be chosen by default for writing this text into a file.
5058
5059 If OBJECT is a string, the most preferred coding system (see the
5060 command `prefer-coding-system') is used.
5061
5062 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5063 guesswork fails. Normally, an error is signaled in such case. */)
5064 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
5065 {
5066 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
5067 }
5068
5069 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
5070 doc: /* Return the secure hash of OBJECT, a buffer or string.
5071 ALGORITHM is a symbol specifying the hash to use:
5072 md5, sha1, sha224, sha256, sha384 or sha512.
5073
5074 The two optional arguments START and END are positions specifying for
5075 which part of OBJECT to compute the hash. If nil or omitted, uses the
5076 whole OBJECT.
5077
5078 If BINARY is non-nil, returns a string in binary form. */)
5079 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
5080 {
5081 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
5082 }
5083 \f
5084 void
5085 syms_of_fns (void)
5086 {
5087 DEFSYM (Qmd5, "md5");
5088 DEFSYM (Qsha1, "sha1");
5089 DEFSYM (Qsha224, "sha224");
5090 DEFSYM (Qsha256, "sha256");
5091 DEFSYM (Qsha384, "sha384");
5092 DEFSYM (Qsha512, "sha512");
5093
5094 /* Hash table stuff. */
5095 DEFSYM (Qhash_table_p, "hash-table-p");
5096 DEFSYM (Qeq, "eq");
5097 DEFSYM (Qeql, "eql");
5098 DEFSYM (Qequal, "equal");
5099 DEFSYM (QCtest, ":test");
5100 DEFSYM (QCsize, ":size");
5101 DEFSYM (QCrehash_size, ":rehash-size");
5102 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5103 DEFSYM (QCweakness, ":weakness");
5104 DEFSYM (Qkey, "key");
5105 DEFSYM (Qvalue, "value");
5106 DEFSYM (Qhash_table_test, "hash-table-test");
5107 DEFSYM (Qkey_or_value, "key-or-value");
5108 DEFSYM (Qkey_and_value, "key-and-value");
5109
5110 defsubr (&Ssxhash);
5111 defsubr (&Smake_hash_table);
5112 defsubr (&Scopy_hash_table);
5113 defsubr (&Shash_table_count);
5114 defsubr (&Shash_table_rehash_size);
5115 defsubr (&Shash_table_rehash_threshold);
5116 defsubr (&Shash_table_size);
5117 defsubr (&Shash_table_test);
5118 defsubr (&Shash_table_weakness);
5119 defsubr (&Shash_table_p);
5120 defsubr (&Sclrhash);
5121 defsubr (&Sgethash);
5122 defsubr (&Sputhash);
5123 defsubr (&Sremhash);
5124 defsubr (&Smaphash);
5125 defsubr (&Sdefine_hash_table_test);
5126
5127 DEFSYM (Qstring_lessp, "string-lessp");
5128 DEFSYM (Qstring_collate_lessp, "string-collate-lessp");
5129 DEFSYM (Qstring_collate_equalp, "string-collate-equalp");
5130 DEFSYM (Qprovide, "provide");
5131 DEFSYM (Qrequire, "require");
5132 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5133 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5134 DEFSYM (Qwidget_type, "widget-type");
5135
5136 staticpro (&string_char_byte_cache_string);
5137 string_char_byte_cache_string = Qnil;
5138
5139 require_nesting_list = Qnil;
5140 staticpro (&require_nesting_list);
5141
5142 Fset (Qyes_or_no_p_history, Qnil);
5143
5144 DEFVAR_LISP ("features", Vfeatures,
5145 doc: /* A list of symbols which are the features of the executing Emacs.
5146 Used by `featurep' and `require', and altered by `provide'. */);
5147 Vfeatures = list1 (intern_c_string ("emacs"));
5148 DEFSYM (Qsubfeatures, "subfeatures");
5149 DEFSYM (Qfuncall, "funcall");
5150
5151 #ifdef HAVE_LANGINFO_CODESET
5152 DEFSYM (Qcodeset, "codeset");
5153 DEFSYM (Qdays, "days");
5154 DEFSYM (Qmonths, "months");
5155 DEFSYM (Qpaper, "paper");
5156 #endif /* HAVE_LANGINFO_CODESET */
5157
5158 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5159 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5160 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5161 invoked by mouse clicks and mouse menu items.
5162
5163 On some platforms, file selection dialogs are also enabled if this is
5164 non-nil. */);
5165 use_dialog_box = 1;
5166
5167 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5168 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5169 This applies to commands from menus and tool bar buttons even when
5170 they are initiated from the keyboard. If `use-dialog-box' is nil,
5171 that disables the use of a file dialog, regardless of the value of
5172 this variable. */);
5173 use_file_dialog = 1;
5174
5175 defsubr (&Sidentity);
5176 defsubr (&Srandom);
5177 defsubr (&Slength);
5178 defsubr (&Ssafe_length);
5179 defsubr (&Sstring_bytes);
5180 defsubr (&Sstring_equal);
5181 defsubr (&Scompare_strings);
5182 defsubr (&Sstring_lessp);
5183 defsubr (&Sstring_collate_lessp);
5184 defsubr (&Sstring_collate_equalp);
5185 defsubr (&Sappend);
5186 defsubr (&Sconcat);
5187 defsubr (&Svconcat);
5188 defsubr (&Scopy_sequence);
5189 defsubr (&Sstring_make_multibyte);
5190 defsubr (&Sstring_make_unibyte);
5191 defsubr (&Sstring_as_multibyte);
5192 defsubr (&Sstring_as_unibyte);
5193 defsubr (&Sstring_to_multibyte);
5194 defsubr (&Sstring_to_unibyte);
5195 defsubr (&Scopy_alist);
5196 defsubr (&Ssubstring);
5197 defsubr (&Ssubstring_no_properties);
5198 defsubr (&Snthcdr);
5199 defsubr (&Snth);
5200 defsubr (&Selt);
5201 defsubr (&Smember);
5202 defsubr (&Smemq);
5203 defsubr (&Smemql);
5204 defsubr (&Sassq);
5205 defsubr (&Sassoc);
5206 defsubr (&Srassq);
5207 defsubr (&Srassoc);
5208 defsubr (&Sdelq);
5209 defsubr (&Sdelete);
5210 defsubr (&Snreverse);
5211 defsubr (&Sreverse);
5212 defsubr (&Ssort);
5213 defsubr (&Splist_get);
5214 defsubr (&Sget);
5215 defsubr (&Splist_put);
5216 defsubr (&Sput);
5217 defsubr (&Slax_plist_get);
5218 defsubr (&Slax_plist_put);
5219 defsubr (&Seql);
5220 defsubr (&Sequal);
5221 defsubr (&Sequal_including_properties);
5222 defsubr (&Sfillarray);
5223 defsubr (&Sclear_string);
5224 defsubr (&Snconc);
5225 defsubr (&Smapcar);
5226 defsubr (&Smapc);
5227 defsubr (&Smapconcat);
5228 defsubr (&Syes_or_no_p);
5229 defsubr (&Sload_average);
5230 defsubr (&Sfeaturep);
5231 defsubr (&Srequire);
5232 defsubr (&Sprovide);
5233 defsubr (&Splist_member);
5234 defsubr (&Swidget_put);
5235 defsubr (&Swidget_get);
5236 defsubr (&Swidget_apply);
5237 defsubr (&Sbase64_encode_region);
5238 defsubr (&Sbase64_decode_region);
5239 defsubr (&Sbase64_encode_string);
5240 defsubr (&Sbase64_decode_string);
5241 defsubr (&Smd5);
5242 defsubr (&Ssecure_hash);
5243 defsubr (&Slocale_info);
5244
5245 hashtest_eq.name = Qeq;
5246 hashtest_eq.user_hash_function = Qnil;
5247 hashtest_eq.user_cmp_function = Qnil;
5248 hashtest_eq.cmpfn = 0;
5249 hashtest_eq.hashfn = hashfn_eq;
5250
5251 hashtest_eql.name = Qeql;
5252 hashtest_eql.user_hash_function = Qnil;
5253 hashtest_eql.user_cmp_function = Qnil;
5254 hashtest_eql.cmpfn = cmpfn_eql;
5255 hashtest_eql.hashfn = hashfn_eql;
5256
5257 hashtest_equal.name = Qequal;
5258 hashtest_equal.user_hash_function = Qnil;
5259 hashtest_equal.user_cmp_function = Qnil;
5260 hashtest_equal.cmpfn = cmpfn_equal;
5261 hashtest_equal.hashfn = hashfn_equal;
5262 }