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