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