1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2017 Free Software Foundation,
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
25 #include <filevercmp.h>
31 #include "character.h"
33 #include "composite.h"
35 #include "intervals.h"
41 # define gnutls_rnd w32_gnutls_rnd
44 static void sort_vector_copy (Lisp_Object
, ptrdiff_t,
45 Lisp_Object
*restrict
, Lisp_Object
*restrict
);
46 enum equal_kind
{ EQUAL_NO_QUIT
, EQUAL_PLAIN
, EQUAL_INCLUDING_PROPERTIES
};
47 static bool internal_equal (Lisp_Object
, Lisp_Object
,
48 enum equal_kind
, int, Lisp_Object
);
50 DEFUN ("identity", Fidentity
, Sidentity
, 1, 1, 0,
51 doc
: /* Return the argument unchanged. */
58 DEFUN ("random", Frandom
, Srandom
, 0, 1, 0,
59 doc
: /* Return a pseudo-random number.
60 All integers representable in Lisp, i.e. between `most-negative-fixnum'
61 and `most-positive-fixnum', inclusive, are equally likely.
63 With positive integer LIMIT, return random number in interval [0,LIMIT).
64 With argument t, set the random number seed from the system's entropy
65 pool if available, otherwise from less-random volatile data such as the time.
66 With a string argument, set the seed based on the string's contents.
67 Other values of LIMIT are ignored.
69 See Info node `(elisp)Random Numbers' for more details. */)
76 else if (STRINGP (limit
))
77 seed_random (SSDATA (limit
), SBYTES (limit
));
80 if (INTEGERP (limit
) && 0 < XINT (limit
))
83 /* Return the remainder, except reject the rare case where
84 get_random returns a number so close to INTMASK that the
85 remainder isn't random. */
86 EMACS_INT remainder
= val
% XINT (limit
);
87 if (val
- remainder
<= INTMASK
- XINT (limit
) + 1)
88 return make_number (remainder
);
91 return make_number (val
);
94 /* Random data-structure functions. */
96 DEFUN ("length", Flength
, Slength
, 1, 1, 0,
97 doc
: /* Return the length of vector, list or string SEQUENCE.
98 A byte-code function object is also allowed.
99 If the string contains multibyte characters, this is not necessarily
100 the number of bytes in the string; it is the number of characters.
101 To get the number of bytes, use `string-bytes'. */)
102 (register Lisp_Object sequence
)
104 register Lisp_Object val
;
106 if (STRINGP (sequence
))
107 XSETFASTINT (val
, SCHARS (sequence
));
108 else if (VECTORP (sequence
))
109 XSETFASTINT (val
, ASIZE (sequence
));
110 else if (CHAR_TABLE_P (sequence
))
111 XSETFASTINT (val
, MAX_CHAR
);
112 else if (BOOL_VECTOR_P (sequence
))
113 XSETFASTINT (val
, bool_vector_size (sequence
));
114 else if (COMPILEDP (sequence
) || RECORDP (sequence
))
115 XSETFASTINT (val
, PVSIZE (sequence
));
116 else if (CONSP (sequence
))
119 FOR_EACH_TAIL (sequence
)
121 CHECK_LIST_END (sequence
, sequence
);
122 if (MOST_POSITIVE_FIXNUM
< i
)
123 error ("List too long");
124 val
= make_number (i
);
126 else if (NILP (sequence
))
127 XSETFASTINT (val
, 0);
129 wrong_type_argument (Qsequencep
, sequence
);
134 DEFUN ("safe-length", Fsafe_length
, Ssafe_length
, 1, 1, 0,
135 doc
: /* Return the length of a list, but avoid error or infinite loop.
136 This function never gets an error. If LIST is not really a list,
137 it returns 0. If LIST is circular, it returns a finite value
138 which is at least the number of distinct elements. */)
142 FOR_EACH_TAIL_SAFE (list
)
144 return make_fixnum_or_float (len
);
147 DEFUN ("string-bytes", Fstring_bytes
, Sstring_bytes
, 1, 1, 0,
148 doc
: /* Return the number of bytes in STRING.
149 If STRING is multibyte, this may be greater than the length of STRING. */)
152 CHECK_STRING (string
);
153 return make_number (SBYTES (string
));
156 DEFUN ("string-equal", Fstring_equal
, Sstring_equal
, 2, 2, 0,
157 doc
: /* Return t if two strings have identical contents.
158 Case is significant, but text properties are ignored.
159 Symbols are also allowed; their print names are used instead. */)
160 (register Lisp_Object s1
, Lisp_Object s2
)
163 s1
= SYMBOL_NAME (s1
);
165 s2
= SYMBOL_NAME (s2
);
169 if (SCHARS (s1
) != SCHARS (s2
)
170 || SBYTES (s1
) != SBYTES (s2
)
171 || memcmp (SDATA (s1
), SDATA (s2
), SBYTES (s1
)))
176 DEFUN ("compare-strings", Fcompare_strings
, Scompare_strings
, 6, 7, 0,
177 doc
: /* Compare the contents of two strings, converting to multibyte if needed.
178 The arguments START1, END1, START2, and END2, if non-nil, are
179 positions specifying which parts of STR1 or STR2 to compare. In
180 string STR1, compare the part between START1 (inclusive) and END1
181 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
182 the string; if END1 is nil, it defaults to the length of the string.
183 Likewise, in string STR2, compare the part between START2 and END2.
184 Like in `substring', negative values are counted from the end.
186 The strings are compared by the numeric values of their characters.
187 For instance, STR1 is "less than" STR2 if its first differing
188 character has a smaller numeric value. If IGNORE-CASE is non-nil,
189 characters are converted to upper-case before comparing them. Unibyte
190 strings are converted to multibyte for comparison.
192 The value is t if the strings (or specified portions) match.
193 If string STR1 is less, the value is a negative number N;
194 - 1 - N is the number of characters that match at the beginning.
195 If string STR1 is greater, the value is a positive number N;
196 N - 1 is the number of characters that match at the beginning. */)
197 (Lisp_Object str1
, Lisp_Object start1
, Lisp_Object end1
, Lisp_Object str2
,
198 Lisp_Object start2
, Lisp_Object end2
, Lisp_Object ignore_case
)
200 ptrdiff_t from1
, to1
, from2
, to2
, i1
, i1_byte
, i2
, i2_byte
;
205 /* For backward compatibility, silently bring too-large positive end
206 values into range. */
207 if (INTEGERP (end1
) && SCHARS (str1
) < XINT (end1
))
208 end1
= make_number (SCHARS (str1
));
209 if (INTEGERP (end2
) && SCHARS (str2
) < XINT (end2
))
210 end2
= make_number (SCHARS (str2
));
212 validate_subarray (str1
, start1
, end1
, SCHARS (str1
), &from1
, &to1
);
213 validate_subarray (str2
, start2
, end2
, SCHARS (str2
), &from2
, &to2
);
218 i1_byte
= string_char_to_byte (str1
, i1
);
219 i2_byte
= string_char_to_byte (str2
, i2
);
221 while (i1
< to1
&& i2
< to2
)
223 /* When we find a mismatch, we must compare the
224 characters, not just the bytes. */
227 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1
, str1
, i1
, i1_byte
);
228 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2
, str2
, i2
, i2_byte
);
233 if (! NILP (ignore_case
))
235 c1
= XINT (Fupcase (make_number (c1
)));
236 c2
= XINT (Fupcase (make_number (c2
)));
242 /* Note that I1 has already been incremented
243 past the character that we are comparing;
244 hence we don't add or subtract 1 here. */
246 return make_number (- i1
+ from1
);
248 return make_number (i1
- from1
);
252 return make_number (i1
- from1
+ 1);
254 return make_number (- i1
+ from1
- 1);
259 DEFUN ("string-lessp", Fstring_lessp
, Sstring_lessp
, 2, 2, 0,
260 doc
: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
262 Symbols are also allowed; their print names are used instead. */)
263 (register Lisp_Object string1
, Lisp_Object string2
)
265 register ptrdiff_t end
;
266 register ptrdiff_t i1
, i1_byte
, i2
, i2_byte
;
268 if (SYMBOLP (string1
))
269 string1
= SYMBOL_NAME (string1
);
270 if (SYMBOLP (string2
))
271 string2
= SYMBOL_NAME (string2
);
272 CHECK_STRING (string1
);
273 CHECK_STRING (string2
);
275 i1
= i1_byte
= i2
= i2_byte
= 0;
277 end
= SCHARS (string1
);
278 if (end
> SCHARS (string2
))
279 end
= SCHARS (string2
);
283 /* When we find a mismatch, we must compare the
284 characters, not just the bytes. */
287 FETCH_STRING_CHAR_ADVANCE (c1
, string1
, i1
, i1_byte
);
288 FETCH_STRING_CHAR_ADVANCE (c2
, string2
, i2
, i2_byte
);
291 return c1
< c2
? Qt
: Qnil
;
293 return i1
< SCHARS (string2
) ? Qt
: Qnil
;
296 DEFUN ("string-version-lessp", Fstring_version_lessp
,
297 Sstring_version_lessp
, 2, 2, 0,
298 doc
: /* Return non-nil if S1 is less than S2, as version strings.
300 This function compares version strings S1 and S2:
301 1) By prefix lexicographically.
302 2) Then by version (similarly to version comparison of Debian's dpkg).
303 Leading zeros in version numbers are ignored.
304 3) If both prefix and version are equal, compare as ordinary strings.
306 For example, \"foo2.png\" compares less than \"foo12.png\".
308 Symbols are also allowed; their print names are used instead. */)
309 (Lisp_Object string1
, Lisp_Object string2
)
311 if (SYMBOLP (string1
))
312 string1
= SYMBOL_NAME (string1
);
313 if (SYMBOLP (string2
))
314 string2
= SYMBOL_NAME (string2
);
315 CHECK_STRING (string1
);
316 CHECK_STRING (string2
);
318 char *p1
= SSDATA (string1
);
319 char *p2
= SSDATA (string2
);
320 char *lim1
= p1
+ SBYTES (string1
);
321 char *lim2
= p2
+ SBYTES (string2
);
324 while ((cmp
= filevercmp (p1
, p2
)) == 0)
326 /* If the strings are identical through their first null bytes,
327 skip past identical prefixes and try again. */
328 ptrdiff_t size
= strlen (p1
) + 1;
332 return lim2
< p2
? Qnil
: Qt
;
337 return cmp
< 0 ? Qt
: Qnil
;
340 DEFUN ("string-collate-lessp", Fstring_collate_lessp
, Sstring_collate_lessp
, 2, 4, 0,
341 doc
: /* Return t if first arg string is less than second in collation order.
342 Symbols are also allowed; their print names are used instead.
344 This function obeys the conventions for collation order in your
345 locale settings. For example, punctuation and whitespace characters
346 might be considered less significant for sorting:
348 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
349 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
351 The optional argument LOCALE, a string, overrides the setting of your
352 current locale identifier for collation. The value is system
353 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
354 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
356 If IGNORE-CASE is non-nil, characters are converted to lower-case
357 before comparing them.
359 To emulate Unicode-compliant collation on MS-Windows systems,
360 bind `w32-collate-ignore-punctuation' to a non-nil value, since
361 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
363 If your system does not support a locale environment, this function
364 behaves like `string-lessp'. */)
365 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object locale
, Lisp_Object ignore_case
)
367 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
368 /* Check parameters. */
370 s1
= SYMBOL_NAME (s1
);
372 s2
= SYMBOL_NAME (s2
);
376 CHECK_STRING (locale
);
378 return (str_collate (s1
, s2
, locale
, ignore_case
) < 0) ? Qt
: Qnil
;
380 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
381 return Fstring_lessp (s1
, s2
);
382 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
385 DEFUN ("string-collate-equalp", Fstring_collate_equalp
, Sstring_collate_equalp
, 2, 4, 0,
386 doc
: /* Return t if two strings have identical contents.
387 Symbols are also allowed; their print names are used instead.
389 This function obeys the conventions for collation order in your locale
390 settings. For example, characters with different coding points but
391 the same meaning might be considered as equal, like different grave
392 accent Unicode characters:
394 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
397 The optional argument LOCALE, a string, overrides the setting of your
398 current locale identifier for collation. The value is system
399 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
400 while it would be \"enu_USA.1252\" on MS Windows systems.
402 If IGNORE-CASE is non-nil, characters are converted to lower-case
403 before comparing them.
405 To emulate Unicode-compliant collation on MS-Windows systems,
406 bind `w32-collate-ignore-punctuation' to a non-nil value, since
407 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
409 If your system does not support a locale environment, this function
410 behaves like `string-equal'.
412 Do NOT use this function to compare file names for equality. */)
413 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object locale
, Lisp_Object ignore_case
)
415 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
416 /* Check parameters. */
418 s1
= SYMBOL_NAME (s1
);
420 s2
= SYMBOL_NAME (s2
);
424 CHECK_STRING (locale
);
426 return (str_collate (s1
, s2
, locale
, ignore_case
) == 0) ? Qt
: Qnil
;
428 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
429 return Fstring_equal (s1
, s2
);
430 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
433 static Lisp_Object
concat (ptrdiff_t nargs
, Lisp_Object
*args
,
434 enum Lisp_Type target_type
, bool last_special
);
438 concat2 (Lisp_Object s1
, Lisp_Object s2
)
440 return concat (2, ((Lisp_Object
[]) {s1
, s2
}), Lisp_String
, 0);
445 concat3 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object s3
)
447 return concat (3, ((Lisp_Object
[]) {s1
, s2
, s3
}), Lisp_String
, 0);
450 DEFUN ("append", Fappend
, Sappend
, 0, MANY
, 0,
451 doc
: /* Concatenate all the arguments and make the result a list.
452 The result is a list whose elements are the elements of all the arguments.
453 Each argument may be a list, vector or string.
454 The last argument is not copied, just used as the tail of the new list.
455 usage: (append &rest SEQUENCES) */)
456 (ptrdiff_t nargs
, Lisp_Object
*args
)
458 return concat (nargs
, args
, Lisp_Cons
, 1);
461 DEFUN ("concat", Fconcat
, Sconcat
, 0, MANY
, 0,
462 doc
: /* Concatenate all the arguments and make the result a string.
463 The result is a string whose elements are the elements of all the arguments.
464 Each argument may be a string or a list or vector of characters (integers).
465 usage: (concat &rest SEQUENCES) */)
466 (ptrdiff_t nargs
, Lisp_Object
*args
)
468 return concat (nargs
, args
, Lisp_String
, 0);
471 DEFUN ("vconcat", Fvconcat
, Svconcat
, 0, MANY
, 0,
472 doc
: /* Concatenate all the arguments and make the result a vector.
473 The result is a vector whose elements are the elements of all the arguments.
474 Each argument may be a list, vector or string.
475 usage: (vconcat &rest SEQUENCES) */)
476 (ptrdiff_t nargs
, Lisp_Object
*args
)
478 return concat (nargs
, args
, Lisp_Vectorlike
, 0);
482 DEFUN ("copy-sequence", Fcopy_sequence
, Scopy_sequence
, 1, 1, 0,
483 doc
: /* Return a copy of a list, vector, string, char-table or record.
484 The elements of a list, vector or record are not copied; they are
485 shared with the original. */)
488 if (NILP (arg
)) return arg
;
492 return Frecord (PVSIZE (arg
), XVECTOR (arg
)->contents
);
495 if (CHAR_TABLE_P (arg
))
497 return copy_char_table (arg
);
500 if (BOOL_VECTOR_P (arg
))
502 EMACS_INT nbits
= bool_vector_size (arg
);
503 ptrdiff_t nbytes
= bool_vector_bytes (nbits
);
504 Lisp_Object val
= make_uninit_bool_vector (nbits
);
505 memcpy (bool_vector_data (val
), bool_vector_data (arg
), nbytes
);
509 if (!CONSP (arg
) && !VECTORP (arg
) && !STRINGP (arg
))
510 wrong_type_argument (Qsequencep
, arg
);
512 return concat (1, &arg
, XTYPE (arg
), 0);
515 /* This structure holds information of an argument of `concat' that is
516 a string and has text properties to be copied. */
519 ptrdiff_t argnum
; /* refer to ARGS (arguments of `concat') */
520 ptrdiff_t from
; /* refer to ARGS[argnum] (argument string) */
521 ptrdiff_t to
; /* refer to VAL (the target string) */
525 concat (ptrdiff_t nargs
, Lisp_Object
*args
,
526 enum Lisp_Type target_type
, bool last_special
)
532 ptrdiff_t toindex_byte
= 0;
533 EMACS_INT result_len
;
534 EMACS_INT result_len_byte
;
536 Lisp_Object last_tail
;
539 /* When we make a multibyte string, we can't copy text properties
540 while concatenating each string because the length of resulting
541 string can't be decided until we finish the whole concatenation.
542 So, we record strings that have text properties to be copied
543 here, and copy the text properties after the concatenation. */
544 struct textprop_rec
*textprops
= NULL
;
545 /* Number of elements in textprops. */
546 ptrdiff_t num_textprops
= 0;
551 /* In append, the last arg isn't treated like the others */
552 if (last_special
&& nargs
> 0)
555 last_tail
= args
[nargs
];
560 /* Check each argument. */
561 for (argnum
= 0; argnum
< nargs
; argnum
++)
564 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
565 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
566 wrong_type_argument (Qsequencep
, this);
569 /* Compute total length in chars of arguments in RESULT_LEN.
570 If desired output is a string, also compute length in bytes
571 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
572 whether the result should be a multibyte string. */
576 for (argnum
= 0; argnum
< nargs
; argnum
++)
580 len
= XFASTINT (Flength (this));
581 if (target_type
== Lisp_String
)
583 /* We must count the number of bytes needed in the string
584 as well as the number of characters. */
588 ptrdiff_t this_len_byte
;
590 if (VECTORP (this) || COMPILEDP (this))
591 for (i
= 0; i
< len
; i
++)
594 CHECK_CHARACTER (ch
);
596 this_len_byte
= CHAR_BYTES (c
);
597 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
599 result_len_byte
+= this_len_byte
;
600 if (! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
603 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
604 wrong_type_argument (Qintegerp
, Faref (this, make_number (0)));
605 else if (CONSP (this))
606 for (; CONSP (this); this = XCDR (this))
609 CHECK_CHARACTER (ch
);
611 this_len_byte
= CHAR_BYTES (c
);
612 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
614 result_len_byte
+= this_len_byte
;
615 if (! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
618 else if (STRINGP (this))
620 if (STRING_MULTIBYTE (this))
623 this_len_byte
= SBYTES (this);
626 this_len_byte
= count_size_as_multibyte (SDATA (this),
628 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
630 result_len_byte
+= this_len_byte
;
635 if (MOST_POSITIVE_FIXNUM
< result_len
)
636 memory_full (SIZE_MAX
);
639 if (! some_multibyte
)
640 result_len_byte
= result_len
;
642 /* Create the output object. */
643 if (target_type
== Lisp_Cons
)
644 val
= Fmake_list (make_number (result_len
), Qnil
);
645 else if (target_type
== Lisp_Vectorlike
)
646 val
= Fmake_vector (make_number (result_len
), Qnil
);
647 else if (some_multibyte
)
648 val
= make_uninit_multibyte_string (result_len
, result_len_byte
);
650 val
= make_uninit_string (result_len
);
652 /* In `append', if all but last arg are nil, return last arg. */
653 if (target_type
== Lisp_Cons
&& EQ (val
, Qnil
))
656 /* Copy the contents of the args into the result. */
658 tail
= val
, toindex
= -1; /* -1 in toindex is flag we are making a list */
660 toindex
= 0, toindex_byte
= 0;
664 SAFE_NALLOCA (textprops
, 1, nargs
);
666 for (argnum
= 0; argnum
< nargs
; argnum
++)
669 ptrdiff_t thisleni
= 0;
670 register ptrdiff_t thisindex
= 0;
671 register ptrdiff_t thisindex_byte
= 0;
675 thislen
= Flength (this), thisleni
= XINT (thislen
);
677 /* Between strings of the same kind, copy fast. */
678 if (STRINGP (this) && STRINGP (val
)
679 && STRING_MULTIBYTE (this) == some_multibyte
)
681 ptrdiff_t thislen_byte
= SBYTES (this);
683 memcpy (SDATA (val
) + toindex_byte
, SDATA (this), SBYTES (this));
684 if (string_intervals (this))
686 textprops
[num_textprops
].argnum
= argnum
;
687 textprops
[num_textprops
].from
= 0;
688 textprops
[num_textprops
++].to
= toindex
;
690 toindex_byte
+= thislen_byte
;
693 /* Copy a single-byte string to a multibyte string. */
694 else if (STRINGP (this) && STRINGP (val
))
696 if (string_intervals (this))
698 textprops
[num_textprops
].argnum
= argnum
;
699 textprops
[num_textprops
].from
= 0;
700 textprops
[num_textprops
++].to
= toindex
;
702 toindex_byte
+= copy_text (SDATA (this),
703 SDATA (val
) + toindex_byte
,
704 SCHARS (this), 0, 1);
708 /* Copy element by element. */
711 register Lisp_Object elt
;
713 /* Fetch next element of `this' arg into `elt', or break if
714 `this' is exhausted. */
715 if (NILP (this)) break;
717 elt
= XCAR (this), this = XCDR (this);
718 else if (thisindex
>= thisleni
)
720 else if (STRINGP (this))
723 if (STRING_MULTIBYTE (this))
724 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c
, this,
729 c
= SREF (this, thisindex
); thisindex
++;
730 if (some_multibyte
&& !ASCII_CHAR_P (c
))
731 c
= BYTE8_TO_CHAR (c
);
733 XSETFASTINT (elt
, c
);
735 else if (BOOL_VECTOR_P (this))
737 elt
= bool_vector_ref (this, thisindex
);
742 elt
= AREF (this, thisindex
);
746 /* Store this element into the result. */
753 else if (VECTORP (val
))
755 ASET (val
, toindex
, elt
);
761 CHECK_CHARACTER (elt
);
764 toindex_byte
+= CHAR_STRING (c
, SDATA (val
) + toindex_byte
);
766 SSET (val
, toindex_byte
++, c
);
772 XSETCDR (prev
, last_tail
);
774 if (num_textprops
> 0)
777 ptrdiff_t last_to_end
= -1;
779 for (argnum
= 0; argnum
< num_textprops
; argnum
++)
781 this = args
[textprops
[argnum
].argnum
];
782 props
= text_property_list (this,
784 make_number (SCHARS (this)),
786 /* If successive arguments have properties, be sure that the
787 value of `composition' property be the copy. */
788 if (last_to_end
== textprops
[argnum
].to
)
789 make_composition_value_copy (props
);
790 add_text_properties_from_list (val
, props
,
791 make_number (textprops
[argnum
].to
));
792 last_to_end
= textprops
[argnum
].to
+ SCHARS (this);
800 static Lisp_Object string_char_byte_cache_string
;
801 static ptrdiff_t string_char_byte_cache_charpos
;
802 static ptrdiff_t string_char_byte_cache_bytepos
;
805 clear_string_char_byte_cache (void)
807 string_char_byte_cache_string
= Qnil
;
810 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
813 string_char_to_byte (Lisp_Object string
, ptrdiff_t char_index
)
816 ptrdiff_t best_below
, best_below_byte
;
817 ptrdiff_t best_above
, best_above_byte
;
819 best_below
= best_below_byte
= 0;
820 best_above
= SCHARS (string
);
821 best_above_byte
= SBYTES (string
);
822 if (best_above
== best_above_byte
)
825 if (EQ (string
, string_char_byte_cache_string
))
827 if (string_char_byte_cache_charpos
< char_index
)
829 best_below
= string_char_byte_cache_charpos
;
830 best_below_byte
= string_char_byte_cache_bytepos
;
834 best_above
= string_char_byte_cache_charpos
;
835 best_above_byte
= string_char_byte_cache_bytepos
;
839 if (char_index
- best_below
< best_above
- char_index
)
841 unsigned char *p
= SDATA (string
) + best_below_byte
;
843 while (best_below
< char_index
)
845 p
+= BYTES_BY_CHAR_HEAD (*p
);
848 i_byte
= p
- SDATA (string
);
852 unsigned char *p
= SDATA (string
) + best_above_byte
;
854 while (best_above
> char_index
)
857 while (!CHAR_HEAD_P (*p
)) p
--;
860 i_byte
= p
- SDATA (string
);
863 string_char_byte_cache_bytepos
= i_byte
;
864 string_char_byte_cache_charpos
= char_index
;
865 string_char_byte_cache_string
= string
;
870 /* Return the character index corresponding to BYTE_INDEX in STRING. */
873 string_byte_to_char (Lisp_Object string
, ptrdiff_t byte_index
)
876 ptrdiff_t best_below
, best_below_byte
;
877 ptrdiff_t best_above
, best_above_byte
;
879 best_below
= best_below_byte
= 0;
880 best_above
= SCHARS (string
);
881 best_above_byte
= SBYTES (string
);
882 if (best_above
== best_above_byte
)
885 if (EQ (string
, string_char_byte_cache_string
))
887 if (string_char_byte_cache_bytepos
< byte_index
)
889 best_below
= string_char_byte_cache_charpos
;
890 best_below_byte
= string_char_byte_cache_bytepos
;
894 best_above
= string_char_byte_cache_charpos
;
895 best_above_byte
= string_char_byte_cache_bytepos
;
899 if (byte_index
- best_below_byte
< best_above_byte
- byte_index
)
901 unsigned char *p
= SDATA (string
) + best_below_byte
;
902 unsigned char *pend
= SDATA (string
) + byte_index
;
906 p
+= BYTES_BY_CHAR_HEAD (*p
);
910 i_byte
= p
- SDATA (string
);
914 unsigned char *p
= SDATA (string
) + best_above_byte
;
915 unsigned char *pbeg
= SDATA (string
) + byte_index
;
920 while (!CHAR_HEAD_P (*p
)) p
--;
924 i_byte
= p
- SDATA (string
);
927 string_char_byte_cache_bytepos
= i_byte
;
928 string_char_byte_cache_charpos
= i
;
929 string_char_byte_cache_string
= string
;
934 /* Convert STRING to a multibyte string. */
937 string_make_multibyte (Lisp_Object string
)
944 if (STRING_MULTIBYTE (string
))
947 nbytes
= count_size_as_multibyte (SDATA (string
),
949 /* If all the chars are ASCII, they won't need any more bytes
950 once converted. In that case, we can return STRING itself. */
951 if (nbytes
== SBYTES (string
))
954 buf
= SAFE_ALLOCA (nbytes
);
955 copy_text (SDATA (string
), buf
, SBYTES (string
),
958 ret
= make_multibyte_string ((char *) buf
, SCHARS (string
), nbytes
);
965 /* Convert STRING (if unibyte) to a multibyte string without changing
966 the number of characters. Characters 0200 trough 0237 are
967 converted to eight-bit characters. */
970 string_to_multibyte (Lisp_Object string
)
977 if (STRING_MULTIBYTE (string
))
980 nbytes
= count_size_as_multibyte (SDATA (string
), SBYTES (string
));
981 /* If all the chars are ASCII, they won't need any more bytes once
983 if (nbytes
== SBYTES (string
))
984 return make_multibyte_string (SSDATA (string
), nbytes
, nbytes
);
986 buf
= SAFE_ALLOCA (nbytes
);
987 memcpy (buf
, SDATA (string
), SBYTES (string
));
988 str_to_multibyte (buf
, nbytes
, SBYTES (string
));
990 ret
= make_multibyte_string ((char *) buf
, SCHARS (string
), nbytes
);
997 /* Convert STRING to a single-byte string. */
1000 string_make_unibyte (Lisp_Object string
)
1007 if (! STRING_MULTIBYTE (string
))
1010 nchars
= SCHARS (string
);
1012 buf
= SAFE_ALLOCA (nchars
);
1013 copy_text (SDATA (string
), buf
, SBYTES (string
),
1016 ret
= make_unibyte_string ((char *) buf
, nchars
);
1022 DEFUN ("string-make-multibyte", Fstring_make_multibyte
, Sstring_make_multibyte
,
1024 doc
: /* Return the multibyte equivalent of STRING.
1025 If STRING is unibyte and contains non-ASCII characters, the function
1026 `unibyte-char-to-multibyte' is used to convert each unibyte character
1027 to a multibyte character. In this case, the returned string is a
1028 newly created string with no text properties. If STRING is multibyte
1029 or entirely ASCII, it is returned unchanged. In particular, when
1030 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1031 \(When the characters are all ASCII, Emacs primitives will treat the
1032 string the same way whether it is unibyte or multibyte.) */)
1033 (Lisp_Object string
)
1035 CHECK_STRING (string
);
1037 return string_make_multibyte (string
);
1040 DEFUN ("string-make-unibyte", Fstring_make_unibyte
, Sstring_make_unibyte
,
1042 doc
: /* Return the unibyte equivalent of STRING.
1043 Multibyte character codes are converted to unibyte according to
1044 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1045 If the lookup in the translation table fails, this function takes just
1046 the low 8 bits of each character. */)
1047 (Lisp_Object string
)
1049 CHECK_STRING (string
);
1051 return string_make_unibyte (string
);
1054 DEFUN ("string-as-unibyte", Fstring_as_unibyte
, Sstring_as_unibyte
,
1056 doc
: /* Return a unibyte string with the same individual bytes as STRING.
1057 If STRING is unibyte, the result is STRING itself.
1058 Otherwise it is a newly created string, with no text properties.
1059 If STRING is multibyte and contains a character of charset
1060 `eight-bit', it is converted to the corresponding single byte. */)
1061 (Lisp_Object string
)
1063 CHECK_STRING (string
);
1065 if (STRING_MULTIBYTE (string
))
1067 unsigned char *str
= (unsigned char *) xlispstrdup (string
);
1068 ptrdiff_t bytes
= str_as_unibyte (str
, SBYTES (string
));
1070 string
= make_unibyte_string ((char *) str
, bytes
);
1076 DEFUN ("string-as-multibyte", Fstring_as_multibyte
, Sstring_as_multibyte
,
1078 doc
: /* Return a multibyte string with the same individual bytes as STRING.
1079 If STRING is multibyte, the result is STRING itself.
1080 Otherwise it is a newly created string, with no text properties.
1082 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1083 part of a correct utf-8 sequence), it is converted to the corresponding
1084 multibyte character of charset `eight-bit'.
1085 See also `string-to-multibyte'.
1087 Beware, this often doesn't really do what you think it does.
1088 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1089 If you're not sure, whether to use `string-as-multibyte' or
1090 `string-to-multibyte', use `string-to-multibyte'. */)
1091 (Lisp_Object string
)
1093 CHECK_STRING (string
);
1095 if (! STRING_MULTIBYTE (string
))
1097 Lisp_Object new_string
;
1098 ptrdiff_t nchars
, nbytes
;
1100 parse_str_as_multibyte (SDATA (string
),
1103 new_string
= make_uninit_multibyte_string (nchars
, nbytes
);
1104 memcpy (SDATA (new_string
), SDATA (string
), SBYTES (string
));
1105 if (nbytes
!= SBYTES (string
))
1106 str_as_multibyte (SDATA (new_string
), nbytes
,
1107 SBYTES (string
), NULL
);
1108 string
= new_string
;
1109 set_string_intervals (string
, NULL
);
1114 DEFUN ("string-to-multibyte", Fstring_to_multibyte
, Sstring_to_multibyte
,
1116 doc
: /* Return a multibyte string with the same individual chars as STRING.
1117 If STRING is multibyte, the result is STRING itself.
1118 Otherwise it is a newly created string, with no text properties.
1120 If STRING is unibyte and contains an 8-bit byte, it is converted to
1121 the corresponding multibyte character of charset `eight-bit'.
1123 This differs from `string-as-multibyte' by converting each byte of a correct
1124 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1125 correct sequence. */)
1126 (Lisp_Object string
)
1128 CHECK_STRING (string
);
1130 return string_to_multibyte (string
);
1133 DEFUN ("string-to-unibyte", Fstring_to_unibyte
, Sstring_to_unibyte
,
1135 doc
: /* Return a unibyte string with the same individual chars as STRING.
1136 If STRING is unibyte, the result is STRING itself.
1137 Otherwise it is a newly created string, with no text properties,
1138 where each `eight-bit' character is converted to the corresponding byte.
1139 If STRING contains a non-ASCII, non-`eight-bit' character,
1140 an error is signaled. */)
1141 (Lisp_Object string
)
1143 CHECK_STRING (string
);
1145 if (STRING_MULTIBYTE (string
))
1147 ptrdiff_t chars
= SCHARS (string
);
1148 unsigned char *str
= xmalloc (chars
);
1149 ptrdiff_t converted
= str_to_unibyte (SDATA (string
), str
, chars
);
1151 if (converted
< chars
)
1152 error ("Can't convert the %"pD
"dth character to unibyte", converted
);
1153 string
= make_unibyte_string ((char *) str
, chars
);
1160 DEFUN ("copy-alist", Fcopy_alist
, Scopy_alist
, 1, 1, 0,
1161 doc
: /* Return a copy of ALIST.
1162 This is an alist which represents the same mapping from objects to objects,
1163 but does not share the alist structure with ALIST.
1164 The objects mapped (cars and cdrs of elements of the alist)
1165 are shared, however.
1166 Elements of ALIST that are not conses are also shared. */)
1171 alist
= concat (1, &alist
, Lisp_Cons
, false);
1172 for (Lisp_Object tem
= alist
; !NILP (tem
); tem
= XCDR (tem
))
1174 Lisp_Object car
= XCAR (tem
);
1176 XSETCAR (tem
, Fcons (XCAR (car
), XCDR (car
)));
1181 /* Check that ARRAY can have a valid subarray [FROM..TO),
1182 given that its size is SIZE.
1183 If FROM is nil, use 0; if TO is nil, use SIZE.
1184 Count negative values backwards from the end.
1185 Set *IFROM and *ITO to the two indexes used. */
1188 validate_subarray (Lisp_Object array
, Lisp_Object from
, Lisp_Object to
,
1189 ptrdiff_t size
, ptrdiff_t *ifrom
, ptrdiff_t *ito
)
1193 if (INTEGERP (from
))
1199 else if (NILP (from
))
1202 wrong_type_argument (Qintegerp
, from
);
1213 wrong_type_argument (Qintegerp
, to
);
1215 if (! (0 <= f
&& f
<= t
&& t
<= size
))
1216 args_out_of_range_3 (array
, from
, to
);
1222 DEFUN ("substring", Fsubstring
, Ssubstring
, 1, 3, 0,
1223 doc
: /* Return a new string whose contents are a substring of STRING.
1224 The returned string consists of the characters between index FROM
1225 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1226 zero-indexed: 0 means the first character of STRING. Negative values
1227 are counted from the end of STRING. If TO is nil, the substring runs
1228 to the end of STRING.
1230 The STRING argument may also be a vector. In that case, the return
1231 value is a new vector that contains the elements between index FROM
1232 \(inclusive) and index TO (exclusive) of that vector argument.
1234 With one argument, just copy STRING (with properties, if any). */)
1235 (Lisp_Object string
, Lisp_Object from
, Lisp_Object to
)
1238 ptrdiff_t size
, ifrom
, ito
;
1240 size
= CHECK_VECTOR_OR_STRING (string
);
1241 validate_subarray (string
, from
, to
, size
, &ifrom
, &ito
);
1243 if (STRINGP (string
))
1246 = !ifrom
? 0 : string_char_to_byte (string
, ifrom
);
1248 = ito
== size
? SBYTES (string
) : string_char_to_byte (string
, ito
);
1249 res
= make_specified_string (SSDATA (string
) + from_byte
,
1250 ito
- ifrom
, to_byte
- from_byte
,
1251 STRING_MULTIBYTE (string
));
1252 copy_text_properties (make_number (ifrom
), make_number (ito
),
1253 string
, make_number (0), res
, Qnil
);
1256 res
= Fvector (ito
- ifrom
, aref_addr (string
, ifrom
));
1262 DEFUN ("substring-no-properties", Fsubstring_no_properties
, Ssubstring_no_properties
, 1, 3, 0,
1263 doc
: /* Return a substring of STRING, without text properties.
1264 It starts at index FROM and ends before TO.
1265 TO may be nil or omitted; then the substring runs to the end of STRING.
1266 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1267 If FROM or TO is negative, it counts from the end.
1269 With one argument, just copy STRING without its properties. */)
1270 (Lisp_Object string
, register Lisp_Object from
, Lisp_Object to
)
1272 ptrdiff_t from_char
, to_char
, from_byte
, to_byte
, size
;
1274 CHECK_STRING (string
);
1276 size
= SCHARS (string
);
1277 validate_subarray (string
, from
, to
, size
, &from_char
, &to_char
);
1279 from_byte
= !from_char
? 0 : string_char_to_byte (string
, from_char
);
1281 to_char
== size
? SBYTES (string
) : string_char_to_byte (string
, to_char
);
1282 return make_specified_string (SSDATA (string
) + from_byte
,
1283 to_char
- from_char
, to_byte
- from_byte
,
1284 STRING_MULTIBYTE (string
));
1287 /* Extract a substring of STRING, giving start and end positions
1288 both in characters and in bytes. */
1291 substring_both (Lisp_Object string
, ptrdiff_t from
, ptrdiff_t from_byte
,
1292 ptrdiff_t to
, ptrdiff_t to_byte
)
1295 ptrdiff_t size
= CHECK_VECTOR_OR_STRING (string
);
1297 if (!(0 <= from
&& from
<= to
&& to
<= size
))
1298 args_out_of_range_3 (string
, make_number (from
), make_number (to
));
1300 if (STRINGP (string
))
1302 res
= make_specified_string (SSDATA (string
) + from_byte
,
1303 to
- from
, to_byte
- from_byte
,
1304 STRING_MULTIBYTE (string
));
1305 copy_text_properties (make_number (from
), make_number (to
),
1306 string
, make_number (0), res
, Qnil
);
1309 res
= Fvector (to
- from
, aref_addr (string
, from
));
1314 DEFUN ("nthcdr", Fnthcdr
, Snthcdr
, 2, 2, 0,
1315 doc
: /* Take cdr N times on LIST, return the result. */)
1316 (Lisp_Object n
, Lisp_Object list
)
1319 Lisp_Object tail
= list
;
1320 for (EMACS_INT num
= XINT (n
); 0 < num
; num
--)
1324 CHECK_LIST_END (tail
, list
);
1333 DEFUN ("nth", Fnth
, Snth
, 2, 2, 0,
1334 doc
: /* Return the Nth element of LIST.
1335 N counts from zero. If LIST is not that long, nil is returned. */)
1336 (Lisp_Object n
, Lisp_Object list
)
1338 return Fcar (Fnthcdr (n
, list
));
1341 DEFUN ("elt", Felt
, Selt
, 2, 2, 0,
1342 doc
: /* Return element of SEQUENCE at index N. */)
1343 (register Lisp_Object sequence
, Lisp_Object n
)
1346 if (CONSP (sequence
) || NILP (sequence
))
1347 return Fcar (Fnthcdr (n
, sequence
));
1349 /* Faref signals a "not array" error, so check here. */
1350 CHECK_ARRAY (sequence
, Qsequencep
);
1351 return Faref (sequence
, n
);
1354 DEFUN ("member", Fmember
, Smember
, 2, 2, 0,
1355 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1356 The value is actually the tail of LIST whose car is ELT. */)
1357 (Lisp_Object elt
, Lisp_Object list
)
1359 Lisp_Object tail
= list
;
1360 FOR_EACH_TAIL (tail
)
1361 if (! NILP (Fequal (elt
, XCAR (tail
))))
1363 CHECK_LIST_END (tail
, list
);
1367 DEFUN ("memq", Fmemq
, Smemq
, 2, 2, 0,
1368 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1369 The value is actually the tail of LIST whose car is ELT. */)
1370 (Lisp_Object elt
, Lisp_Object list
)
1372 Lisp_Object tail
= list
;
1373 FOR_EACH_TAIL (tail
)
1374 if (EQ (XCAR (tail
), elt
))
1376 CHECK_LIST_END (tail
, list
);
1380 DEFUN ("memql", Fmemql
, Smemql
, 2, 2, 0,
1381 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1382 The value is actually the tail of LIST whose car is ELT. */)
1383 (Lisp_Object elt
, Lisp_Object list
)
1386 return Fmemq (elt
, list
);
1388 Lisp_Object tail
= list
;
1389 FOR_EACH_TAIL (tail
)
1391 Lisp_Object tem
= XCAR (tail
);
1392 if (FLOATP (tem
) && equal_no_quit (elt
, tem
))
1395 CHECK_LIST_END (tail
, list
);
1399 DEFUN ("assq", Fassq
, Sassq
, 2, 2, 0,
1400 doc
: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1401 The value is actually the first element of LIST whose car is KEY.
1402 Elements of LIST that are not conses are ignored. */)
1403 (Lisp_Object key
, Lisp_Object list
)
1405 Lisp_Object tail
= list
;
1406 FOR_EACH_TAIL (tail
)
1407 if (CONSP (XCAR (tail
)) && EQ (XCAR (XCAR (tail
)), key
))
1409 CHECK_LIST_END (tail
, list
);
1413 /* Like Fassq but never report an error and do not allow quits.
1414 Use only on objects known to be non-circular lists. */
1417 assq_no_quit (Lisp_Object key
, Lisp_Object list
)
1419 for (; ! NILP (list
); list
= XCDR (list
))
1420 if (CONSP (XCAR (list
)) && EQ (XCAR (XCAR (list
)), key
))
1425 DEFUN ("assoc", Fassoc
, Sassoc
, 2, 3, 0,
1426 doc
: /* Return non-nil if KEY is equal to the car of an element of LIST.
1427 The value is actually the first element of LIST whose car equals KEY.
1429 Equality is defined by TESTFN if non-nil or by `equal' if nil. */)
1430 (Lisp_Object key
, Lisp_Object list
, Lisp_Object testfn
)
1432 Lisp_Object tail
= list
;
1433 FOR_EACH_TAIL (tail
)
1435 Lisp_Object car
= XCAR (tail
);
1438 ? (EQ (XCAR (car
), key
) || !NILP (Fequal
1440 : !NILP (call2 (testfn
, XCAR (car
), key
))))
1443 CHECK_LIST_END (tail
, list
);
1447 /* Like Fassoc but never report an error and do not allow quits.
1448 Use only on keys and lists known to be non-circular, and on keys
1449 that are not too deep and are not window configurations. */
1452 assoc_no_quit (Lisp_Object key
, Lisp_Object list
)
1454 for (; ! NILP (list
); list
= XCDR (list
))
1456 Lisp_Object car
= XCAR (list
);
1458 && (EQ (XCAR (car
), key
) || equal_no_quit (XCAR (car
), key
)))
1464 DEFUN ("rassq", Frassq
, Srassq
, 2, 2, 0,
1465 doc
: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1466 The value is actually the first element of LIST whose cdr is KEY. */)
1467 (Lisp_Object key
, Lisp_Object list
)
1469 Lisp_Object tail
= list
;
1470 FOR_EACH_TAIL (tail
)
1471 if (CONSP (XCAR (tail
)) && EQ (XCDR (XCAR (tail
)), key
))
1473 CHECK_LIST_END (tail
, list
);
1477 DEFUN ("rassoc", Frassoc
, Srassoc
, 2, 2, 0,
1478 doc
: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1479 The value is actually the first element of LIST whose cdr equals KEY. */)
1480 (Lisp_Object key
, Lisp_Object list
)
1482 Lisp_Object tail
= list
;
1483 FOR_EACH_TAIL (tail
)
1485 Lisp_Object car
= XCAR (tail
);
1487 && (EQ (XCDR (car
), key
) || !NILP (Fequal (XCDR (car
), key
))))
1490 CHECK_LIST_END (tail
, list
);
1494 DEFUN ("delq", Fdelq
, Sdelq
, 2, 2, 0,
1495 doc
: /* Delete members of LIST which are `eq' to ELT, and return the result.
1496 More precisely, this function skips any members `eq' to ELT at the
1497 front of LIST, then removes members `eq' to ELT from the remaining
1498 sublist by modifying its list structure, then returns the resulting
1501 Write `(setq foo (delq element foo))' to be sure of correctly changing
1502 the value of a list `foo'. See also `remq', which does not modify the
1504 (Lisp_Object elt
, Lisp_Object list
)
1506 Lisp_Object prev
= Qnil
, tail
= list
;
1508 FOR_EACH_TAIL (tail
)
1510 Lisp_Object tem
= XCAR (tail
);
1516 Fsetcdr (prev
, XCDR (tail
));
1521 CHECK_LIST_END (tail
, list
);
1525 DEFUN ("delete", Fdelete
, Sdelete
, 2, 2, 0,
1526 doc
: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1527 SEQ must be a sequence (i.e. a list, a vector, or a string).
1528 The return value is a sequence of the same type.
1530 If SEQ is a list, this behaves like `delq', except that it compares
1531 with `equal' instead of `eq'. In particular, it may remove elements
1532 by altering the list structure.
1534 If SEQ is not a list, deletion is never performed destructively;
1535 instead this function creates and returns a new vector or string.
1537 Write `(setq foo (delete element foo))' to be sure of correctly
1538 changing the value of a sequence `foo'. */)
1539 (Lisp_Object elt
, Lisp_Object seq
)
1545 for (i
= n
= 0; i
< ASIZE (seq
); ++i
)
1546 if (NILP (Fequal (AREF (seq
, i
), elt
)))
1549 if (n
!= ASIZE (seq
))
1551 struct Lisp_Vector
*p
= allocate_vector (n
);
1553 for (i
= n
= 0; i
< ASIZE (seq
); ++i
)
1554 if (NILP (Fequal (AREF (seq
, i
), elt
)))
1555 p
->contents
[n
++] = AREF (seq
, i
);
1557 XSETVECTOR (seq
, p
);
1560 else if (STRINGP (seq
))
1562 ptrdiff_t i
, ibyte
, nchars
, nbytes
, cbytes
;
1565 for (i
= nchars
= nbytes
= ibyte
= 0;
1567 ++i
, ibyte
+= cbytes
)
1569 if (STRING_MULTIBYTE (seq
))
1571 c
= STRING_CHAR (SDATA (seq
) + ibyte
);
1572 cbytes
= CHAR_BYTES (c
);
1580 if (!INTEGERP (elt
) || c
!= XINT (elt
))
1587 if (nchars
!= SCHARS (seq
))
1591 tem
= make_uninit_multibyte_string (nchars
, nbytes
);
1592 if (!STRING_MULTIBYTE (seq
))
1593 STRING_SET_UNIBYTE (tem
);
1595 for (i
= nchars
= nbytes
= ibyte
= 0;
1597 ++i
, ibyte
+= cbytes
)
1599 if (STRING_MULTIBYTE (seq
))
1601 c
= STRING_CHAR (SDATA (seq
) + ibyte
);
1602 cbytes
= CHAR_BYTES (c
);
1610 if (!INTEGERP (elt
) || c
!= XINT (elt
))
1612 unsigned char *from
= SDATA (seq
) + ibyte
;
1613 unsigned char *to
= SDATA (tem
) + nbytes
;
1619 for (n
= cbytes
; n
--; )
1629 Lisp_Object prev
= Qnil
, tail
= seq
;
1631 FOR_EACH_TAIL (tail
)
1633 if (!NILP (Fequal (elt
, XCAR (tail
))))
1638 Fsetcdr (prev
, XCDR (tail
));
1643 CHECK_LIST_END (tail
, seq
);
1649 DEFUN ("nreverse", Fnreverse
, Snreverse
, 1, 1, 0,
1650 doc
: /* Reverse order of items in a list, vector or string SEQ.
1651 If SEQ is a list, it should be nil-terminated.
1652 This function may destructively modify SEQ to produce the value. */)
1657 else if (STRINGP (seq
))
1658 return Freverse (seq
);
1659 else if (CONSP (seq
))
1661 Lisp_Object prev
, tail
, next
;
1663 for (prev
= Qnil
, tail
= seq
; CONSP (tail
); tail
= next
)
1666 /* If SEQ contains a cycle, attempting to reverse it
1667 in-place will inevitably come back to SEQ. */
1669 circular_list (seq
);
1670 Fsetcdr (tail
, prev
);
1673 CHECK_LIST_END (tail
, seq
);
1676 else if (VECTORP (seq
))
1678 ptrdiff_t i
, size
= ASIZE (seq
);
1680 for (i
= 0; i
< size
/ 2; i
++)
1682 Lisp_Object tem
= AREF (seq
, i
);
1683 ASET (seq
, i
, AREF (seq
, size
- i
- 1));
1684 ASET (seq
, size
- i
- 1, tem
);
1687 else if (BOOL_VECTOR_P (seq
))
1689 ptrdiff_t i
, size
= bool_vector_size (seq
);
1691 for (i
= 0; i
< size
/ 2; i
++)
1693 bool tem
= bool_vector_bitref (seq
, i
);
1694 bool_vector_set (seq
, i
, bool_vector_bitref (seq
, size
- i
- 1));
1695 bool_vector_set (seq
, size
- i
- 1, tem
);
1699 wrong_type_argument (Qarrayp
, seq
);
1703 DEFUN ("reverse", Freverse
, Sreverse
, 1, 1, 0,
1704 doc
: /* Return the reversed copy of list, vector, or string SEQ.
1705 See also the function `nreverse', which is used more often. */)
1712 else if (CONSP (seq
))
1716 new = Fcons (XCAR (seq
), new);
1717 CHECK_LIST_END (seq
, seq
);
1719 else if (VECTORP (seq
))
1721 ptrdiff_t i
, size
= ASIZE (seq
);
1723 new = make_uninit_vector (size
);
1724 for (i
= 0; i
< size
; i
++)
1725 ASET (new, i
, AREF (seq
, size
- i
- 1));
1727 else if (BOOL_VECTOR_P (seq
))
1730 EMACS_INT nbits
= bool_vector_size (seq
);
1732 new = make_uninit_bool_vector (nbits
);
1733 for (i
= 0; i
< nbits
; i
++)
1734 bool_vector_set (new, i
, bool_vector_bitref (seq
, nbits
- i
- 1));
1736 else if (STRINGP (seq
))
1738 ptrdiff_t size
= SCHARS (seq
), bytes
= SBYTES (seq
);
1744 new = make_uninit_string (size
);
1745 for (i
= 0; i
< size
; i
++)
1746 SSET (new, i
, SREF (seq
, size
- i
- 1));
1750 unsigned char *p
, *q
;
1752 new = make_uninit_multibyte_string (size
, bytes
);
1753 p
= SDATA (seq
), q
= SDATA (new) + bytes
;
1754 while (q
> SDATA (new))
1758 ch
= STRING_CHAR_AND_LENGTH (p
, len
);
1760 CHAR_STRING (ch
, q
);
1765 wrong_type_argument (Qsequencep
, seq
);
1769 /* Sort LIST using PREDICATE, preserving original order of elements
1770 considered as equal. */
1773 sort_list (Lisp_Object list
, Lisp_Object predicate
)
1775 Lisp_Object front
, back
;
1776 Lisp_Object len
, tem
;
1780 len
= Flength (list
);
1781 length
= XINT (len
);
1785 XSETINT (len
, (length
/ 2) - 1);
1786 tem
= Fnthcdr (len
, list
);
1788 Fsetcdr (tem
, Qnil
);
1790 front
= Fsort (front
, predicate
);
1791 back
= Fsort (back
, predicate
);
1792 return merge (front
, back
, predicate
);
1795 /* Using PRED to compare, return whether A and B are in order.
1796 Compare stably when A appeared before B in the input. */
1798 inorder (Lisp_Object pred
, Lisp_Object a
, Lisp_Object b
)
1800 return NILP (call2 (pred
, b
, a
));
1803 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1804 into DEST. Argument arrays must be nonempty and must not overlap,
1805 except that B might be the last part of DEST. */
1807 merge_vectors (Lisp_Object pred
,
1808 ptrdiff_t alen
, Lisp_Object
const a
[restrict
VLA_ELEMS (alen
)],
1809 ptrdiff_t blen
, Lisp_Object
const b
[VLA_ELEMS (blen
)],
1810 Lisp_Object dest
[VLA_ELEMS (alen
+ blen
)])
1812 eassume (0 < alen
&& 0 < blen
);
1813 Lisp_Object
const *alim
= a
+ alen
;
1814 Lisp_Object
const *blim
= b
+ blen
;
1818 if (inorder (pred
, a
[0], b
[0]))
1824 memcpy (dest
, b
, (blim
- b
) * sizeof *dest
);
1833 memcpy (dest
, a
, (alim
- a
) * sizeof *dest
);
1840 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1841 temporary storage. LEN must be at least 2. */
1843 sort_vector_inplace (Lisp_Object pred
, ptrdiff_t len
,
1844 Lisp_Object vec
[restrict
VLA_ELEMS (len
)],
1845 Lisp_Object tmp
[restrict
VLA_ELEMS (len
>> 1)])
1848 ptrdiff_t halflen
= len
>> 1;
1849 sort_vector_copy (pred
, halflen
, vec
, tmp
);
1850 if (1 < len
- halflen
)
1851 sort_vector_inplace (pred
, len
- halflen
, vec
+ halflen
, vec
);
1852 merge_vectors (pred
, halflen
, tmp
, len
- halflen
, vec
+ halflen
, vec
);
1855 /* Using PRED to compare, sort from LEN-length SRC into DST.
1856 Len must be positive. */
1858 sort_vector_copy (Lisp_Object pred
, ptrdiff_t len
,
1859 Lisp_Object src
[restrict
VLA_ELEMS (len
)],
1860 Lisp_Object dest
[restrict
VLA_ELEMS (len
)])
1863 ptrdiff_t halflen
= len
>> 1;
1869 sort_vector_inplace (pred
, halflen
, src
, dest
);
1870 if (1 < len
- halflen
)
1871 sort_vector_inplace (pred
, len
- halflen
, src
+ halflen
, dest
);
1872 merge_vectors (pred
, halflen
, src
, len
- halflen
, src
+ halflen
, dest
);
1876 /* Sort VECTOR in place using PREDICATE, preserving original order of
1877 elements considered as equal. */
1880 sort_vector (Lisp_Object vector
, Lisp_Object predicate
)
1882 ptrdiff_t len
= ASIZE (vector
);
1885 ptrdiff_t halflen
= len
>> 1;
1888 SAFE_ALLOCA_LISP (tmp
, halflen
);
1889 for (ptrdiff_t i
= 0; i
< halflen
; i
++)
1890 tmp
[i
] = make_number (0);
1891 sort_vector_inplace (predicate
, len
, XVECTOR (vector
)->contents
, tmp
);
1895 DEFUN ("sort", Fsort
, Ssort
, 2, 2, 0,
1896 doc
: /* Sort SEQ, stably, comparing elements using PREDICATE.
1897 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
1898 modified by side effects. PREDICATE is called with two elements of
1899 SEQ, and should return non-nil if the first element should sort before
1901 (Lisp_Object seq
, Lisp_Object predicate
)
1904 seq
= sort_list (seq
, predicate
);
1905 else if (VECTORP (seq
))
1906 sort_vector (seq
, predicate
);
1907 else if (!NILP (seq
))
1908 wrong_type_argument (Qsequencep
, seq
);
1913 merge (Lisp_Object org_l1
, Lisp_Object org_l2
, Lisp_Object pred
)
1915 Lisp_Object l1
= org_l1
;
1916 Lisp_Object l2
= org_l2
;
1917 Lisp_Object tail
= Qnil
;
1918 Lisp_Object value
= Qnil
;
1938 if (inorder (pred
, Fcar (l1
), Fcar (l2
)))
1953 Fsetcdr (tail
, tem
);
1959 /* This does not check for quits. That is safe since it must terminate. */
1961 DEFUN ("plist-get", Fplist_get
, Splist_get
, 2, 2, 0,
1962 doc
: /* Extract a value from a property list.
1963 PLIST is a property list, which is a list of the form
1964 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1965 corresponding to the given PROP, or nil if PROP is not one of the
1966 properties on the list. This function never signals an error. */)
1967 (Lisp_Object plist
, Lisp_Object prop
)
1969 Lisp_Object tail
= plist
;
1970 FOR_EACH_TAIL_SAFE (tail
)
1972 if (! CONSP (XCDR (tail
)))
1974 if (EQ (prop
, XCAR (tail
)))
1975 return XCAR (XCDR (tail
));
1977 if (EQ (tail
, li
.tortoise
))
1984 DEFUN ("get", Fget
, Sget
, 2, 2, 0,
1985 doc
: /* Return the value of SYMBOL's PROPNAME property.
1986 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1987 (Lisp_Object symbol
, Lisp_Object propname
)
1989 CHECK_SYMBOL (symbol
);
1990 Lisp_Object propval
= Fplist_get (CDR (Fassq (symbol
, Voverriding_plist_environment
)),
1992 if (!NILP (propval
))
1994 return Fplist_get (XSYMBOL (symbol
)->plist
, propname
);
1997 DEFUN ("plist-put", Fplist_put
, Splist_put
, 3, 3, 0,
1998 doc
: /* Change value in PLIST of PROP to VAL.
1999 PLIST is a property list, which is a list of the form
2000 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2001 If PROP is already a property on the list, its value is set to VAL,
2002 otherwise the new PROP VAL pair is added. The new plist is returned;
2003 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2004 The PLIST is modified by side effects. */)
2005 (Lisp_Object plist
, Lisp_Object prop
, Lisp_Object val
)
2007 Lisp_Object prev
= Qnil
, tail
= plist
;
2008 FOR_EACH_TAIL (tail
)
2010 if (! CONSP (XCDR (tail
)))
2013 if (EQ (prop
, XCAR (tail
)))
2015 Fsetcar (XCDR (tail
), val
);
2021 if (EQ (tail
, li
.tortoise
))
2022 circular_list (plist
);
2024 CHECK_TYPE (NILP (tail
), Qplistp
, plist
);
2026 = Fcons (prop
, Fcons (val
, NILP (prev
) ? plist
: XCDR (XCDR (prev
))));
2029 Fsetcdr (XCDR (prev
), newcell
);
2033 DEFUN ("put", Fput
, Sput
, 3, 3, 0,
2034 doc
: /* Store SYMBOL's PROPNAME property with value VALUE.
2035 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2036 (Lisp_Object symbol
, Lisp_Object propname
, Lisp_Object value
)
2038 CHECK_SYMBOL (symbol
);
2040 (symbol
, Fplist_put (XSYMBOL (symbol
)->plist
, propname
, value
));
2044 DEFUN ("lax-plist-get", Flax_plist_get
, Slax_plist_get
, 2, 2, 0,
2045 doc
: /* Extract a value from a property list, comparing with `equal'.
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
2049 one of the properties on the list. */)
2050 (Lisp_Object plist
, Lisp_Object prop
)
2052 Lisp_Object tail
= plist
;
2053 FOR_EACH_TAIL (tail
)
2055 if (! CONSP (XCDR (tail
)))
2057 if (! NILP (Fequal (prop
, XCAR (tail
))))
2058 return XCAR (XCDR (tail
));
2060 if (EQ (tail
, li
.tortoise
))
2061 circular_list (plist
);
2064 CHECK_TYPE (NILP (tail
), Qplistp
, plist
);
2069 DEFUN ("lax-plist-put", Flax_plist_put
, Slax_plist_put
, 3, 3, 0,
2070 doc
: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2071 PLIST is a property list, which is a list of the form
2072 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2073 If PROP is already a property on the list, its value is set to VAL,
2074 otherwise the new PROP VAL pair is added. The new plist is returned;
2075 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2076 The PLIST is modified by side effects. */)
2077 (Lisp_Object plist
, Lisp_Object prop
, Lisp_Object val
)
2079 Lisp_Object prev
= Qnil
, tail
= plist
;
2080 FOR_EACH_TAIL (tail
)
2082 if (! CONSP (XCDR (tail
)))
2085 if (! NILP (Fequal (prop
, XCAR (tail
))))
2087 Fsetcar (XCDR (tail
), val
);
2093 if (EQ (tail
, li
.tortoise
))
2094 circular_list (plist
);
2096 CHECK_TYPE (NILP (tail
), Qplistp
, plist
);
2097 Lisp_Object newcell
= list2 (prop
, val
);
2100 Fsetcdr (XCDR (prev
), newcell
);
2104 DEFUN ("eql", Feql
, Seql
, 2, 2, 0,
2105 doc
: /* Return t if the two args are the same Lisp object.
2106 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2107 (Lisp_Object obj1
, Lisp_Object obj2
)
2110 return equal_no_quit (obj1
, obj2
) ? Qt
: Qnil
;
2112 return EQ (obj1
, obj2
) ? Qt
: Qnil
;
2115 DEFUN ("equal", Fequal
, Sequal
, 2, 2, 0,
2116 doc
: /* Return t if two Lisp objects have similar structure and contents.
2117 They must have the same data type.
2118 Conses are compared by comparing the cars and the cdrs.
2119 Vectors and strings are compared element by element.
2120 Numbers are compared by value, but integers cannot equal floats.
2121 (Use `=' if you want integers and floats to be able to be equal.)
2122 Symbols must match exactly. */)
2123 (Lisp_Object o1
, Lisp_Object o2
)
2125 return internal_equal (o1
, o2
, EQUAL_PLAIN
, 0, Qnil
) ? Qt
: Qnil
;
2128 DEFUN ("equal-including-properties", Fequal_including_properties
, Sequal_including_properties
, 2, 2, 0,
2129 doc
: /* Return t if two Lisp objects have similar structure and contents.
2130 This is like `equal' except that it compares the text properties
2131 of strings. (`equal' ignores text properties.) */)
2132 (Lisp_Object o1
, Lisp_Object o2
)
2134 return (internal_equal (o1
, o2
, EQUAL_INCLUDING_PROPERTIES
, 0, Qnil
)
2138 /* Return true if O1 and O2 are equal. Do not quit or check for cycles.
2139 Use this only on arguments that are cycle-free and not too large and
2140 are not window configurations. */
2143 equal_no_quit (Lisp_Object o1
, Lisp_Object o2
)
2145 return internal_equal (o1
, o2
, EQUAL_NO_QUIT
, 0, Qnil
);
2148 /* Return true if O1 and O2 are equal. EQUAL_KIND specifies what kind
2149 of equality test to use: if it is EQUAL_NO_QUIT, do not check for
2150 cycles or large arguments or quits; if EQUAL_PLAIN, do ordinary
2151 Lisp equality; and if EQUAL_INCLUDING_PROPERTIES, do
2152 equal-including-properties.
2154 If DEPTH is the current depth of recursion; signal an error if it
2155 gets too deep. HT is a hash table used to detect cycles; if nil,
2156 it has not been allocated yet. But ignore the last two arguments
2157 if EQUAL_KIND == EQUAL_NO_QUIT. */
2160 internal_equal (Lisp_Object o1
, Lisp_Object o2
, enum equal_kind equal_kind
,
2161 int depth
, Lisp_Object ht
)
2166 eassert (equal_kind
!= EQUAL_NO_QUIT
);
2168 error ("Stack overflow in equal");
2170 ht
= CALLN (Fmake_hash_table
, QCtest
, Qeq
);
2173 case Lisp_Cons
: case Lisp_Misc
: case Lisp_Vectorlike
:
2175 struct Lisp_Hash_Table
*h
= XHASH_TABLE (ht
);
2177 ptrdiff_t i
= hash_lookup (h
, o1
, &hash
);
2179 { /* `o1' was seen already. */
2180 Lisp_Object o2s
= HASH_VALUE (h
, i
);
2181 if (!NILP (Fmemq (o2
, o2s
)))
2184 set_hash_value_slot (h
, i
, Fcons (o2
, o2s
));
2187 hash_put (h
, o1
, Fcons (o2
, Qnil
), hash
);
2195 if (XTYPE (o1
) != XTYPE (o2
))
2202 double d1
= XFLOAT_DATA (o1
);
2203 double d2
= XFLOAT_DATA (o2
);
2204 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2205 though they are not =. */
2206 return d1
== d2
|| (d1
!= d1
&& d2
!= d2
);
2210 if (equal_kind
== EQUAL_NO_QUIT
)
2211 for (; CONSP (o1
); o1
= XCDR (o1
))
2215 if (! equal_no_quit (XCAR (o1
), XCAR (o2
)))
2218 if (EQ (XCDR (o1
), o2
))
2226 if (! internal_equal (XCAR (o1
), XCAR (o2
),
2227 equal_kind
, depth
+ 1, ht
))
2230 if (EQ (XCDR (o1
), o2
))
2237 if (XMISCTYPE (o1
) != XMISCTYPE (o2
))
2241 if (!internal_equal (OVERLAY_START (o1
), OVERLAY_START (o2
),
2242 equal_kind
, depth
+ 1, ht
)
2243 || !internal_equal (OVERLAY_END (o1
), OVERLAY_END (o2
),
2244 equal_kind
, depth
+ 1, ht
))
2246 o1
= XOVERLAY (o1
)->plist
;
2247 o2
= XOVERLAY (o2
)->plist
;
2253 return (XMARKER (o1
)->buffer
== XMARKER (o2
)->buffer
2254 && (XMARKER (o1
)->buffer
== 0
2255 || XMARKER (o1
)->bytepos
== XMARKER (o2
)->bytepos
));
2259 case Lisp_Vectorlike
:
2262 ptrdiff_t size
= ASIZE (o1
);
2263 /* Pseudovectors have the type encoded in the size field, so this test
2264 actually checks that the objects have the same type as well as the
2266 if (ASIZE (o2
) != size
)
2268 /* Boolvectors are compared much like strings. */
2269 if (BOOL_VECTOR_P (o1
))
2271 EMACS_INT size
= bool_vector_size (o1
);
2272 if (size
!= bool_vector_size (o2
))
2274 if (memcmp (bool_vector_data (o1
), bool_vector_data (o2
),
2275 bool_vector_bytes (size
)))
2279 if (WINDOW_CONFIGURATIONP (o1
))
2281 eassert (equal_kind
!= EQUAL_NO_QUIT
);
2282 return compare_window_configurations (o1
, o2
, false);
2285 /* Aside from them, only true vectors, char-tables, compiled
2286 functions, and fonts (font-spec, font-entity, font-object)
2287 are sensible to compare, so eliminate the others now. */
2288 if (size
& PSEUDOVECTOR_FLAG
)
2290 if (((size
& PVEC_TYPE_MASK
) >> PSEUDOVECTOR_AREA_BITS
)
2293 size
&= PSEUDOVECTOR_SIZE_MASK
;
2295 for (i
= 0; i
< size
; i
++)
2300 if (!internal_equal (v1
, v2
, equal_kind
, depth
+ 1, ht
))
2308 if (SCHARS (o1
) != SCHARS (o2
))
2310 if (SBYTES (o1
) != SBYTES (o2
))
2312 if (memcmp (SDATA (o1
), SDATA (o2
), SBYTES (o1
)))
2314 if (equal_kind
== EQUAL_INCLUDING_PROPERTIES
2315 && !compare_string_intervals (o1
, o2
))
2327 DEFUN ("fillarray", Ffillarray
, Sfillarray
, 2, 2, 0,
2328 doc
: /* Store each element of ARRAY with ITEM.
2329 ARRAY is a vector, string, char-table, or bool-vector. */)
2330 (Lisp_Object array
, Lisp_Object item
)
2332 register ptrdiff_t size
, idx
;
2334 if (VECTORP (array
))
2335 for (idx
= 0, size
= ASIZE (array
); idx
< size
; idx
++)
2336 ASET (array
, idx
, item
);
2337 else if (CHAR_TABLE_P (array
))
2341 for (i
= 0; i
< (1 << CHARTAB_SIZE_BITS_0
); i
++)
2342 set_char_table_contents (array
, i
, item
);
2343 set_char_table_defalt (array
, item
);
2345 else if (STRINGP (array
))
2347 register unsigned char *p
= SDATA (array
);
2349 CHECK_CHARACTER (item
);
2350 charval
= XFASTINT (item
);
2351 size
= SCHARS (array
);
2352 if (STRING_MULTIBYTE (array
))
2354 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2355 int len
= CHAR_STRING (charval
, str
);
2356 ptrdiff_t size_byte
= SBYTES (array
);
2359 if (INT_MULTIPLY_WRAPV (size
, len
, &product
) || product
!= size_byte
)
2360 error ("Attempt to change byte length of a string");
2361 for (idx
= 0; idx
< size_byte
; idx
++)
2362 *p
++ = str
[idx
% len
];
2365 for (idx
= 0; idx
< size
; idx
++)
2368 else if (BOOL_VECTOR_P (array
))
2369 return bool_vector_fill (array
, item
);
2371 wrong_type_argument (Qarrayp
, array
);
2375 DEFUN ("clear-string", Fclear_string
, Sclear_string
,
2377 doc
: /* Clear the contents of STRING.
2378 This makes STRING unibyte and may change its length. */)
2379 (Lisp_Object string
)
2382 CHECK_STRING (string
);
2383 len
= SBYTES (string
);
2384 memset (SDATA (string
), 0, len
);
2385 STRING_SET_CHARS (string
, len
);
2386 STRING_SET_UNIBYTE (string
);
2392 nconc2 (Lisp_Object s1
, Lisp_Object s2
)
2394 return CALLN (Fnconc
, s1
, s2
);
2397 DEFUN ("nconc", Fnconc
, Snconc
, 0, MANY
, 0,
2398 doc
: /* Concatenate any number of lists by altering them.
2399 Only the last argument is not altered, and need not be a list.
2400 usage: (nconc &rest LISTS) */)
2401 (ptrdiff_t nargs
, Lisp_Object
*args
)
2403 Lisp_Object val
= Qnil
;
2405 for (ptrdiff_t argnum
= 0; argnum
< nargs
; argnum
++)
2407 Lisp_Object tem
= args
[argnum
];
2408 if (NILP (tem
)) continue;
2413 if (argnum
+ 1 == nargs
) break;
2421 tem
= args
[argnum
+ 1];
2422 Fsetcdr (tail
, tem
);
2424 args
[argnum
+ 1] = tail
;
2430 /* This is the guts of all mapping functions.
2431 Apply FN to each element of SEQ, one by one, storing the results
2432 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2433 length of VALS, which should also be the length of SEQ. Return the
2434 number of results; although this is normally LENI, it can be less
2435 if SEQ is made shorter as a side effect of FN. */
2438 mapcar1 (EMACS_INT leni
, Lisp_Object
*vals
, Lisp_Object fn
, Lisp_Object seq
)
2440 Lisp_Object tail
, dummy
;
2443 if (VECTORP (seq
) || COMPILEDP (seq
))
2445 for (i
= 0; i
< leni
; i
++)
2447 dummy
= call1 (fn
, AREF (seq
, i
));
2452 else if (BOOL_VECTOR_P (seq
))
2454 for (i
= 0; i
< leni
; i
++)
2456 dummy
= call1 (fn
, bool_vector_ref (seq
, i
));
2461 else if (STRINGP (seq
))
2465 for (i
= 0, i_byte
= 0; i
< leni
;)
2468 ptrdiff_t i_before
= i
;
2470 FETCH_STRING_CHAR_ADVANCE (c
, seq
, i
, i_byte
);
2471 XSETFASTINT (dummy
, c
);
2472 dummy
= call1 (fn
, dummy
);
2474 vals
[i_before
] = dummy
;
2477 else /* Must be a list, since Flength did not get an error */
2480 for (i
= 0; i
< leni
; i
++)
2484 dummy
= call1 (fn
, XCAR (tail
));
2494 DEFUN ("mapconcat", Fmapconcat
, Smapconcat
, 3, 3, 0,
2495 doc
: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2496 In between each pair of results, stick in SEPARATOR. Thus, " " as
2497 SEPARATOR results in spaces between the values returned by FUNCTION.
2498 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2499 (Lisp_Object function
, Lisp_Object sequence
, Lisp_Object separator
)
2502 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2503 if (CHAR_TABLE_P (sequence
))
2504 wrong_type_argument (Qlistp
, sequence
);
2505 EMACS_INT args_alloc
= 2 * leni
- 1;
2507 return empty_unibyte_string
;
2509 SAFE_ALLOCA_LISP (args
, args_alloc
);
2510 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2511 ptrdiff_t nargs
= 2 * nmapped
- 1;
2513 for (ptrdiff_t i
= nmapped
- 1; i
> 0; i
--)
2514 args
[i
+ i
] = args
[i
];
2516 for (ptrdiff_t i
= 1; i
< nargs
; i
+= 2)
2517 args
[i
] = separator
;
2519 Lisp_Object ret
= Fconcat (nargs
, args
);
2524 DEFUN ("mapcar", Fmapcar
, Smapcar
, 2, 2, 0,
2525 doc
: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2526 The result is a list just as long as SEQUENCE.
2527 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2528 (Lisp_Object function
, Lisp_Object sequence
)
2531 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2532 if (CHAR_TABLE_P (sequence
))
2533 wrong_type_argument (Qlistp
, sequence
);
2535 SAFE_ALLOCA_LISP (args
, leni
);
2536 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2537 Lisp_Object ret
= Flist (nmapped
, args
);
2542 DEFUN ("mapc", Fmapc
, Smapc
, 2, 2, 0,
2543 doc
: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2544 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2545 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2546 (Lisp_Object function
, Lisp_Object sequence
)
2548 register EMACS_INT leni
;
2550 leni
= XFASTINT (Flength (sequence
));
2551 if (CHAR_TABLE_P (sequence
))
2552 wrong_type_argument (Qlistp
, sequence
);
2553 mapcar1 (leni
, 0, function
, sequence
);
2558 DEFUN ("mapcan", Fmapcan
, Smapcan
, 2, 2, 0,
2559 doc
: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2560 the results by altering them (using `nconc').
2561 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2562 (Lisp_Object function
, Lisp_Object sequence
)
2565 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2566 if (CHAR_TABLE_P (sequence
))
2567 wrong_type_argument (Qlistp
, sequence
);
2569 SAFE_ALLOCA_LISP (args
, leni
);
2570 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2571 Lisp_Object ret
= Fnconc (nmapped
, args
);
2576 /* This is how C code calls `yes-or-no-p' and allows the user
2580 do_yes_or_no_p (Lisp_Object prompt
)
2582 return call1 (intern ("yes-or-no-p"), prompt
);
2585 DEFUN ("yes-or-no-p", Fyes_or_no_p
, Syes_or_no_p
, 1, 1, 0,
2586 doc
: /* Ask user a yes-or-no question.
2587 Return t if answer is yes, and nil if the answer is no.
2588 PROMPT is the string to display to ask the question. It should end in
2589 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2591 The user must confirm the answer with RET, and can edit it until it
2594 If dialog boxes are supported, a dialog box will be used
2595 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2596 (Lisp_Object prompt
)
2600 CHECK_STRING (prompt
);
2602 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
2603 && use_dialog_box
&& ! NILP (last_input_event
))
2605 Lisp_Object pane
, menu
, obj
;
2606 redisplay_preserve_echo_area (4);
2607 pane
= list2 (Fcons (build_string ("Yes"), Qt
),
2608 Fcons (build_string ("No"), Qnil
));
2609 menu
= Fcons (prompt
, pane
);
2610 obj
= Fx_popup_dialog (Qt
, menu
, Qnil
);
2614 AUTO_STRING (yes_or_no
, "(yes or no) ");
2615 prompt
= CALLN (Fconcat
, prompt
, yes_or_no
);
2619 ans
= Fdowncase (Fread_from_minibuffer (prompt
, Qnil
, Qnil
, Qnil
,
2620 Qyes_or_no_p_history
, Qnil
,
2622 if (SCHARS (ans
) == 3 && !strcmp (SSDATA (ans
), "yes"))
2624 if (SCHARS (ans
) == 2 && !strcmp (SSDATA (ans
), "no"))
2629 message1 ("Please answer yes or no.");
2630 Fsleep_for (make_number (2), Qnil
);
2634 DEFUN ("load-average", Fload_average
, Sload_average
, 0, 1, 0,
2635 doc
: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2637 Each of the three load averages is multiplied by 100, then converted
2640 When USE-FLOATS is non-nil, floats will be used instead of integers.
2641 These floats are not multiplied by 100.
2643 If the 5-minute or 15-minute load averages are not available, return a
2644 shortened list, containing only those averages which are available.
2646 An error is thrown if the load average can't be obtained. In some
2647 cases making it work would require Emacs being installed setuid or
2648 setgid so that it can read kernel information, and that usually isn't
2650 (Lisp_Object use_floats
)
2653 int loads
= getloadavg (load_ave
, 3);
2654 Lisp_Object ret
= Qnil
;
2657 error ("load-average not implemented for this operating system");
2661 Lisp_Object load
= (NILP (use_floats
)
2662 ? make_number (100.0 * load_ave
[loads
])
2663 : make_float (load_ave
[loads
]));
2664 ret
= Fcons (load
, ret
);
2670 DEFUN ("featurep", Ffeaturep
, Sfeaturep
, 1, 2, 0,
2671 doc
: /* Return t if FEATURE is present in this Emacs.
2673 Use this to conditionalize execution of lisp code based on the
2674 presence or absence of Emacs or environment extensions.
2675 Use `provide' to declare that a feature is available. This function
2676 looks at the value of the variable `features'. The optional argument
2677 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2678 (Lisp_Object feature
, Lisp_Object subfeature
)
2680 register Lisp_Object tem
;
2681 CHECK_SYMBOL (feature
);
2682 tem
= Fmemq (feature
, Vfeatures
);
2683 if (!NILP (tem
) && !NILP (subfeature
))
2684 tem
= Fmember (subfeature
, Fget (feature
, Qsubfeatures
));
2685 return (NILP (tem
)) ? Qnil
: Qt
;
2688 DEFUN ("provide", Fprovide
, Sprovide
, 1, 2, 0,
2689 doc
: /* Announce that FEATURE is a feature of the current Emacs.
2690 The optional argument SUBFEATURES should be a list of symbols listing
2691 particular subfeatures supported in this version of FEATURE. */)
2692 (Lisp_Object feature
, Lisp_Object subfeatures
)
2694 register Lisp_Object tem
;
2695 CHECK_SYMBOL (feature
);
2696 CHECK_LIST (subfeatures
);
2697 if (!NILP (Vautoload_queue
))
2698 Vautoload_queue
= Fcons (Fcons (make_number (0), Vfeatures
),
2700 tem
= Fmemq (feature
, Vfeatures
);
2702 Vfeatures
= Fcons (feature
, Vfeatures
);
2703 if (!NILP (subfeatures
))
2704 Fput (feature
, Qsubfeatures
, subfeatures
);
2705 LOADHIST_ATTACH (Fcons (Qprovide
, feature
));
2707 /* Run any load-hooks for this file. */
2708 tem
= Fassq (feature
, Vafter_load_alist
);
2710 Fmapc (Qfuncall
, XCDR (tem
));
2715 /* `require' and its subroutines. */
2717 /* List of features currently being require'd, innermost first. */
2719 static Lisp_Object require_nesting_list
;
2722 require_unwind (Lisp_Object old_value
)
2724 require_nesting_list
= old_value
;
2727 DEFUN ("require", Frequire
, Srequire
, 1, 3, 0,
2728 doc
: /* If feature FEATURE is not loaded, load it from FILENAME.
2729 If FEATURE is not a member of the list `features', then the feature is
2730 not loaded; so load the file FILENAME.
2732 If FILENAME is omitted, the printname of FEATURE is used as the file
2733 name, and `load' will try to load this name appended with the suffix
2734 `.elc', `.el', or the system-dependent suffix for dynamic module
2735 files, in that order. The name without appended suffix will not be
2736 used. See `get-load-suffixes' for the complete list of suffixes.
2738 The directories in `load-path' are searched when trying to find the
2741 If the optional third argument NOERROR is non-nil, then return nil if
2742 the file is not found instead of signaling an error. Normally the
2743 return value is FEATURE.
2745 The normal messages at start and end of loading FILENAME are
2747 (Lisp_Object feature
, Lisp_Object filename
, Lisp_Object noerror
)
2750 bool from_file
= load_in_progress
;
2752 CHECK_SYMBOL (feature
);
2754 /* Record the presence of `require' in this file
2755 even if the feature specified is already loaded.
2756 But not more than once in any file,
2757 and not when we aren't loading or reading from a file. */
2759 for (tem
= Vcurrent_load_list
; CONSP (tem
); tem
= XCDR (tem
))
2760 if (NILP (XCDR (tem
)) && STRINGP (XCAR (tem
)))
2765 tem
= Fcons (Qrequire
, feature
);
2766 if (NILP (Fmember (tem
, Vcurrent_load_list
)))
2767 LOADHIST_ATTACH (tem
);
2769 tem
= Fmemq (feature
, Vfeatures
);
2773 ptrdiff_t count
= SPECPDL_INDEX ();
2776 /* This is to make sure that loadup.el gives a clear picture
2777 of what files are preloaded and when. */
2778 if (! NILP (Vpurify_flag
))
2779 error ("(require %s) while preparing to dump",
2780 SDATA (SYMBOL_NAME (feature
)));
2782 /* A certain amount of recursive `require' is legitimate,
2783 but if we require the same feature recursively 3 times,
2785 tem
= require_nesting_list
;
2786 while (! NILP (tem
))
2788 if (! NILP (Fequal (feature
, XCAR (tem
))))
2793 error ("Recursive `require' for feature `%s'",
2794 SDATA (SYMBOL_NAME (feature
)));
2796 /* Update the list for any nested `require's that occur. */
2797 record_unwind_protect (require_unwind
, require_nesting_list
);
2798 require_nesting_list
= Fcons (feature
, require_nesting_list
);
2800 /* Value saved here is to be restored into Vautoload_queue */
2801 record_unwind_protect (un_autoload
, Vautoload_queue
);
2802 Vautoload_queue
= Qt
;
2804 /* Load the file. */
2805 tem
= Fload (NILP (filename
) ? Fsymbol_name (feature
) : filename
,
2806 noerror
, Qt
, Qnil
, (NILP (filename
) ? Qt
: Qnil
));
2808 /* If load failed entirely, return nil. */
2810 return unbind_to (count
, Qnil
);
2812 tem
= Fmemq (feature
, Vfeatures
);
2815 unsigned char *tem2
= SDATA (SYMBOL_NAME (feature
));
2816 Lisp_Object tem3
= Fcar (Fcar (Vload_history
));
2819 error ("Required feature `%s' was not provided", tem2
);
2821 /* Cf autoload-do-load. */
2822 error ("Loading file %s failed to provide feature `%s'",
2823 SDATA (tem3
), tem2
);
2826 /* Once loading finishes, don't undo it. */
2827 Vautoload_queue
= Qt
;
2828 feature
= unbind_to (count
, feature
);
2834 /* Primitives for work of the "widget" library.
2835 In an ideal world, this section would not have been necessary.
2836 However, lisp function calls being as slow as they are, it turns
2837 out that some functions in the widget library (wid-edit.el) are the
2838 bottleneck of Widget operation. Here is their translation to C,
2839 for the sole reason of efficiency. */
2841 DEFUN ("plist-member", Fplist_member
, Splist_member
, 2, 2, 0,
2842 doc
: /* Return non-nil if PLIST has the property PROP.
2843 PLIST is a property list, which is a list of the form
2844 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2845 Unlike `plist-get', this allows you to distinguish between a missing
2846 property and a property with the value nil.
2847 The value is actually the tail of PLIST whose car is PROP. */)
2848 (Lisp_Object plist
, Lisp_Object prop
)
2850 Lisp_Object tail
= plist
;
2851 FOR_EACH_TAIL (tail
)
2853 if (EQ (XCAR (tail
), prop
))
2858 if (EQ (tail
, li
.tortoise
))
2859 circular_list (tail
);
2861 CHECK_TYPE (NILP (tail
), Qplistp
, plist
);
2865 DEFUN ("widget-put", Fwidget_put
, Swidget_put
, 3, 3, 0,
2866 doc
: /* In WIDGET, set PROPERTY to VALUE.
2867 The value can later be retrieved with `widget-get'. */)
2868 (Lisp_Object widget
, Lisp_Object property
, Lisp_Object value
)
2870 CHECK_CONS (widget
);
2871 XSETCDR (widget
, Fplist_put (XCDR (widget
), property
, value
));
2875 DEFUN ("widget-get", Fwidget_get
, Swidget_get
, 2, 2, 0,
2876 doc
: /* In WIDGET, get the value of PROPERTY.
2877 The value could either be specified when the widget was created, or
2878 later with `widget-put'. */)
2879 (Lisp_Object widget
, Lisp_Object property
)
2887 CHECK_CONS (widget
);
2888 tmp
= Fplist_member (XCDR (widget
), property
);
2894 tmp
= XCAR (widget
);
2897 widget
= Fget (tmp
, Qwidget_type
);
2901 DEFUN ("widget-apply", Fwidget_apply
, Swidget_apply
, 2, MANY
, 0,
2902 doc
: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2903 ARGS are passed as extra arguments to the function.
2904 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2905 (ptrdiff_t nargs
, Lisp_Object
*args
)
2907 Lisp_Object widget
= args
[0];
2908 Lisp_Object property
= args
[1];
2909 Lisp_Object propval
= Fwidget_get (widget
, property
);
2910 Lisp_Object trailing_args
= Flist (nargs
- 2, args
+ 2);
2911 Lisp_Object result
= CALLN (Fapply
, propval
, widget
, trailing_args
);
2915 #ifdef HAVE_LANGINFO_CODESET
2916 #include <langinfo.h>
2919 DEFUN ("locale-info", Flocale_info
, Slocale_info
, 1, 1, 0,
2920 doc
: /* Access locale data ITEM for the current C locale, if available.
2921 ITEM should be one of the following:
2923 `codeset', returning the character set as a string (locale item CODESET);
2925 `days', returning a 7-element vector of day names (locale items DAY_n);
2927 `months', returning a 12-element vector of month names (locale items MON_n);
2929 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2930 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2932 If the system can't provide such information through a call to
2933 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2935 See also Info node `(libc)Locales'.
2937 The data read from the system are decoded using `locale-coding-system'. */)
2941 #ifdef HAVE_LANGINFO_CODESET
2942 if (EQ (item
, Qcodeset
))
2944 str
= nl_langinfo (CODESET
);
2945 return build_string (str
);
2948 else if (EQ (item
, Qdays
)) /* e.g. for calendar-day-name-array */
2950 Lisp_Object v
= Fmake_vector (make_number (7), Qnil
);
2951 const int days
[7] = {DAY_1
, DAY_2
, DAY_3
, DAY_4
, DAY_5
, DAY_6
, DAY_7
};
2953 synchronize_system_time_locale ();
2954 for (i
= 0; i
< 7; i
++)
2956 str
= nl_langinfo (days
[i
]);
2957 AUTO_STRING (val
, str
);
2958 /* Fixme: Is this coding system necessarily right, even if
2959 it is consistent with CODESET? If not, what to do? */
2960 ASET (v
, i
, code_convert_string_norecord (val
, Vlocale_coding_system
,
2967 else if (EQ (item
, Qmonths
)) /* e.g. for calendar-month-name-array */
2969 Lisp_Object v
= Fmake_vector (make_number (12), Qnil
);
2970 const int months
[12] = {MON_1
, MON_2
, MON_3
, MON_4
, MON_5
, MON_6
, MON_7
,
2971 MON_8
, MON_9
, MON_10
, MON_11
, MON_12
};
2973 synchronize_system_time_locale ();
2974 for (i
= 0; i
< 12; i
++)
2976 str
= nl_langinfo (months
[i
]);
2977 AUTO_STRING (val
, str
);
2978 ASET (v
, i
, code_convert_string_norecord (val
, Vlocale_coding_system
,
2984 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2985 but is in the locale files. This could be used by ps-print. */
2987 else if (EQ (item
, Qpaper
))
2988 return list2i (nl_langinfo (PAPER_WIDTH
), nl_langinfo (PAPER_HEIGHT
));
2989 #endif /* PAPER_WIDTH */
2990 #endif /* HAVE_LANGINFO_CODESET*/
2994 /* base64 encode/decode functions (RFC 2045).
2995 Based on code from GNU recode. */
2997 #define MIME_LINE_LENGTH 76
2999 #define IS_ASCII(Character) \
3001 #define IS_BASE64(Character) \
3002 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3003 #define IS_BASE64_IGNORABLE(Character) \
3004 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3005 || (Character) == '\f' || (Character) == '\r')
3007 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3008 character or return retval if there are no characters left to
3010 #define READ_QUADRUPLET_BYTE(retval) \
3015 if (nchars_return) \
3016 *nchars_return = nchars; \
3021 while (IS_BASE64_IGNORABLE (c))
3023 /* Table of characters coding the 64 values. */
3024 static const char base64_value_to_char
[64] =
3026 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3027 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3028 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3029 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3030 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3031 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3032 '8', '9', '+', '/' /* 60-63 */
3035 /* Table of base64 values for first 128 characters. */
3036 static const short base64_char_to_value
[128] =
3038 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3039 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3040 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3041 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3042 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3043 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3044 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3045 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3046 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3047 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3048 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3049 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3050 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3053 /* The following diagram shows the logical steps by which three octets
3054 get transformed into four base64 characters.
3056 .--------. .--------. .--------.
3057 |aaaaaabb| |bbbbcccc| |ccdddddd|
3058 `--------' `--------' `--------'
3060 .--------+--------+--------+--------.
3061 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3062 `--------+--------+--------+--------'
3064 .--------+--------+--------+--------.
3065 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3066 `--------+--------+--------+--------'
3068 The octets are divided into 6 bit chunks, which are then encoded into
3069 base64 characters. */
3072 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3073 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3076 DEFUN ("base64-encode-region", Fbase64_encode_region
, Sbase64_encode_region
,
3078 doc
: /* Base64-encode the region between BEG and END.
3079 Return the length of the encoded text.
3080 Optional third argument NO-LINE-BREAK means do not break long lines
3081 into shorter lines. */)
3082 (Lisp_Object beg
, Lisp_Object end
, Lisp_Object no_line_break
)
3085 ptrdiff_t allength
, length
;
3086 ptrdiff_t ibeg
, iend
, encoded_length
;
3087 ptrdiff_t old_pos
= PT
;
3090 validate_region (&beg
, &end
);
3092 ibeg
= CHAR_TO_BYTE (XFASTINT (beg
));
3093 iend
= CHAR_TO_BYTE (XFASTINT (end
));
3094 move_gap_both (XFASTINT (beg
), ibeg
);
3096 /* We need to allocate enough room for encoding the text.
3097 We need 33 1/3% more space, plus a newline every 76
3098 characters, and then we round up. */
3099 length
= iend
- ibeg
;
3100 allength
= length
+ length
/3 + 1;
3101 allength
+= allength
/ MIME_LINE_LENGTH
+ 1 + 6;
3103 encoded
= SAFE_ALLOCA (allength
);
3104 encoded_length
= base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg
),
3105 encoded
, length
, NILP (no_line_break
),
3106 !NILP (BVAR (current_buffer
, enable_multibyte_characters
)));
3107 if (encoded_length
> allength
)
3110 if (encoded_length
< 0)
3112 /* The encoding wasn't possible. */
3114 error ("Multibyte character in data for base64 encoding");
3117 /* Now we have encoded the region, so we insert the new contents
3118 and delete the old. (Insert first in order to preserve markers.) */
3119 SET_PT_BOTH (XFASTINT (beg
), ibeg
);
3120 insert (encoded
, encoded_length
);
3122 del_range_byte (ibeg
+ encoded_length
, iend
+ encoded_length
);
3124 /* If point was outside of the region, restore it exactly; else just
3125 move to the beginning of the region. */
3126 if (old_pos
>= XFASTINT (end
))
3127 old_pos
+= encoded_length
- (XFASTINT (end
) - XFASTINT (beg
));
3128 else if (old_pos
> XFASTINT (beg
))
3129 old_pos
= XFASTINT (beg
);
3132 /* We return the length of the encoded text. */
3133 return make_number (encoded_length
);
3136 DEFUN ("base64-encode-string", Fbase64_encode_string
, Sbase64_encode_string
,
3138 doc
: /* Base64-encode STRING and return the result.
3139 Optional second argument NO-LINE-BREAK means do not break long lines
3140 into shorter lines. */)
3141 (Lisp_Object string
, Lisp_Object no_line_break
)
3143 ptrdiff_t allength
, length
, encoded_length
;
3145 Lisp_Object encoded_string
;
3148 CHECK_STRING (string
);
3150 /* We need to allocate enough room for encoding the text.
3151 We need 33 1/3% more space, plus a newline every 76
3152 characters, and then we round up. */
3153 length
= SBYTES (string
);
3154 allength
= length
+ length
/3 + 1;
3155 allength
+= allength
/ MIME_LINE_LENGTH
+ 1 + 6;
3157 /* We need to allocate enough room for decoding the text. */
3158 encoded
= SAFE_ALLOCA (allength
);
3160 encoded_length
= base64_encode_1 (SSDATA (string
),
3161 encoded
, length
, NILP (no_line_break
),
3162 STRING_MULTIBYTE (string
));
3163 if (encoded_length
> allength
)
3166 if (encoded_length
< 0)
3168 /* The encoding wasn't possible. */
3169 error ("Multibyte character in data for base64 encoding");
3172 encoded_string
= make_unibyte_string (encoded
, encoded_length
);
3175 return encoded_string
;
3179 base64_encode_1 (const char *from
, char *to
, ptrdiff_t length
,
3180 bool line_break
, bool multibyte
)
3193 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3194 if (CHAR_BYTE8_P (c
))
3195 c
= CHAR_TO_BYTE8 (c
);
3203 /* Wrap line every 76 characters. */
3207 if (counter
< MIME_LINE_LENGTH
/ 4)
3216 /* Process first byte of a triplet. */
3218 *e
++ = base64_value_to_char
[0x3f & c
>> 2];
3219 value
= (0x03 & c
) << 4;
3221 /* Process second byte of a triplet. */
3225 *e
++ = base64_value_to_char
[value
];
3233 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3234 if (CHAR_BYTE8_P (c
))
3235 c
= CHAR_TO_BYTE8 (c
);
3243 *e
++ = base64_value_to_char
[value
| (0x0f & c
>> 4)];
3244 value
= (0x0f & c
) << 2;
3246 /* Process third byte of a triplet. */
3250 *e
++ = base64_value_to_char
[value
];
3257 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3258 if (CHAR_BYTE8_P (c
))
3259 c
= CHAR_TO_BYTE8 (c
);
3267 *e
++ = base64_value_to_char
[value
| (0x03 & c
>> 6)];
3268 *e
++ = base64_value_to_char
[0x3f & c
];
3275 DEFUN ("base64-decode-region", Fbase64_decode_region
, Sbase64_decode_region
,
3277 doc
: /* Base64-decode the region between BEG and END.
3278 Return the length of the decoded text.
3279 If the region can't be decoded, signal an error and don't modify the buffer. */)
3280 (Lisp_Object beg
, Lisp_Object end
)
3282 ptrdiff_t ibeg
, iend
, length
, allength
;
3284 ptrdiff_t old_pos
= PT
;
3285 ptrdiff_t decoded_length
;
3286 ptrdiff_t inserted_chars
;
3287 bool multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3290 validate_region (&beg
, &end
);
3292 ibeg
= CHAR_TO_BYTE (XFASTINT (beg
));
3293 iend
= CHAR_TO_BYTE (XFASTINT (end
));
3295 length
= iend
- ibeg
;
3297 /* We need to allocate enough room for decoding the text. If we are
3298 working on a multibyte buffer, each decoded code may occupy at
3300 allength
= multibyte
? length
* 2 : length
;
3301 decoded
= SAFE_ALLOCA (allength
);
3303 move_gap_both (XFASTINT (beg
), ibeg
);
3304 decoded_length
= base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg
),
3306 multibyte
, &inserted_chars
);
3307 if (decoded_length
> allength
)
3310 if (decoded_length
< 0)
3312 /* The decoding wasn't possible. */
3313 error ("Invalid base64 data");
3316 /* Now we have decoded the region, so we insert the new contents
3317 and delete the old. (Insert first in order to preserve markers.) */
3318 TEMP_SET_PT_BOTH (XFASTINT (beg
), ibeg
);
3319 insert_1_both (decoded
, inserted_chars
, decoded_length
, 0, 1, 0);
3322 /* Delete the original text. */
3323 del_range_both (PT
, PT_BYTE
, XFASTINT (end
) + inserted_chars
,
3324 iend
+ decoded_length
, 1);
3326 /* If point was outside of the region, restore it exactly; else just
3327 move to the beginning of the region. */
3328 if (old_pos
>= XFASTINT (end
))
3329 old_pos
+= inserted_chars
- (XFASTINT (end
) - XFASTINT (beg
));
3330 else if (old_pos
> XFASTINT (beg
))
3331 old_pos
= XFASTINT (beg
);
3332 SET_PT (old_pos
> ZV
? ZV
: old_pos
);
3334 return make_number (inserted_chars
);
3337 DEFUN ("base64-decode-string", Fbase64_decode_string
, Sbase64_decode_string
,
3339 doc
: /* Base64-decode STRING and return the result. */)
3340 (Lisp_Object string
)
3343 ptrdiff_t length
, decoded_length
;
3344 Lisp_Object decoded_string
;
3347 CHECK_STRING (string
);
3349 length
= SBYTES (string
);
3350 /* We need to allocate enough room for decoding the text. */
3351 decoded
= SAFE_ALLOCA (length
);
3353 /* The decoded result should be unibyte. */
3354 decoded_length
= base64_decode_1 (SSDATA (string
), decoded
, length
,
3356 if (decoded_length
> length
)
3358 else if (decoded_length
>= 0)
3359 decoded_string
= make_unibyte_string (decoded
, decoded_length
);
3361 decoded_string
= Qnil
;
3364 if (!STRINGP (decoded_string
))
3365 error ("Invalid base64 data");
3367 return decoded_string
;
3370 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3371 MULTIBYTE, the decoded result should be in multibyte
3372 form. If NCHARS_RETURN is not NULL, store the number of produced
3373 characters in *NCHARS_RETURN. */
3376 base64_decode_1 (const char *from
, char *to
, ptrdiff_t length
,
3377 bool multibyte
, ptrdiff_t *nchars_return
)
3379 ptrdiff_t i
= 0; /* Used inside READ_QUADRUPLET_BYTE */
3382 unsigned long value
;
3383 ptrdiff_t nchars
= 0;
3387 /* Process first byte of a quadruplet. */
3389 READ_QUADRUPLET_BYTE (e
-to
);
3393 value
= base64_char_to_value
[c
] << 18;
3395 /* Process second byte of a quadruplet. */
3397 READ_QUADRUPLET_BYTE (-1);
3401 value
|= base64_char_to_value
[c
] << 12;
3403 c
= (unsigned char) (value
>> 16);
3404 if (multibyte
&& c
>= 128)
3405 e
+= BYTE8_STRING (c
, e
);
3410 /* Process third byte of a quadruplet. */
3412 READ_QUADRUPLET_BYTE (-1);
3416 READ_QUADRUPLET_BYTE (-1);
3425 value
|= base64_char_to_value
[c
] << 6;
3427 c
= (unsigned char) (0xff & value
>> 8);
3428 if (multibyte
&& c
>= 128)
3429 e
+= BYTE8_STRING (c
, e
);
3434 /* Process fourth byte of a quadruplet. */
3436 READ_QUADRUPLET_BYTE (-1);
3443 value
|= base64_char_to_value
[c
];
3445 c
= (unsigned char) (0xff & value
);
3446 if (multibyte
&& c
>= 128)
3447 e
+= BYTE8_STRING (c
, e
);
3456 /***********************************************************************
3458 ***** Hash Tables *****
3460 ***********************************************************************/
3462 /* Implemented by gerd@gnu.org. This hash table implementation was
3463 inspired by CMUCL hash tables. */
3467 1. For small tables, association lists are probably faster than
3468 hash tables because they have lower overhead.
3470 For uses of hash tables where the O(1) behavior of table
3471 operations is not a requirement, it might therefore be a good idea
3472 not to hash. Instead, we could just do a linear search in the
3473 key_and_value vector of the hash table. This could be done
3474 if a `:linear-search t' argument is given to make-hash-table. */
3477 /* The list of all weak hash tables. Don't staticpro this one. */
3479 static struct Lisp_Hash_Table
*weak_hash_tables
;
3482 /***********************************************************************
3484 ***********************************************************************/
3487 CHECK_HASH_TABLE (Lisp_Object x
)
3489 CHECK_TYPE (HASH_TABLE_P (x
), Qhash_table_p
, x
);
3493 set_hash_key_and_value (struct Lisp_Hash_Table
*h
, Lisp_Object key_and_value
)
3495 h
->key_and_value
= key_and_value
;
3498 set_hash_next (struct Lisp_Hash_Table
*h
, Lisp_Object next
)
3503 set_hash_next_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, ptrdiff_t val
)
3505 gc_aset (h
->next
, idx
, make_number (val
));
3508 set_hash_hash (struct Lisp_Hash_Table
*h
, Lisp_Object hash
)
3513 set_hash_hash_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, Lisp_Object val
)
3515 gc_aset (h
->hash
, idx
, val
);
3518 set_hash_index (struct Lisp_Hash_Table
*h
, Lisp_Object index
)
3523 set_hash_index_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, ptrdiff_t val
)
3525 gc_aset (h
->index
, idx
, make_number (val
));
3528 /* If OBJ is a Lisp hash table, return a pointer to its struct
3529 Lisp_Hash_Table. Otherwise, signal an error. */
3531 static struct Lisp_Hash_Table
*
3532 check_hash_table (Lisp_Object obj
)
3534 CHECK_HASH_TABLE (obj
);
3535 return XHASH_TABLE (obj
);
3539 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3540 number. A number is "almost" a prime number if it is not divisible
3541 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3544 next_almost_prime (EMACS_INT n
)
3546 verify (NEXT_ALMOST_PRIME_LIMIT
== 11);
3547 for (n
|= 1; ; n
+= 2)
3548 if (n
% 3 != 0 && n
% 5 != 0 && n
% 7 != 0)
3553 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3554 which USED[I] is non-zero. If found at index I in ARGS, set
3555 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3556 0. This function is used to extract a keyword/argument pair from
3557 a DEFUN parameter list. */
3560 get_key_arg (Lisp_Object key
, ptrdiff_t nargs
, Lisp_Object
*args
, char *used
)
3564 for (i
= 1; i
< nargs
; i
++)
3565 if (!used
[i
- 1] && EQ (args
[i
- 1], key
))
3576 /* Return a Lisp vector which has the same contents as VEC but has
3577 at least INCR_MIN more entries, where INCR_MIN is positive.
3578 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3579 than NITEMS_MAX. New entries in the resulting vector are
3583 larger_vecalloc (Lisp_Object vec
, ptrdiff_t incr_min
, ptrdiff_t nitems_max
)
3585 struct Lisp_Vector
*v
;
3586 ptrdiff_t incr
, incr_max
, old_size
, new_size
;
3587 ptrdiff_t C_language_max
= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *v
->contents
;
3588 ptrdiff_t n_max
= (0 <= nitems_max
&& nitems_max
< C_language_max
3589 ? nitems_max
: C_language_max
);
3590 eassert (VECTORP (vec
));
3591 eassert (0 < incr_min
&& -1 <= nitems_max
);
3592 old_size
= ASIZE (vec
);
3593 incr_max
= n_max
- old_size
;
3594 incr
= max (incr_min
, min (old_size
>> 1, incr_max
));
3595 if (incr_max
< incr
)
3596 memory_full (SIZE_MAX
);
3597 new_size
= old_size
+ incr
;
3598 v
= allocate_vector (new_size
);
3599 memcpy (v
->contents
, XVECTOR (vec
)->contents
, old_size
* sizeof *v
->contents
);
3600 XSETVECTOR (vec
, v
);
3604 /* Likewise, except set new entries in the resulting vector to nil. */
3607 larger_vector (Lisp_Object vec
, ptrdiff_t incr_min
, ptrdiff_t nitems_max
)
3609 ptrdiff_t old_size
= ASIZE (vec
);
3610 Lisp_Object v
= larger_vecalloc (vec
, incr_min
, nitems_max
);
3611 ptrdiff_t new_size
= ASIZE (v
);
3612 memclear (XVECTOR (v
)->contents
+ old_size
,
3613 (new_size
- old_size
) * word_size
);
3618 /***********************************************************************
3620 ***********************************************************************/
3622 /* Return the index of the next entry in H following the one at IDX,
3626 HASH_NEXT (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
)
3628 return XINT (AREF (h
->next
, idx
));
3631 /* Return the index of the element in hash table H that is the start
3632 of the collision list at index IDX, or -1 if the list is empty. */
3635 HASH_INDEX (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
)
3637 return XINT (AREF (h
->index
, idx
));
3640 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3641 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3642 KEY2 are the same. */
3645 cmpfn_eql (struct hash_table_test
*ht
,
3649 return (FLOATP (key1
)
3651 && XFLOAT_DATA (key1
) == XFLOAT_DATA (key2
));
3655 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3656 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3657 KEY2 are the same. */
3660 cmpfn_equal (struct hash_table_test
*ht
,
3664 return !NILP (Fequal (key1
, key2
));
3668 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3669 HASH2 in hash table H using H->user_cmp_function. Value is true
3670 if KEY1 and KEY2 are the same. */
3673 cmpfn_user_defined (struct hash_table_test
*ht
,
3677 return !NILP (call2 (ht
->user_cmp_function
, key1
, key2
));
3680 /* Value is a hash code for KEY for use in hash table H which uses
3681 `eq' to compare keys. The hash code returned is guaranteed to fit
3682 in a Lisp integer. */
3685 hashfn_eq (struct hash_table_test
*ht
, Lisp_Object key
)
3687 return XHASH (key
) ^ XTYPE (key
);
3690 /* Value is a hash code for KEY for use in hash table H which uses
3691 `equal' to compare keys. The hash code returned is guaranteed to fit
3692 in a Lisp integer. */
3695 hashfn_equal (struct hash_table_test
*ht
, Lisp_Object key
)
3697 return sxhash (key
, 0);
3700 /* Value is a hash code for KEY for use in hash table H which uses
3701 `eql' to compare keys. The hash code returned is guaranteed to fit
3702 in a Lisp integer. */
3705 hashfn_eql (struct hash_table_test
*ht
, Lisp_Object key
)
3707 return FLOATP (key
) ? hashfn_equal (ht
, key
) : hashfn_eq (ht
, key
);
3710 /* Value is a hash code for KEY for use in hash table H which uses as
3711 user-defined function to compare keys. The hash code returned is
3712 guaranteed to fit in a Lisp integer. */
3715 hashfn_user_defined (struct hash_table_test
*ht
, Lisp_Object key
)
3717 Lisp_Object hash
= call1 (ht
->user_hash_function
, key
);
3718 return hashfn_eq (ht
, hash
);
3721 struct hash_table_test
const
3722 hashtest_eq
= { LISPSYM_INITIALLY (Qeq
), LISPSYM_INITIALLY (Qnil
),
3723 LISPSYM_INITIALLY (Qnil
), 0, hashfn_eq
},
3724 hashtest_eql
= { LISPSYM_INITIALLY (Qeql
), LISPSYM_INITIALLY (Qnil
),
3725 LISPSYM_INITIALLY (Qnil
), cmpfn_eql
, hashfn_eql
},
3726 hashtest_equal
= { LISPSYM_INITIALLY (Qequal
), LISPSYM_INITIALLY (Qnil
),
3727 LISPSYM_INITIALLY (Qnil
), cmpfn_equal
, hashfn_equal
};
3729 /* Allocate basically initialized hash table. */
3731 static struct Lisp_Hash_Table
*
3732 allocate_hash_table (void)
3734 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table
,
3735 count
, PVEC_HASH_TABLE
);
3738 /* An upper bound on the size of a hash table index. It must fit in
3739 ptrdiff_t and be a valid Emacs fixnum. */
3740 #define INDEX_SIZE_BOUND \
3741 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3743 /* Create and initialize a new hash table.
3745 TEST specifies the test the hash table will use to compare keys.
3746 It must be either one of the predefined tests `eq', `eql' or
3747 `equal' or a symbol denoting a user-defined test named TEST with
3748 test and hash functions USER_TEST and USER_HASH.
3750 Give the table initial capacity SIZE, 0 <= SIZE <= MOST_POSITIVE_FIXNUM.
3752 If REHASH_SIZE is equal to a negative integer, this hash table's
3753 new size when it becomes full is computed by subtracting
3754 REHASH_SIZE from its old size. Otherwise it must be positive, and
3755 the table's new size is computed by multiplying its old size by
3758 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3759 be resized when the approximate ratio of table entries to table
3760 size exceeds REHASH_THRESHOLD.
3762 WEAK specifies the weakness of the table. If non-nil, it must be
3763 one of the symbols `key', `value', `key-or-value', or `key-and-value'.
3765 If PURECOPY is non-nil, the table can be copied to pure storage via
3766 `purecopy' when Emacs is being dumped. Such tables can no longer be
3767 changed after purecopy. */
3770 make_hash_table (struct hash_table_test test
, EMACS_INT size
,
3771 float rehash_size
, float rehash_threshold
,
3772 Lisp_Object weak
, bool pure
)
3774 struct Lisp_Hash_Table
*h
;
3776 EMACS_INT index_size
;
3780 /* Preconditions. */
3781 eassert (SYMBOLP (test
.name
));
3782 eassert (0 <= size
&& size
<= MOST_POSITIVE_FIXNUM
);
3783 eassert (rehash_size
<= -1 || 0 < rehash_size
);
3784 eassert (0 < rehash_threshold
&& rehash_threshold
<= 1);
3789 double threshold
= rehash_threshold
;
3790 index_float
= size
/ threshold
;
3791 index_size
= (index_float
< INDEX_SIZE_BOUND
+ 1
3792 ? next_almost_prime (index_float
)
3793 : INDEX_SIZE_BOUND
+ 1);
3794 if (INDEX_SIZE_BOUND
< max (index_size
, 2 * size
))
3795 error ("Hash table too large");
3797 /* Allocate a table and initialize it. */
3798 h
= allocate_hash_table ();
3800 /* Initialize hash table slots. */
3803 h
->rehash_threshold
= rehash_threshold
;
3804 h
->rehash_size
= rehash_size
;
3806 h
->key_and_value
= Fmake_vector (make_number (2 * size
), Qnil
);
3807 h
->hash
= Fmake_vector (make_number (size
), Qnil
);
3808 h
->next
= Fmake_vector (make_number (size
), make_number (-1));
3809 h
->index
= Fmake_vector (make_number (index_size
), make_number (-1));
3812 /* Set up the free list. */
3813 for (i
= 0; i
< size
- 1; ++i
)
3814 set_hash_next_slot (h
, i
, i
+ 1);
3817 XSET_HASH_TABLE (table
, h
);
3818 eassert (HASH_TABLE_P (table
));
3819 eassert (XHASH_TABLE (table
) == h
);
3821 /* Maybe add this hash table to the list of all weak hash tables. */
3824 h
->next_weak
= weak_hash_tables
;
3825 weak_hash_tables
= h
;
3832 /* Return a copy of hash table H1. Keys and values are not copied,
3833 only the table itself is. */
3836 copy_hash_table (struct Lisp_Hash_Table
*h1
)
3839 struct Lisp_Hash_Table
*h2
;
3841 h2
= allocate_hash_table ();
3843 h2
->key_and_value
= Fcopy_sequence (h1
->key_and_value
);
3844 h2
->hash
= Fcopy_sequence (h1
->hash
);
3845 h2
->next
= Fcopy_sequence (h1
->next
);
3846 h2
->index
= Fcopy_sequence (h1
->index
);
3847 XSET_HASH_TABLE (table
, h2
);
3849 /* Maybe add this hash table to the list of all weak hash tables. */
3850 if (!NILP (h2
->weak
))
3852 h2
->next_weak
= h1
->next_weak
;
3860 /* Resize hash table H if it's too full. If H cannot be resized
3861 because it's already too large, throw an error. */
3864 maybe_resize_hash_table (struct Lisp_Hash_Table
*h
)
3866 if (h
->next_free
< 0)
3868 ptrdiff_t old_size
= HASH_TABLE_SIZE (h
);
3869 EMACS_INT new_size
, index_size
, nsize
;
3871 double rehash_size
= h
->rehash_size
;
3874 if (rehash_size
< 0)
3875 new_size
= old_size
- rehash_size
;
3878 double float_new_size
= old_size
* (rehash_size
+ 1);
3879 if (float_new_size
< INDEX_SIZE_BOUND
+ 1)
3880 new_size
= float_new_size
;
3882 new_size
= INDEX_SIZE_BOUND
+ 1;
3884 if (new_size
<= old_size
)
3885 new_size
= old_size
+ 1;
3886 double threshold
= h
->rehash_threshold
;
3887 index_float
= new_size
/ threshold
;
3888 index_size
= (index_float
< INDEX_SIZE_BOUND
+ 1
3889 ? next_almost_prime (index_float
)
3890 : INDEX_SIZE_BOUND
+ 1);
3891 nsize
= max (index_size
, 2 * new_size
);
3892 if (INDEX_SIZE_BOUND
< nsize
)
3893 error ("Hash table too large to resize");
3895 #ifdef ENABLE_CHECKING
3896 if (HASH_TABLE_P (Vpurify_flag
)
3897 && XHASH_TABLE (Vpurify_flag
) == h
)
3898 message ("Growing hash table to: %"pI
"d", new_size
);
3901 set_hash_key_and_value (h
, larger_vector (h
->key_and_value
,
3902 2 * (new_size
- old_size
), -1));
3903 set_hash_hash (h
, larger_vector (h
->hash
, new_size
- old_size
, -1));
3904 set_hash_index (h
, Fmake_vector (make_number (index_size
),
3906 set_hash_next (h
, larger_vecalloc (h
->next
, new_size
- old_size
, -1));
3908 /* Update the free list. Do it so that new entries are added at
3909 the end of the free list. This makes some operations like
3911 for (i
= old_size
; i
< new_size
- 1; ++i
)
3912 set_hash_next_slot (h
, i
, i
+ 1);
3913 set_hash_next_slot (h
, i
, -1);
3915 if (h
->next_free
< 0)
3916 h
->next_free
= old_size
;
3919 ptrdiff_t last
= h
->next_free
;
3922 ptrdiff_t next
= HASH_NEXT (h
, last
);
3927 set_hash_next_slot (h
, last
, old_size
);
3931 for (i
= 0; i
< old_size
; ++i
)
3932 if (!NILP (HASH_HASH (h
, i
)))
3934 EMACS_UINT hash_code
= XUINT (HASH_HASH (h
, i
));
3935 ptrdiff_t start_of_bucket
= hash_code
% ASIZE (h
->index
);
3936 set_hash_next_slot (h
, i
, HASH_INDEX (h
, start_of_bucket
));
3937 set_hash_index_slot (h
, start_of_bucket
, i
);
3943 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3944 the hash code of KEY. Value is the index of the entry in H
3945 matching KEY, or -1 if not found. */
3948 hash_lookup (struct Lisp_Hash_Table
*h
, Lisp_Object key
, EMACS_UINT
*hash
)
3950 EMACS_UINT hash_code
;
3951 ptrdiff_t start_of_bucket
, i
;
3953 hash_code
= h
->test
.hashfn (&h
->test
, key
);
3954 eassert ((hash_code
& ~INTMASK
) == 0);
3958 start_of_bucket
= hash_code
% ASIZE (h
->index
);
3960 for (i
= HASH_INDEX (h
, start_of_bucket
); 0 <= i
; i
= HASH_NEXT (h
, i
))
3961 if (EQ (key
, HASH_KEY (h
, i
))
3963 && hash_code
== XUINT (HASH_HASH (h
, i
))
3964 && h
->test
.cmpfn (&h
->test
, key
, HASH_KEY (h
, i
))))
3971 /* Put an entry into hash table H that associates KEY with VALUE.
3972 HASH is a previously computed hash code of KEY.
3973 Value is the index of the entry in H matching KEY. */
3976 hash_put (struct Lisp_Hash_Table
*h
, Lisp_Object key
, Lisp_Object value
,
3979 ptrdiff_t start_of_bucket
, i
;
3981 eassert ((hash
& ~INTMASK
) == 0);
3983 /* Increment count after resizing because resizing may fail. */
3984 maybe_resize_hash_table (h
);
3987 /* Store key/value in the key_and_value vector. */
3989 h
->next_free
= HASH_NEXT (h
, i
);
3990 set_hash_key_slot (h
, i
, key
);
3991 set_hash_value_slot (h
, i
, value
);
3993 /* Remember its hash code. */
3994 set_hash_hash_slot (h
, i
, make_number (hash
));
3996 /* Add new entry to its collision chain. */
3997 start_of_bucket
= hash
% ASIZE (h
->index
);
3998 set_hash_next_slot (h
, i
, HASH_INDEX (h
, start_of_bucket
));
3999 set_hash_index_slot (h
, start_of_bucket
, i
);
4004 /* Remove the entry matching KEY from hash table H, if there is one. */
4007 hash_remove_from_table (struct Lisp_Hash_Table
*h
, Lisp_Object key
)
4009 EMACS_UINT hash_code
= h
->test
.hashfn (&h
->test
, key
);
4010 eassert ((hash_code
& ~INTMASK
) == 0);
4011 ptrdiff_t start_of_bucket
= hash_code
% ASIZE (h
->index
);
4012 ptrdiff_t prev
= -1;
4014 for (ptrdiff_t i
= HASH_INDEX (h
, start_of_bucket
);
4016 i
= HASH_NEXT (h
, i
))
4018 if (EQ (key
, HASH_KEY (h
, i
))
4020 && hash_code
== XUINT (HASH_HASH (h
, i
))
4021 && h
->test
.cmpfn (&h
->test
, key
, HASH_KEY (h
, i
))))
4023 /* Take entry out of collision chain. */
4025 set_hash_index_slot (h
, start_of_bucket
, HASH_NEXT (h
, i
));
4027 set_hash_next_slot (h
, prev
, HASH_NEXT (h
, i
));
4029 /* Clear slots in key_and_value and add the slots to
4031 set_hash_key_slot (h
, i
, Qnil
);
4032 set_hash_value_slot (h
, i
, Qnil
);
4033 set_hash_hash_slot (h
, i
, Qnil
);
4034 set_hash_next_slot (h
, i
, h
->next_free
);
4037 eassert (h
->count
>= 0);
4046 /* Clear hash table H. */
4049 hash_clear (struct Lisp_Hash_Table
*h
)
4053 ptrdiff_t i
, size
= HASH_TABLE_SIZE (h
);
4055 for (i
= 0; i
< size
; ++i
)
4057 set_hash_next_slot (h
, i
, i
< size
- 1 ? i
+ 1 : -1);
4058 set_hash_key_slot (h
, i
, Qnil
);
4059 set_hash_value_slot (h
, i
, Qnil
);
4060 set_hash_hash_slot (h
, i
, Qnil
);
4063 for (i
= 0; i
< ASIZE (h
->index
); ++i
)
4064 ASET (h
->index
, i
, make_number (-1));
4073 /************************************************************************
4075 ************************************************************************/
4077 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4078 entries from the table that don't survive the current GC.
4079 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4080 true if anything was marked. */
4083 sweep_weak_table (struct Lisp_Hash_Table
*h
, bool remove_entries_p
)
4085 ptrdiff_t n
= gc_asize (h
->index
);
4086 bool marked
= false;
4088 for (ptrdiff_t bucket
= 0; bucket
< n
; ++bucket
)
4090 /* Follow collision chain, removing entries that
4091 don't survive this garbage collection. */
4092 ptrdiff_t prev
= -1;
4094 for (ptrdiff_t i
= HASH_INDEX (h
, bucket
); 0 <= i
; i
= next
)
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
));
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
);
4111 next
= HASH_NEXT (h
, i
);
4113 if (remove_entries_p
)
4117 /* Take out of collision chain. */
4119 set_hash_index_slot (h
, bucket
, next
);
4121 set_hash_next_slot (h
, prev
, next
);
4123 /* Add to free list. */
4124 set_hash_next_slot (h
, i
, h
->next_free
);
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
);
4143 /* Make sure key and value survive. */
4144 if (!key_known_to_survive_p
)
4146 mark_object (HASH_KEY (h
, i
));
4150 if (!value_known_to_survive_p
)
4152 mark_object (HASH_VALUE (h
, i
));
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. */
4167 NO_INLINE
/* For better stack traces */
4169 sweep_weak_hash_tables (void)
4171 struct Lisp_Hash_Table
*h
, *used
, *next
;
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. */
4183 for (h
= weak_hash_tables
; h
; h
= h
->next_weak
)
4185 if (h
->header
.size
& ARRAY_MARK_FLAG
)
4186 marked
|= sweep_weak_table (h
, 0);
4191 /* Remove tables and entries that aren't used. */
4192 for (h
= weak_hash_tables
, used
= NULL
; h
; h
= next
)
4194 next
= h
->next_weak
;
4196 if (h
->header
.size
& ARRAY_MARK_FLAG
)
4198 /* TABLE is marked as used. Sweep its contents. */
4200 sweep_weak_table (h
, 1);
4202 /* Add table to the list of used weak hash tables. */
4203 h
->next_weak
= used
;
4208 weak_hash_tables
= used
;
4213 /***********************************************************************
4214 Hash Code Computation
4215 ***********************************************************************/
4217 /* Maximum depth up to which to dive into Lisp structures. */
4219 #define SXHASH_MAX_DEPTH 3
4221 /* Maximum length up to which to take list and vector elements into
4224 #define SXHASH_MAX_LEN 7
4226 /* Return a hash for string PTR which has length LEN. The hash value
4227 can be any EMACS_UINT value. */
4230 hash_string (char const *ptr
, ptrdiff_t len
)
4232 char const *p
= ptr
;
4233 char const *end
= p
+ len
;
4235 EMACS_UINT hash
= 0;
4240 hash
= sxhash_combine (hash
, c
);
4246 /* Return a hash for string PTR which has length LEN. The hash
4247 code returned is guaranteed to fit in a Lisp integer. */
4250 sxhash_string (char const *ptr
, ptrdiff_t len
)
4252 EMACS_UINT hash
= hash_string (ptr
, len
);
4253 return SXHASH_REDUCE (hash
);
4256 /* Return a hash for the floating point value VAL. */
4259 sxhash_float (double val
)
4261 EMACS_UINT hash
= 0;
4263 WORDS_PER_DOUBLE
= (sizeof val
/ sizeof hash
4264 + (sizeof val
% sizeof hash
!= 0))
4268 EMACS_UINT word
[WORDS_PER_DOUBLE
];
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
);
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. */
4282 sxhash_list (Lisp_Object list
, int depth
)
4284 EMACS_UINT hash
= 0;
4287 if (depth
< SXHASH_MAX_DEPTH
)
4289 CONSP (list
) && i
< SXHASH_MAX_LEN
;
4290 list
= XCDR (list
), ++i
)
4292 EMACS_UINT hash2
= sxhash (XCAR (list
), depth
+ 1);
4293 hash
= sxhash_combine (hash
, hash2
);
4298 EMACS_UINT hash2
= sxhash (list
, depth
+ 1);
4299 hash
= sxhash_combine (hash
, hash2
);
4302 return SXHASH_REDUCE (hash
);
4306 /* Return a hash for (pseudo)vector VECTOR. DEPTH is the current depth in
4307 the Lisp structure. */
4310 sxhash_vector (Lisp_Object vec
, int depth
)
4312 EMACS_UINT hash
= ASIZE (vec
);
4315 n
= min (SXHASH_MAX_LEN
, hash
& PSEUDOVECTOR_FLAG
? PVSIZE (vec
) : hash
);
4316 for (i
= 0; i
< n
; ++i
)
4318 EMACS_UINT hash2
= sxhash (AREF (vec
, i
), depth
+ 1);
4319 hash
= sxhash_combine (hash
, hash2
);
4322 return SXHASH_REDUCE (hash
);
4325 /* Return a hash for bool-vector VECTOR. */
4328 sxhash_bool_vector (Lisp_Object vec
)
4330 EMACS_INT size
= bool_vector_size (vec
);
4331 EMACS_UINT hash
= size
;
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
]);
4338 return SXHASH_REDUCE (hash
);
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. */
4346 sxhash (Lisp_Object obj
, int depth
)
4350 if (depth
> SXHASH_MAX_DEPTH
)
4353 switch (XTYPE (obj
))
4365 hash
= sxhash_string (SSDATA (obj
), SBYTES (obj
));
4368 /* This can be everything from a vector to an overlay. */
4369 case Lisp_Vectorlike
:
4370 if (VECTORP (obj
) || RECORDP (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. Same for records. */
4375 hash
= sxhash_vector (obj
, depth
);
4376 else if (BOOL_VECTOR_P (obj
))
4377 hash
= sxhash_bool_vector (obj
);
4379 /* Others are `equal' if they are `eq', so let's take their
4385 hash
= sxhash_list (obj
, depth
);
4389 hash
= sxhash_float (XFLOAT_DATA (obj
));
4401 /***********************************************************************
4403 ***********************************************************************/
4405 DEFUN ("sxhash-eq", Fsxhash_eq
, Ssxhash_eq
, 1, 1, 0,
4406 doc
: /* Return an integer hash code for OBJ suitable for `eq'.
4407 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4410 return make_number (hashfn_eq (NULL
, obj
));
4413 DEFUN ("sxhash-eql", Fsxhash_eql
, Ssxhash_eql
, 1, 1, 0,
4414 doc
: /* Return an integer hash code for OBJ suitable for `eql'.
4415 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4418 return make_number (hashfn_eql (NULL
, obj
));
4421 DEFUN ("sxhash-equal", Fsxhash_equal
, Ssxhash_equal
, 1, 1, 0,
4422 doc
: /* Return an integer hash code for OBJ suitable for `equal'.
4423 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4426 return make_number (hashfn_equal (NULL
, obj
));
4429 DEFUN ("make-hash-table", Fmake_hash_table
, Smake_hash_table
, 0, MANY
, 0,
4430 doc
: /* Create and return a new hash table.
4432 Arguments are specified as keyword/argument pairs. The following
4433 arguments are defined:
4435 :test TEST -- TEST must be a symbol that specifies how to compare
4436 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4437 `equal'. User-supplied test and hash functions can be specified via
4438 `define-hash-table-test'.
4440 :size SIZE -- A hint as to how many elements will be put in the table.
4443 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4444 fills up. If REHASH-SIZE is an integer, increase the size by that
4445 amount. If it is a float, it must be > 1.0, and the new size is the
4446 old size multiplied by that factor. Default is 1.5.
4448 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4449 Resize the hash table when the ratio (table entries / table size)
4450 exceeds an approximation to THRESHOLD. Default is 0.8125.
4452 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4453 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4454 returned is a weak table. Key/value pairs are removed from a weak
4455 hash table when there are no non-weak references pointing to their
4456 key, value, one of key or value, or both key and value, depending on
4457 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4460 :purecopy PURECOPY -- If PURECOPY is non-nil, the table can be copied
4461 to pure storage when Emacs is being dumped, making the contents of the
4462 table read only. Any further changes to purified tables will result
4465 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4466 (ptrdiff_t nargs
, Lisp_Object
*args
)
4468 Lisp_Object test
, weak
;
4470 struct hash_table_test testdesc
;
4474 /* The vector `used' is used to keep track of arguments that
4475 have been consumed. */
4476 char *used
= SAFE_ALLOCA (nargs
* sizeof *used
);
4477 memset (used
, 0, nargs
* sizeof *used
);
4479 /* See if there's a `:test TEST' among the arguments. */
4480 i
= get_key_arg (QCtest
, nargs
, args
, used
);
4481 test
= i
? args
[i
] : Qeql
;
4483 testdesc
= hashtest_eq
;
4484 else if (EQ (test
, Qeql
))
4485 testdesc
= hashtest_eql
;
4486 else if (EQ (test
, Qequal
))
4487 testdesc
= hashtest_equal
;
4490 /* See if it is a user-defined test. */
4493 prop
= Fget (test
, Qhash_table_test
);
4494 if (!CONSP (prop
) || !CONSP (XCDR (prop
)))
4495 signal_error ("Invalid hash table test", test
);
4496 testdesc
.name
= test
;
4497 testdesc
.user_cmp_function
= XCAR (prop
);
4498 testdesc
.user_hash_function
= XCAR (XCDR (prop
));
4499 testdesc
.hashfn
= hashfn_user_defined
;
4500 testdesc
.cmpfn
= cmpfn_user_defined
;
4503 /* See if there's a `:purecopy PURECOPY' argument. */
4504 i
= get_key_arg (QCpurecopy
, nargs
, args
, used
);
4505 pure
= i
&& !NILP (args
[i
]);
4506 /* See if there's a `:size SIZE' argument. */
4507 i
= get_key_arg (QCsize
, nargs
, args
, used
);
4508 Lisp_Object size_arg
= i
? args
[i
] : Qnil
;
4510 if (NILP (size_arg
))
4511 size
= DEFAULT_HASH_SIZE
;
4512 else if (NATNUMP (size_arg
))
4513 size
= XFASTINT (size_arg
);
4515 signal_error ("Invalid hash table size", size_arg
);
4517 /* Look for `:rehash-size SIZE'. */
4519 i
= get_key_arg (QCrehash_size
, nargs
, args
, used
);
4521 rehash_size
= DEFAULT_REHASH_SIZE
;
4522 else if (INTEGERP (args
[i
]) && 0 < XINT (args
[i
]))
4523 rehash_size
= - XINT (args
[i
]);
4524 else if (FLOATP (args
[i
]) && 0 < (float) (XFLOAT_DATA (args
[i
]) - 1))
4525 rehash_size
= (float) (XFLOAT_DATA (args
[i
]) - 1);
4527 signal_error ("Invalid hash table rehash size", args
[i
]);
4529 /* Look for `:rehash-threshold THRESHOLD'. */
4530 i
= get_key_arg (QCrehash_threshold
, nargs
, args
, used
);
4531 float rehash_threshold
= (!i
? DEFAULT_REHASH_THRESHOLD
4532 : !FLOATP (args
[i
]) ? 0
4533 : (float) XFLOAT_DATA (args
[i
]));
4534 if (! (0 < rehash_threshold
&& rehash_threshold
<= 1))
4535 signal_error ("Invalid hash table rehash threshold", args
[i
]);
4537 /* Look for `:weakness WEAK'. */
4538 i
= get_key_arg (QCweakness
, nargs
, args
, used
);
4539 weak
= i
? args
[i
] : Qnil
;
4541 weak
= Qkey_and_value
;
4544 && !EQ (weak
, Qvalue
)
4545 && !EQ (weak
, Qkey_or_value
)
4546 && !EQ (weak
, Qkey_and_value
))
4547 signal_error ("Invalid hash table weakness", weak
);
4549 /* Now, all args should have been used up, or there's a problem. */
4550 for (i
= 0; i
< nargs
; ++i
)
4552 signal_error ("Invalid argument list", args
[i
]);
4555 return make_hash_table (testdesc
, size
, rehash_size
, rehash_threshold
, weak
,
4560 DEFUN ("copy-hash-table", Fcopy_hash_table
, Scopy_hash_table
, 1, 1, 0,
4561 doc
: /* Return a copy of hash table TABLE. */)
4564 return copy_hash_table (check_hash_table (table
));
4568 DEFUN ("hash-table-count", Fhash_table_count
, Shash_table_count
, 1, 1, 0,
4569 doc
: /* Return the number of elements in TABLE. */)
4572 return make_number (check_hash_table (table
)->count
);
4576 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size
,
4577 Shash_table_rehash_size
, 1, 1, 0,
4578 doc
: /* Return the current rehash size of TABLE. */)
4581 double rehash_size
= check_hash_table (table
)->rehash_size
;
4582 if (rehash_size
< 0)
4584 EMACS_INT s
= -rehash_size
;
4585 return make_number (min (s
, MOST_POSITIVE_FIXNUM
));
4588 return make_float (rehash_size
+ 1);
4592 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold
,
4593 Shash_table_rehash_threshold
, 1, 1, 0,
4594 doc
: /* Return the current rehash threshold of TABLE. */)
4597 return make_float (check_hash_table (table
)->rehash_threshold
);
4601 DEFUN ("hash-table-size", Fhash_table_size
, Shash_table_size
, 1, 1, 0,
4602 doc
: /* Return the size of TABLE.
4603 The size can be used as an argument to `make-hash-table' to create
4604 a hash table than can hold as many elements as TABLE holds
4605 without need for resizing. */)
4608 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4609 return make_number (HASH_TABLE_SIZE (h
));
4613 DEFUN ("hash-table-test", Fhash_table_test
, Shash_table_test
, 1, 1, 0,
4614 doc
: /* Return the test TABLE uses. */)
4617 return check_hash_table (table
)->test
.name
;
4621 DEFUN ("hash-table-weakness", Fhash_table_weakness
, Shash_table_weakness
,
4623 doc
: /* Return the weakness of TABLE. */)
4626 return check_hash_table (table
)->weak
;
4630 DEFUN ("hash-table-p", Fhash_table_p
, Shash_table_p
, 1, 1, 0,
4631 doc
: /* Return t if OBJ is a Lisp hash table object. */)
4634 return HASH_TABLE_P (obj
) ? Qt
: Qnil
;
4638 DEFUN ("clrhash", Fclrhash
, Sclrhash
, 1, 1, 0,
4639 doc
: /* Clear hash table TABLE and return it. */)
4642 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4643 CHECK_IMPURE (table
, h
);
4645 /* Be compatible with XEmacs. */
4650 DEFUN ("gethash", Fgethash
, Sgethash
, 2, 3, 0,
4651 doc
: /* Look up KEY in TABLE and return its associated value.
4652 If KEY is not found, return DFLT which defaults to nil. */)
4653 (Lisp_Object key
, Lisp_Object table
, Lisp_Object dflt
)
4655 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4656 ptrdiff_t i
= hash_lookup (h
, key
, NULL
);
4657 return i
>= 0 ? HASH_VALUE (h
, i
) : dflt
;
4661 DEFUN ("puthash", Fputhash
, Sputhash
, 3, 3, 0,
4662 doc
: /* Associate KEY with VALUE in hash table TABLE.
4663 If KEY is already present in table, replace its current value with
4664 VALUE. In any case, return VALUE. */)
4665 (Lisp_Object key
, Lisp_Object value
, Lisp_Object table
)
4667 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4668 CHECK_IMPURE (table
, h
);
4672 i
= hash_lookup (h
, key
, &hash
);
4674 set_hash_value_slot (h
, i
, value
);
4676 hash_put (h
, key
, value
, hash
);
4682 DEFUN ("remhash", Fremhash
, Sremhash
, 2, 2, 0,
4683 doc
: /* Remove KEY from TABLE. */)
4684 (Lisp_Object key
, Lisp_Object table
)
4686 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4687 CHECK_IMPURE (table
, h
);
4688 hash_remove_from_table (h
, key
);
4693 DEFUN ("maphash", Fmaphash
, Smaphash
, 2, 2, 0,
4694 doc
: /* Call FUNCTION for all entries in hash table TABLE.
4695 FUNCTION is called with two arguments, KEY and VALUE.
4696 `maphash' always returns nil. */)
4697 (Lisp_Object function
, Lisp_Object table
)
4699 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4701 for (ptrdiff_t i
= 0; i
< HASH_TABLE_SIZE (h
); ++i
)
4702 if (!NILP (HASH_HASH (h
, i
)))
4703 call2 (function
, HASH_KEY (h
, i
), HASH_VALUE (h
, i
));
4709 DEFUN ("define-hash-table-test", Fdefine_hash_table_test
,
4710 Sdefine_hash_table_test
, 3, 3, 0,
4711 doc
: /* Define a new hash table test with name NAME, a symbol.
4713 In hash tables created with NAME specified as test, use TEST to
4714 compare keys, and HASH for computing hash codes of keys.
4716 TEST must be a function taking two arguments and returning non-nil if
4717 both arguments are the same. HASH must be a function taking one
4718 argument and returning an object that is the hash code of the argument.
4719 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4720 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4721 (Lisp_Object name
, Lisp_Object test
, Lisp_Object hash
)
4723 return Fput (name
, Qhash_table_test
, list2 (test
, hash
));
4728 /************************************************************************
4729 MD5, SHA-1, and SHA-2
4730 ************************************************************************/
4738 make_digest_string (Lisp_Object digest
, int digest_size
)
4740 unsigned char *p
= SDATA (digest
);
4742 for (int i
= digest_size
- 1; i
>= 0; i
--)
4744 static char const hexdigit
[16] = "0123456789abcdef";
4746 p
[2 * i
] = hexdigit
[p_i
>> 4];
4747 p
[2 * i
+ 1] = hexdigit
[p_i
& 0xf];
4752 DEFUN ("secure-hash-algorithms", Fsecure_hash_algorithms
,
4753 Ssecure_hash_algorithms
, 0, 0, 0,
4754 doc
: /* Return a list of all the supported `secure_hash' algorithms. */)
4757 return listn (CONSTYPE_HEAP
, 6,
4766 /* Extract data from a string or a buffer. SPEC is a list of
4767 (BUFFER-OR-STRING-OR-SYMBOL START END CODING-SYSTEM NOERROR) which behave as
4768 specified with `secure-hash' and in Info node
4769 `(elisp)Format of GnuTLS Cryptography Inputs'. */
4771 extract_data_from_object (Lisp_Object spec
,
4772 ptrdiff_t *start_byte
,
4773 ptrdiff_t *end_byte
)
4775 Lisp_Object object
= XCAR (spec
);
4777 if (CONSP (spec
)) spec
= XCDR (spec
);
4778 Lisp_Object start
= CAR_SAFE (spec
);
4780 if (CONSP (spec
)) spec
= XCDR (spec
);
4781 Lisp_Object end
= CAR_SAFE (spec
);
4783 if (CONSP (spec
)) spec
= XCDR (spec
);
4784 Lisp_Object coding_system
= CAR_SAFE (spec
);
4786 if (CONSP (spec
)) spec
= XCDR (spec
);
4787 Lisp_Object noerror
= CAR_SAFE (spec
);
4789 if (STRINGP (object
))
4791 if (NILP (coding_system
))
4793 /* Decide the coding-system to encode the data with. */
4795 if (STRING_MULTIBYTE (object
))
4796 /* use default, we can't guess correct value */
4797 coding_system
= preferred_coding_system ();
4799 coding_system
= Qraw_text
;
4802 if (NILP (Fcoding_system_p (coding_system
)))
4804 /* Invalid coding system. */
4806 if (!NILP (noerror
))
4807 coding_system
= Qraw_text
;
4809 xsignal1 (Qcoding_system_error
, coding_system
);
4812 if (STRING_MULTIBYTE (object
))
4813 object
= code_convert_string (object
, coding_system
, Qnil
, 1, 0, 1);
4815 ptrdiff_t size
= SCHARS (object
), start_char
, end_char
;
4816 validate_subarray (object
, start
, end
, size
, &start_char
, &end_char
);
4818 *start_byte
= !start_char
? 0 : string_char_to_byte (object
, start_char
);
4819 *end_byte
= (end_char
== size
4821 : string_char_to_byte (object
, end_char
));
4823 else if (BUFFERP (object
))
4825 struct buffer
*prev
= current_buffer
;
4828 record_unwind_current_buffer ();
4830 CHECK_BUFFER (object
);
4832 struct buffer
*bp
= XBUFFER (object
);
4833 set_buffer_internal (bp
);
4839 CHECK_NUMBER_COERCE_MARKER (start
);
4847 CHECK_NUMBER_COERCE_MARKER (end
);
4858 if (!(BEGV
<= b
&& e
<= ZV
))
4859 args_out_of_range (start
, end
);
4861 if (NILP (coding_system
))
4863 /* Decide the coding-system to encode the data with.
4864 See fileio.c:Fwrite-region */
4866 if (!NILP (Vcoding_system_for_write
))
4867 coding_system
= Vcoding_system_for_write
;
4870 bool force_raw_text
= 0;
4872 coding_system
= BVAR (XBUFFER (object
), buffer_file_coding_system
);
4873 if (NILP (coding_system
)
4874 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4876 coding_system
= Qnil
;
4877 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4881 if (NILP (coding_system
) && !NILP (Fbuffer_file_name (object
)))
4883 /* Check file-coding-system-alist. */
4884 Lisp_Object val
= CALLN (Ffind_operation_coding_system
,
4885 Qwrite_region
, start
, end
,
4886 Fbuffer_file_name (object
));
4887 if (CONSP (val
) && !NILP (XCDR (val
)))
4888 coding_system
= XCDR (val
);
4891 if (NILP (coding_system
)
4892 && !NILP (BVAR (XBUFFER (object
), buffer_file_coding_system
)))
4894 /* If we still have not decided a coding system, use the
4895 default value of buffer-file-coding-system. */
4896 coding_system
= BVAR (XBUFFER (object
), buffer_file_coding_system
);
4900 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4901 /* Confirm that VAL can surely encode the current region. */
4902 coding_system
= call4 (Vselect_safe_coding_system_function
,
4903 make_number (b
), make_number (e
),
4904 coding_system
, Qnil
);
4907 coding_system
= Qraw_text
;
4910 if (NILP (Fcoding_system_p (coding_system
)))
4912 /* Invalid coding system. */
4914 if (!NILP (noerror
))
4915 coding_system
= Qraw_text
;
4917 xsignal1 (Qcoding_system_error
, coding_system
);
4921 object
= make_buffer_string (b
, e
, 0);
4922 set_buffer_internal (prev
);
4923 /* Discard the unwind protect for recovering the current
4927 if (STRING_MULTIBYTE (object
))
4928 object
= code_convert_string (object
, coding_system
, Qnil
, 1, 0, 0);
4930 *end_byte
= SBYTES (object
);
4932 else if (EQ (object
, Qiv_auto
))
4935 /* Format: (iv-auto REQUIRED-LENGTH). */
4937 if (! NATNUMP (start
))
4938 error ("Without a length, `iv-auto' can't be used; see ELisp manual");
4941 EMACS_INT start_hold
= XFASTINT (start
);
4942 object
= make_uninit_string (start_hold
);
4943 gnutls_rnd (GNUTLS_RND_NONCE
, SSDATA (object
), start_hold
);
4946 *end_byte
= start_hold
;
4949 error ("GnuTLS is not available, so `iv-auto' can't be used");
4953 return SSDATA (object
);
4957 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4960 secure_hash (Lisp_Object algorithm
, Lisp_Object object
, Lisp_Object start
,
4961 Lisp_Object end
, Lisp_Object coding_system
, Lisp_Object noerror
,
4964 ptrdiff_t start_byte
, end_byte
;
4966 void *(*hash_func
) (const char *, size_t, void *);
4969 CHECK_SYMBOL (algorithm
);
4971 Lisp_Object spec
= list5 (object
, start
, end
, coding_system
, noerror
);
4973 const char *input
= extract_data_from_object (spec
, &start_byte
, &end_byte
);
4976 error ("secure_hash: failed to extract data from object, aborting!");
4978 if (EQ (algorithm
, Qmd5
))
4980 digest_size
= MD5_DIGEST_SIZE
;
4981 hash_func
= md5_buffer
;
4983 else if (EQ (algorithm
, Qsha1
))
4985 digest_size
= SHA1_DIGEST_SIZE
;
4986 hash_func
= sha1_buffer
;
4988 else if (EQ (algorithm
, Qsha224
))
4990 digest_size
= SHA224_DIGEST_SIZE
;
4991 hash_func
= sha224_buffer
;
4993 else if (EQ (algorithm
, Qsha256
))
4995 digest_size
= SHA256_DIGEST_SIZE
;
4996 hash_func
= sha256_buffer
;
4998 else if (EQ (algorithm
, Qsha384
))
5000 digest_size
= SHA384_DIGEST_SIZE
;
5001 hash_func
= sha384_buffer
;
5003 else if (EQ (algorithm
, Qsha512
))
5005 digest_size
= SHA512_DIGEST_SIZE
;
5006 hash_func
= sha512_buffer
;
5009 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm
)));
5011 /* allocate 2 x digest_size so that it can be re-used to hold the
5013 digest
= make_uninit_string (digest_size
* 2);
5015 hash_func (input
+ start_byte
,
5016 end_byte
- start_byte
,
5020 return make_digest_string (digest
, digest_size
);
5022 return make_unibyte_string (SSDATA (digest
), digest_size
);
5025 DEFUN ("md5", Fmd5
, Smd5
, 1, 5, 0,
5026 doc
: /* Return MD5 message digest of OBJECT, a buffer or string.
5028 A message digest is a cryptographic checksum of a document, and the
5029 algorithm to calculate it is defined in RFC 1321.
5031 The two optional arguments START and END are character positions
5032 specifying for which part of OBJECT the message digest should be
5033 computed. If nil or omitted, the digest is computed for the whole
5036 The MD5 message digest is computed from the result of encoding the
5037 text in a coding system, not directly from the internal Emacs form of
5038 the text. The optional fourth argument CODING-SYSTEM specifies which
5039 coding system to encode the text with. It should be the same coding
5040 system that you used or will use when actually writing the text into a
5043 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5044 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5045 system would be chosen by default for writing this text into a file.
5047 If OBJECT is a string, the most preferred coding system (see the
5048 command `prefer-coding-system') is used.
5050 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5051 guesswork fails. Normally, an error is signaled in such case. */)
5052 (Lisp_Object object
, Lisp_Object start
, Lisp_Object end
, Lisp_Object coding_system
, Lisp_Object noerror
)
5054 return secure_hash (Qmd5
, object
, start
, end
, coding_system
, noerror
, Qnil
);
5057 DEFUN ("secure-hash", Fsecure_hash
, Ssecure_hash
, 2, 5, 0,
5058 doc
: /* Return the secure hash of OBJECT, a buffer or string.
5059 ALGORITHM is a symbol specifying the hash to use:
5060 md5, sha1, sha224, sha256, sha384 or sha512.
5062 The two optional arguments START and END are positions specifying for
5063 which part of OBJECT to compute the hash. If nil or omitted, uses the
5066 The full list of algorithms can be obtained with `secure-hash-algorithms'.
5068 If BINARY is non-nil, returns a string in binary form. */)
5069 (Lisp_Object algorithm
, Lisp_Object object
, Lisp_Object start
, Lisp_Object end
, Lisp_Object binary
)
5071 return secure_hash (algorithm
, object
, start
, end
, Qnil
, Qnil
, binary
);
5074 DEFUN ("buffer-hash", Fbuffer_hash
, Sbuffer_hash
, 0, 1, 0,
5075 doc
: /* Return a hash of the contents of BUFFER-OR-NAME.
5076 This hash is performed on the raw internal format of the buffer,
5077 disregarding any coding systems. If nil, use the current buffer. */ )
5078 (Lisp_Object buffer_or_name
)
5082 struct sha1_ctx ctx
;
5084 if (NILP (buffer_or_name
))
5085 buffer
= Fcurrent_buffer ();
5087 buffer
= Fget_buffer (buffer_or_name
);
5089 nsberror (buffer_or_name
);
5091 b
= XBUFFER (buffer
);
5092 sha1_init_ctx (&ctx
);
5094 /* Process the first part of the buffer. */
5095 sha1_process_bytes (BUF_BEG_ADDR (b
),
5096 BUF_GPT_BYTE (b
) - BUF_BEG_BYTE (b
),
5099 /* If the gap is before the end of the buffer, process the last half
5101 if (BUF_GPT_BYTE (b
) < BUF_Z_BYTE (b
))
5102 sha1_process_bytes (BUF_GAP_END_ADDR (b
),
5103 BUF_Z_ADDR (b
) - BUF_GAP_END_ADDR (b
),
5106 Lisp_Object digest
= make_uninit_string (SHA1_DIGEST_SIZE
* 2);
5107 sha1_finish_ctx (&ctx
, SSDATA (digest
));
5108 return make_digest_string (digest
, SHA1_DIGEST_SIZE
);
5115 /* Hash table stuff. */
5116 DEFSYM (Qhash_table_p
, "hash-table-p");
5118 DEFSYM (Qeql
, "eql");
5119 DEFSYM (Qequal
, "equal");
5120 DEFSYM (QCtest
, ":test");
5121 DEFSYM (QCsize
, ":size");
5122 DEFSYM (QCpurecopy
, ":purecopy");
5123 DEFSYM (QCrehash_size
, ":rehash-size");
5124 DEFSYM (QCrehash_threshold
, ":rehash-threshold");
5125 DEFSYM (QCweakness
, ":weakness");
5126 DEFSYM (Qkey
, "key");
5127 DEFSYM (Qvalue
, "value");
5128 DEFSYM (Qhash_table_test
, "hash-table-test");
5129 DEFSYM (Qkey_or_value
, "key-or-value");
5130 DEFSYM (Qkey_and_value
, "key-and-value");
5132 defsubr (&Ssxhash_eq
);
5133 defsubr (&Ssxhash_eql
);
5134 defsubr (&Ssxhash_equal
);
5135 defsubr (&Smake_hash_table
);
5136 defsubr (&Scopy_hash_table
);
5137 defsubr (&Shash_table_count
);
5138 defsubr (&Shash_table_rehash_size
);
5139 defsubr (&Shash_table_rehash_threshold
);
5140 defsubr (&Shash_table_size
);
5141 defsubr (&Shash_table_test
);
5142 defsubr (&Shash_table_weakness
);
5143 defsubr (&Shash_table_p
);
5144 defsubr (&Sclrhash
);
5145 defsubr (&Sgethash
);
5146 defsubr (&Sputhash
);
5147 defsubr (&Sremhash
);
5148 defsubr (&Smaphash
);
5149 defsubr (&Sdefine_hash_table_test
);
5151 /* Crypto and hashing stuff. */
5152 DEFSYM (Qiv_auto
, "iv-auto");
5154 DEFSYM (Qmd5
, "md5");
5155 DEFSYM (Qsha1
, "sha1");
5156 DEFSYM (Qsha224
, "sha224");
5157 DEFSYM (Qsha256
, "sha256");
5158 DEFSYM (Qsha384
, "sha384");
5159 DEFSYM (Qsha512
, "sha512");
5161 /* Miscellaneous stuff. */
5163 DEFSYM (Qstring_lessp
, "string-lessp");
5164 DEFSYM (Qprovide
, "provide");
5165 DEFSYM (Qrequire
, "require");
5166 DEFSYM (Qyes_or_no_p_history
, "yes-or-no-p-history");
5167 DEFSYM (Qcursor_in_echo_area
, "cursor-in-echo-area");
5168 DEFSYM (Qwidget_type
, "widget-type");
5170 DEFVAR_LISP ("overriding-plist-environment", Voverriding_plist_environment
,
5171 doc
: /* An alist overrides the plists of the symbols which it lists.
5172 Used by the byte-compiler to apply `define-symbol-prop' during
5174 Voverriding_plist_environment
= Qnil
;
5175 DEFSYM (Qoverriding_plist_environment
, "overriding-plist-environment");
5177 staticpro (&string_char_byte_cache_string
);
5178 string_char_byte_cache_string
= Qnil
;
5180 require_nesting_list
= Qnil
;
5181 staticpro (&require_nesting_list
);
5183 Fset (Qyes_or_no_p_history
, Qnil
);
5185 DEFVAR_LISP ("features", Vfeatures
,
5186 doc
: /* A list of symbols which are the features of the executing Emacs.
5187 Used by `featurep' and `require', and altered by `provide'. */);
5188 Vfeatures
= list1 (Qemacs
);
5189 DEFSYM (Qfeatures
, "features");
5190 /* Let people use lexically scoped vars named `features'. */
5191 Fmake_var_non_special (Qfeatures
);
5192 DEFSYM (Qsubfeatures
, "subfeatures");
5193 DEFSYM (Qfuncall
, "funcall");
5194 DEFSYM (Qplistp
, "plistp");
5196 #ifdef HAVE_LANGINFO_CODESET
5197 DEFSYM (Qcodeset
, "codeset");
5198 DEFSYM (Qdays
, "days");
5199 DEFSYM (Qmonths
, "months");
5200 DEFSYM (Qpaper
, "paper");
5201 #endif /* HAVE_LANGINFO_CODESET */
5203 DEFVAR_BOOL ("use-dialog-box", use_dialog_box
,
5204 doc
: /* Non-nil means mouse commands use dialog boxes to ask questions.
5205 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5206 invoked by mouse clicks and mouse menu items.
5208 On some platforms, file selection dialogs are also enabled if this is
5212 DEFVAR_BOOL ("use-file-dialog", use_file_dialog
,
5213 doc
: /* Non-nil means mouse commands use a file dialog to ask for files.
5214 This applies to commands from menus and tool bar buttons even when
5215 they are initiated from the keyboard. If `use-dialog-box' is nil,
5216 that disables the use of a file dialog, regardless of the value of
5218 use_file_dialog
= 1;
5220 defsubr (&Sidentity
);
5223 defsubr (&Ssafe_length
);
5224 defsubr (&Sstring_bytes
);
5225 defsubr (&Sstring_equal
);
5226 defsubr (&Scompare_strings
);
5227 defsubr (&Sstring_lessp
);
5228 defsubr (&Sstring_version_lessp
);
5229 defsubr (&Sstring_collate_lessp
);
5230 defsubr (&Sstring_collate_equalp
);
5233 defsubr (&Svconcat
);
5234 defsubr (&Scopy_sequence
);
5235 defsubr (&Sstring_make_multibyte
);
5236 defsubr (&Sstring_make_unibyte
);
5237 defsubr (&Sstring_as_multibyte
);
5238 defsubr (&Sstring_as_unibyte
);
5239 defsubr (&Sstring_to_multibyte
);
5240 defsubr (&Sstring_to_unibyte
);
5241 defsubr (&Scopy_alist
);
5242 defsubr (&Ssubstring
);
5243 defsubr (&Ssubstring_no_properties
);
5256 defsubr (&Snreverse
);
5257 defsubr (&Sreverse
);
5259 defsubr (&Splist_get
);
5261 defsubr (&Splist_put
);
5263 defsubr (&Slax_plist_get
);
5264 defsubr (&Slax_plist_put
);
5267 defsubr (&Sequal_including_properties
);
5268 defsubr (&Sfillarray
);
5269 defsubr (&Sclear_string
);
5274 defsubr (&Smapconcat
);
5275 defsubr (&Syes_or_no_p
);
5276 defsubr (&Sload_average
);
5277 defsubr (&Sfeaturep
);
5278 defsubr (&Srequire
);
5279 defsubr (&Sprovide
);
5280 defsubr (&Splist_member
);
5281 defsubr (&Swidget_put
);
5282 defsubr (&Swidget_get
);
5283 defsubr (&Swidget_apply
);
5284 defsubr (&Sbase64_encode_region
);
5285 defsubr (&Sbase64_decode_region
);
5286 defsubr (&Sbase64_encode_string
);
5287 defsubr (&Sbase64_decode_string
);
5289 defsubr (&Ssecure_hash_algorithms
);
5290 defsubr (&Ssecure_hash
);
5291 defsubr (&Sbuffer_hash
);
5292 defsubr (&Slocale_info
);