fc1d70015f258345fb0285ccc2275c260c827a75
[chise/xemacs-chise.git.1] / src / fns.c
1 /* Random utility Lisp functions.
2    Copyright (C) 1985, 86, 87, 93, 94, 95 Free Software Foundation, Inc.
3    Copyright (C) 1995, 1996 Ben Wing.
4
5 This file is part of XEmacs.
6
7 XEmacs is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 XEmacs is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with XEmacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Synched up with: Mule 2.0, FSF 19.30. */
23
24 /* This file has been Mule-ized. */
25
26 /* Note: FSF 19.30 has bool vectors.  We have bit vectors. */
27
28 /* Hacked on for Mule by Ben Wing, December 1994, January 1995. */
29
30 #include <config.h>
31
32 /* Note on some machines this defines `vector' as a typedef,
33    so make sure we don't use that name in this file.  */
34 #undef vector
35 #define vector *****
36
37 #include "lisp.h"
38
39 #include "sysfile.h"
40
41 #include "buffer.h"
42 #include "bytecode.h"
43 #include "device.h"
44 #include "events.h"
45 #include "extents.h"
46 #include "frame.h"
47 #include "systime.h"
48 #include "insdel.h"
49 #include "lstream.h"
50 #include "opaque.h"
51
52 /* NOTE: This symbol is also used in lread.c */
53 #define FEATUREP_SYNTAX
54
55 Lisp_Object Qstring_lessp;
56 Lisp_Object Qidentity;
57
58 static int internal_old_equal (Lisp_Object, Lisp_Object, int);
59 Lisp_Object safe_copy_tree (Lisp_Object arg, Lisp_Object vecp, int depth);
60
61 static Lisp_Object
62 mark_bit_vector (Lisp_Object obj)
63 {
64   return Qnil;
65 }
66
67 static void
68 print_bit_vector (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
69 {
70   size_t i;
71   Lisp_Bit_Vector *v = XBIT_VECTOR (obj);
72   size_t len = bit_vector_length (v);
73   size_t last = len;
74
75   if (INTP (Vprint_length))
76     last = min (len, XINT (Vprint_length));
77   write_c_string ("#*", printcharfun);
78   for (i = 0; i < last; i++)
79     {
80       if (bit_vector_bit (v, i))
81         write_c_string ("1", printcharfun);
82       else
83         write_c_string ("0", printcharfun);
84     }
85
86   if (last != len)
87     write_c_string ("...", printcharfun);
88 }
89
90 static int
91 bit_vector_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
92 {
93   Lisp_Bit_Vector *v1 = XBIT_VECTOR (obj1);
94   Lisp_Bit_Vector *v2 = XBIT_VECTOR (obj2);
95
96   return ((bit_vector_length (v1) == bit_vector_length (v2)) &&
97           !memcmp (v1->bits, v2->bits,
98                    BIT_VECTOR_LONG_STORAGE (bit_vector_length (v1)) *
99                    sizeof (long)));
100 }
101
102 static unsigned long
103 bit_vector_hash (Lisp_Object obj, int depth)
104 {
105   Lisp_Bit_Vector *v = XBIT_VECTOR (obj);
106   return HASH2 (bit_vector_length (v),
107                 memory_hash (v->bits,
108                              BIT_VECTOR_LONG_STORAGE (bit_vector_length (v)) *
109                              sizeof (long)));
110 }
111
112 static size_t
113 size_bit_vector (const void *lheader)
114 {
115   Lisp_Bit_Vector *v = (Lisp_Bit_Vector *) lheader;
116   return FLEXIBLE_ARRAY_STRUCT_SIZEOF (Lisp_Bit_Vector, bits,
117                                        BIT_VECTOR_LONG_STORAGE (bit_vector_length (v)));
118 }
119
120 static const struct lrecord_description bit_vector_description[] = {
121   { XD_LISP_OBJECT, offsetof (Lisp_Bit_Vector, next) },
122   { XD_END }
123 };
124
125
126 DEFINE_BASIC_LRECORD_SEQUENCE_IMPLEMENTATION ("bit-vector", bit_vector,
127                                               mark_bit_vector, print_bit_vector, 0,
128                                               bit_vector_equal, bit_vector_hash,
129                                               bit_vector_description, size_bit_vector,
130                                               Lisp_Bit_Vector);
131 \f
132 DEFUN ("identity", Fidentity, 1, 1, 0, /*
133 Return the argument unchanged.
134 */
135        (arg))
136 {
137   return arg;
138 }
139
140 extern long get_random (void);
141 extern void seed_random (long arg);
142
143 DEFUN ("random", Frandom, 0, 1, 0, /*
144 Return a pseudo-random number.
145 All integers representable in Lisp are equally likely.
146   On most systems, this is 28 bits' worth.
147 With positive integer argument N, return random number in interval [0,N).
148 With argument t, set the random number seed from the current time and pid.
149 */
150        (limit))
151 {
152   EMACS_INT val;
153   unsigned long denominator;
154
155   if (EQ (limit, Qt))
156     seed_random (getpid () + time (NULL));
157   if (NATNUMP (limit) && !ZEROP (limit))
158     {
159       /* Try to take our random number from the higher bits of VAL,
160          not the lower, since (says Gentzel) the low bits of `random'
161          are less random than the higher ones.  We do this by using the
162          quotient rather than the remainder.  At the high end of the RNG
163          it's possible to get a quotient larger than limit; discarding
164          these values eliminates the bias that would otherwise appear
165          when using a large limit.  */
166       denominator = ((unsigned long)1 << VALBITS) / XINT (limit);
167       do
168         val = get_random () / denominator;
169       while (val >= XINT (limit));
170     }
171   else
172     val = get_random ();
173
174   return make_int (val);
175 }
176 \f
177 /* Random data-structure functions */
178
179 #ifdef LOSING_BYTECODE
180
181 /* #### Delete this shit */
182
183 /* Charcount is a misnomer here as we might be dealing with the
184    length of a vector or list, but emphasizes that we're not dealing
185    with Bytecounts in strings */
186 static Charcount
187 length_with_bytecode_hack (Lisp_Object seq)
188 {
189   if (!COMPILED_FUNCTIONP (seq))
190     return XINT (Flength (seq));
191   else
192     {
193       Lisp_Compiled_Function *f = XCOMPILED_FUNCTION (seq);
194
195       return (f->flags.interactivep ? COMPILED_INTERACTIVE :
196               f->flags.domainp      ? COMPILED_DOMAIN :
197               COMPILED_DOC_STRING)
198         + 1;
199     }
200 }
201
202 #endif /* LOSING_BYTECODE */
203
204 void
205 check_losing_bytecode (const char *function, Lisp_Object seq)
206 {
207   if (COMPILED_FUNCTIONP (seq))
208     error_with_frob
209       (seq,
210        "As of 20.3, `%s' no longer works with compiled-function objects",
211        function);
212 }
213
214 DEFUN ("length", Flength, 1, 1, 0, /*
215 Return the length of vector, bit vector, list or string SEQUENCE.
216 */
217        (sequence))
218 {
219  retry:
220   if (STRINGP (sequence))
221     return make_int (XSTRING_CHAR_LENGTH (sequence));
222   else if (CONSP (sequence))
223     {
224       size_t len;
225       GET_EXTERNAL_LIST_LENGTH (sequence, len);
226       return make_int (len);
227     }
228   else if (VECTORP (sequence))
229     return make_int (XVECTOR_LENGTH (sequence));
230   else if (NILP (sequence))
231     return Qzero;
232   else if (BIT_VECTORP (sequence))
233     return make_int (bit_vector_length (XBIT_VECTOR (sequence)));
234   else
235     {
236       check_losing_bytecode ("length", sequence);
237       sequence = wrong_type_argument (Qsequencep, sequence);
238       goto retry;
239     }
240 }
241
242 DEFUN ("safe-length", Fsafe_length, 1, 1, 0, /*
243 Return the length of a list, but avoid error or infinite loop.
244 This function never gets an error.  If LIST is not really a list,
245 it returns 0.  If LIST is circular, it returns a finite value
246 which is at least the number of distinct elements.
247 */
248        (list))
249 {
250   Lisp_Object hare, tortoise;
251   size_t len;
252
253   for (hare = tortoise = list, len = 0;
254        CONSP (hare) && (! EQ (hare, tortoise) || len == 0);
255        hare = XCDR (hare), len++)
256     {
257       if (len & 1)
258         tortoise = XCDR (tortoise);
259     }
260
261   return make_int (len);
262 }
263
264 /*** string functions. ***/
265
266 DEFUN ("string-equal", Fstring_equal, 2, 2, 0, /*
267 Return t if two strings have identical contents.
268 Case is significant.  Text properties are ignored.
269 \(Under XEmacs, `equal' also ignores text properties and extents in
270 strings, but this is not the case under FSF Emacs 19.  In FSF Emacs 20
271 `equal' is the same as in XEmacs, in that respect.)
272 Symbols are also allowed; their print names are used instead.
273 */
274        (string1, string2))
275 {
276   Bytecount len;
277   Lisp_String *p1, *p2;
278
279   if (SYMBOLP (string1))
280     p1 = XSYMBOL (string1)->name;
281   else
282     {
283       CHECK_STRING (string1);
284       p1 = XSTRING (string1);
285     }
286
287   if (SYMBOLP (string2))
288     p2 = XSYMBOL (string2)->name;
289   else
290     {
291       CHECK_STRING (string2);
292       p2 = XSTRING (string2);
293     }
294
295   return (((len = string_length (p1)) == string_length (p2)) &&
296           !memcmp (string_data (p1), string_data (p2), len)) ? Qt : Qnil;
297 }
298
299
300 DEFUN ("string-lessp", Fstring_lessp, 2, 2, 0, /*
301 Return t if first arg string is less than second in lexicographic order.
302 If I18N2 support (but not Mule support) was compiled in, ordering is
303 determined by the locale. (Case is significant for the default C locale.)
304 In all other cases, comparison is simply done on a character-by-
305 character basis using the numeric value of a character. (Note that
306 this may not produce particularly meaningful results under Mule if
307 characters from different charsets are being compared.)
308
309 Symbols are also allowed; their print names are used instead.
310
311 The reason that the I18N2 locale-specific collation is not used under
312 Mule is that the locale model of internationalization does not handle
313 multiple charsets and thus has no hope of working properly under Mule.
314 What we really should do is create a collation table over all built-in
315 charsets.  This is extremely difficult to do from scratch, however.
316
317 Unicode is a good first step towards solving this problem.  In fact,
318 it is quite likely that a collation table exists (or will exist) for
319 Unicode.  When Unicode support is added to XEmacs/Mule, this problem
320 may be solved.
321 */
322        (string1, string2))
323 {
324   Lisp_String *p1, *p2;
325   Charcount end, len2;
326   int i;
327
328   if (SYMBOLP (string1))
329     p1 = XSYMBOL (string1)->name;
330   else
331     {
332       CHECK_STRING (string1);
333       p1 = XSTRING (string1);
334     }
335
336   if (SYMBOLP (string2))
337     p2 = XSYMBOL (string2)->name;
338   else
339     {
340       CHECK_STRING (string2);
341       p2 = XSTRING (string2);
342     }
343
344   end  = string_char_length (p1);
345   len2 = string_char_length (p2);
346   if (end > len2)
347     end = len2;
348
349 #if defined (I18N2) && !defined (MULE)
350   /* There is no hope of this working under Mule.  Even if we converted
351      the data into an external format so that strcoll() processed it
352      properly, it would still not work because strcoll() does not
353      handle multiple locales.  This is the fundamental flaw in the
354      locale model. */
355   {
356     Bytecount bcend = charcount_to_bytecount (string_data (p1), end);
357     /* Compare strings using collation order of locale. */
358     /* Need to be tricky to handle embedded nulls. */
359
360     for (i = 0; i < bcend; i += strlen((char *) string_data (p1) + i) + 1)
361       {
362         int val = strcoll ((char *) string_data (p1) + i,
363                            (char *) string_data (p2) + i);
364         if (val < 0)
365           return Qt;
366         if (val > 0)
367           return Qnil;
368       }
369   }
370 #else /* not I18N2, or MULE */
371   {
372     Bufbyte *ptr1 = string_data (p1);
373     Bufbyte *ptr2 = string_data (p2);
374
375     /* #### It is not really necessary to do this: We could compare
376        byte-by-byte and still get a reasonable comparison, since this
377        would compare characters with a charset in the same way.  With
378        a little rearrangement of the leading bytes, we could make most
379        inter-charset comparisons work out the same, too; even if some
380        don't, this is not a big deal because inter-charset comparisons
381        aren't really well-defined anyway. */
382     for (i = 0; i < end; i++)
383       {
384         if (charptr_emchar (ptr1) != charptr_emchar (ptr2))
385           return charptr_emchar (ptr1) < charptr_emchar (ptr2) ? Qt : Qnil;
386         INC_CHARPTR (ptr1);
387         INC_CHARPTR (ptr2);
388       }
389   }
390 #endif /* not I18N2, or MULE */
391   /* Can't do i < len2 because then comparison between "foo" and "foo^@"
392      won't work right in I18N2 case */
393   return end < len2 ? Qt : Qnil;
394 }
395
396 DEFUN ("string-modified-tick", Fstring_modified_tick, 1, 1, 0, /*
397 Return STRING's tick counter, incremented for each change to the string.
398 Each string has a tick counter which is incremented each time the contents
399 of the string are changed (e.g. with `aset').  It wraps around occasionally.
400 */
401        (string))
402 {
403   Lisp_String *s;
404
405   CHECK_STRING (string);
406   s = XSTRING (string);
407   if (CONSP (s->plist) && INTP (XCAR (s->plist)))
408     return XCAR (s->plist);
409   else
410     return Qzero;
411 }
412
413 void
414 bump_string_modiff (Lisp_Object str)
415 {
416   Lisp_String *s = XSTRING (str);
417   Lisp_Object *ptr = &s->plist;
418
419 #ifdef I18N3
420   /* #### remove the `string-translatable' property from the string,
421      if there is one. */
422 #endif
423   /* skip over extent info if it's there */
424   if (CONSP (*ptr) && EXTENT_INFOP (XCAR (*ptr)))
425     ptr = &XCDR (*ptr);
426   if (CONSP (*ptr) && INTP (XCAR (*ptr)))
427     XSETINT (XCAR (*ptr), 1+XINT (XCAR (*ptr)));
428   else
429     *ptr = Fcons (make_int (1), *ptr);
430 }
431
432 \f
433 enum  concat_target_type { c_cons, c_string, c_vector, c_bit_vector };
434 static Lisp_Object concat (int nargs, Lisp_Object *args,
435                            enum concat_target_type target_type,
436                            int last_special);
437
438 Lisp_Object
439 concat2 (Lisp_Object string1, Lisp_Object string2)
440 {
441   Lisp_Object args[2];
442   args[0] = string1;
443   args[1] = string2;
444   return concat (2, args, c_string, 0);
445 }
446
447 Lisp_Object
448 concat3 (Lisp_Object string1, Lisp_Object string2, Lisp_Object string3)
449 {
450   Lisp_Object args[3];
451   args[0] = string1;
452   args[1] = string2;
453   args[2] = string3;
454   return concat (3, args, c_string, 0);
455 }
456
457 Lisp_Object
458 vconcat2 (Lisp_Object vec1, Lisp_Object vec2)
459 {
460   Lisp_Object args[2];
461   args[0] = vec1;
462   args[1] = vec2;
463   return concat (2, args, c_vector, 0);
464 }
465
466 Lisp_Object
467 vconcat3 (Lisp_Object vec1, Lisp_Object vec2, Lisp_Object vec3)
468 {
469   Lisp_Object args[3];
470   args[0] = vec1;
471   args[1] = vec2;
472   args[2] = vec3;
473   return concat (3, args, c_vector, 0);
474 }
475
476 DEFUN ("append", Fappend, 0, MANY, 0, /*
477 Concatenate all the arguments and make the result a list.
478 The result is a list whose elements are the elements of all the arguments.
479 Each argument may be a list, vector, bit vector, or string.
480 The last argument is not copied, just used as the tail of the new list.
481 Also see: `nconc'.
482 */
483        (int nargs, Lisp_Object *args))
484 {
485   return concat (nargs, args, c_cons, 1);
486 }
487
488 DEFUN ("concat", Fconcat, 0, MANY, 0, /*
489 Concatenate all the arguments and make the result a string.
490 The result is a string whose elements are the elements of all the arguments.
491 Each argument may be a string or a list or vector of characters.
492
493 As of XEmacs 21.0, this function does NOT accept individual integers
494 as arguments.  Old code that relies on, for example, (concat "foo" 50)
495 returning "foo50" will fail.  To fix such code, either apply
496 `int-to-string' to the integer argument, or use `format'.
497 */
498        (int nargs, Lisp_Object *args))
499 {
500   return concat (nargs, args, c_string, 0);
501 }
502
503 DEFUN ("vconcat", Fvconcat, 0, MANY, 0, /*
504 Concatenate all the arguments and make the result a vector.
505 The result is a vector whose elements are the elements of all the arguments.
506 Each argument may be a list, vector, bit vector, or string.
507 */
508        (int nargs, Lisp_Object *args))
509 {
510   return concat (nargs, args, c_vector, 0);
511 }
512
513 DEFUN ("bvconcat", Fbvconcat, 0, MANY, 0, /*
514 Concatenate all the arguments and make the result a bit vector.
515 The result is a bit vector whose elements are the elements of all the
516 arguments.  Each argument may be a list, vector, bit vector, or string.
517 */
518        (int nargs, Lisp_Object *args))
519 {
520   return concat (nargs, args, c_bit_vector, 0);
521 }
522
523 /* Copy a (possibly dotted) list.  LIST must be a cons.
524    Can't use concat (1, &alist, c_cons, 0) - doesn't handle dotted lists. */
525 static Lisp_Object
526 copy_list (Lisp_Object list)
527 {
528   Lisp_Object list_copy = Fcons (XCAR (list), XCDR (list));
529   Lisp_Object last = list_copy;
530   Lisp_Object hare, tortoise;
531   size_t len;
532
533   for (tortoise = hare = XCDR (list), len = 1;
534        CONSP (hare);
535        hare = XCDR (hare), len++)
536     {
537       XCDR (last) = Fcons (XCAR (hare), XCDR (hare));
538       last = XCDR (last);
539
540       if (len < CIRCULAR_LIST_SUSPICION_LENGTH)
541         continue;
542       if (len & 1)
543         tortoise = XCDR (tortoise);
544       if (EQ (tortoise, hare))
545         signal_circular_list_error (list);
546     }
547
548   return list_copy;
549 }
550
551 DEFUN ("copy-list", Fcopy_list, 1, 1, 0, /*
552 Return a copy of list LIST, which may be a dotted list.
553 The elements of LIST are not copied; they are shared
554 with the original.
555 */
556        (list))
557 {
558  again:
559   if (NILP  (list)) return list;
560   if (CONSP (list)) return copy_list (list);
561
562   list = wrong_type_argument (Qlistp, list);
563   goto again;
564 }
565
566 DEFUN ("copy-sequence", Fcopy_sequence, 1, 1, 0, /*
567 Return a copy of list, vector, bit vector or string SEQUENCE.
568 The elements of a list or vector are not copied; they are shared
569 with the original. SEQUENCE may be a dotted list.
570 */
571        (sequence))
572 {
573  again:
574   if (NILP        (sequence)) return sequence;
575   if (CONSP       (sequence)) return copy_list (sequence);
576   if (STRINGP     (sequence)) return concat (1, &sequence, c_string,     0);
577   if (VECTORP     (sequence)) return concat (1, &sequence, c_vector,     0);
578   if (BIT_VECTORP (sequence)) return concat (1, &sequence, c_bit_vector, 0);
579
580   check_losing_bytecode ("copy-sequence", sequence);
581   sequence = wrong_type_argument (Qsequencep, sequence);
582   goto again;
583 }
584
585 struct merge_string_extents_struct
586 {
587   Lisp_Object string;
588   Bytecount entry_offset;
589   Bytecount entry_length;
590 };
591
592 static Lisp_Object
593 concat (int nargs, Lisp_Object *args,
594         enum concat_target_type target_type,
595         int last_special)
596 {
597   Lisp_Object val;
598   Lisp_Object tail = Qnil;
599   int toindex;
600   int argnum;
601   Lisp_Object last_tail;
602   Lisp_Object prev;
603   struct merge_string_extents_struct *args_mse = 0;
604   Bufbyte *string_result = 0;
605   Bufbyte *string_result_ptr = 0;
606   struct gcpro gcpro1;
607
608   /* The modus operandi in Emacs is "caller gc-protects args".
609      However, concat is called many times in Emacs on freshly
610      created stuff.  So we help those callers out by protecting
611      the args ourselves to save them a lot of temporary-variable
612      grief. */
613
614   GCPRO1 (args[0]);
615   gcpro1.nvars = nargs;
616
617 #ifdef I18N3
618   /* #### if the result is a string and any of the strings have a string
619      for the `string-translatable' property, then concat should also
620      concat the args but use the `string-translatable' strings, and store
621      the result in the returned string's `string-translatable' property. */
622 #endif
623   if (target_type == c_string)
624     args_mse = alloca_array (struct merge_string_extents_struct, nargs);
625
626   /* In append, the last arg isn't treated like the others */
627   if (last_special && nargs > 0)
628     {
629       nargs--;
630       last_tail = args[nargs];
631     }
632   else
633     last_tail = Qnil;
634
635   /* Check and coerce the arguments. */
636   for (argnum = 0; argnum < nargs; argnum++)
637     {
638       Lisp_Object seq = args[argnum];
639       if (LISTP (seq))
640         ;
641       else if (VECTORP (seq) || STRINGP (seq) || BIT_VECTORP (seq))
642         ;
643 #ifdef LOSING_BYTECODE
644       else if (COMPILED_FUNCTIONP (seq))
645         /* Urk!  We allow this, for "compatibility"... */
646         ;
647 #endif
648 #if 0                           /* removed for XEmacs 21 */
649       else if (INTP (seq))
650         /* This is too revolting to think about but maintains
651            compatibility with FSF (and lots and lots of old code). */
652         args[argnum] = Fnumber_to_string (seq);
653 #endif
654       else
655         {
656           check_losing_bytecode ("concat", seq);
657           args[argnum] = wrong_type_argument (Qsequencep, seq);
658         }
659
660       if (args_mse)
661         {
662           if (STRINGP (seq))
663             args_mse[argnum].string = seq;
664           else
665             args_mse[argnum].string = Qnil;
666         }
667     }
668
669   {
670     /* Charcount is a misnomer here as we might be dealing with the
671        length of a vector or list, but emphasizes that we're not dealing
672        with Bytecounts in strings */
673     Charcount total_length;
674
675     for (argnum = 0, total_length = 0; argnum < nargs; argnum++)
676       {
677 #ifdef LOSING_BYTECODE
678         Charcount thislen = length_with_bytecode_hack (args[argnum]);
679 #else
680         Charcount thislen = XINT (Flength (args[argnum]));
681 #endif
682         total_length += thislen;
683       }
684
685     switch (target_type)
686       {
687       case c_cons:
688         if (total_length == 0)
689           /* In append, if all but last arg are nil, return last arg */
690           RETURN_UNGCPRO (last_tail);
691         val = Fmake_list (make_int (total_length), Qnil);
692         break;
693       case c_vector:
694         val = make_vector (total_length, Qnil);
695         break;
696       case c_bit_vector:
697         val = make_bit_vector (total_length, Qzero);
698         break;
699       case c_string:
700         /* We don't make the string yet because we don't know the
701            actual number of bytes.  This loop was formerly written
702            to call Fmake_string() here and then call set_string_char()
703            for each char.  This seems logical enough but is waaaaaaaay
704            slow -- set_string_char() has to scan the whole string up
705            to the place where the substitution is called for in order
706            to find the place to change, and may have to do some
707            realloc()ing in order to make the char fit properly.
708            O(N^2) yuckage. */
709         val = Qnil;
710         string_result = (Bufbyte *) alloca (total_length * MAX_EMCHAR_LEN);
711         string_result_ptr = string_result;
712         break;
713       default:
714         val = Qnil;
715         abort ();
716       }
717   }
718
719
720   if (CONSP (val))
721     tail = val, toindex = -1;   /* -1 in toindex is flag we are
722                                     making a list */
723   else
724     toindex = 0;
725
726   prev = Qnil;
727
728   for (argnum = 0; argnum < nargs; argnum++)
729     {
730       Charcount thisleni = 0;
731       Charcount thisindex = 0;
732       Lisp_Object seq = args[argnum];
733       Bufbyte *string_source_ptr = 0;
734       Bufbyte *string_prev_result_ptr = string_result_ptr;
735
736       if (!CONSP (seq))
737         {
738 #ifdef LOSING_BYTECODE
739           thisleni = length_with_bytecode_hack (seq);
740 #else
741           thisleni = XINT (Flength (seq));
742 #endif
743         }
744       if (STRINGP (seq))
745         string_source_ptr = XSTRING_DATA (seq);
746
747       while (1)
748         {
749           Lisp_Object elt;
750
751           /* We've come to the end of this arg, so exit. */
752           if (NILP (seq))
753             break;
754
755           /* Fetch next element of `seq' arg into `elt' */
756           if (CONSP (seq))
757             {
758               elt = XCAR (seq);
759               seq = XCDR (seq);
760             }
761           else
762             {
763               if (thisindex >= thisleni)
764                 break;
765
766               if (STRINGP (seq))
767                 {
768                   elt = make_char (charptr_emchar (string_source_ptr));
769                   INC_CHARPTR (string_source_ptr);
770                 }
771               else if (VECTORP (seq))
772                 elt = XVECTOR_DATA (seq)[thisindex];
773               else if (BIT_VECTORP (seq))
774                 elt = make_int (bit_vector_bit (XBIT_VECTOR (seq),
775                                                 thisindex));
776               else
777                 elt = Felt (seq, make_int (thisindex));
778               thisindex++;
779             }
780
781           /* Store into result */
782           if (toindex < 0)
783             {
784               /* toindex negative means we are making a list */
785               XCAR (tail) = elt;
786               prev = tail;
787               tail = XCDR (tail);
788             }
789           else if (VECTORP (val))
790             XVECTOR_DATA (val)[toindex++] = elt;
791           else if (BIT_VECTORP (val))
792             {
793               CHECK_BIT (elt);
794               set_bit_vector_bit (XBIT_VECTOR (val), toindex++, XINT (elt));
795             }
796           else
797             {
798               CHECK_CHAR_COERCE_INT (elt);
799               string_result_ptr += set_charptr_emchar (string_result_ptr,
800                                                        XCHAR (elt));
801             }
802         }
803       if (args_mse)
804         {
805           args_mse[argnum].entry_offset =
806             string_prev_result_ptr - string_result;
807           args_mse[argnum].entry_length =
808             string_result_ptr - string_prev_result_ptr;
809         }
810     }
811
812   /* Now we finally make the string. */
813   if (target_type == c_string)
814     {
815       val = make_string (string_result, string_result_ptr - string_result);
816       for (argnum = 0; argnum < nargs; argnum++)
817         {
818           if (STRINGP (args_mse[argnum].string))
819             copy_string_extents (val, args_mse[argnum].string,
820                                  args_mse[argnum].entry_offset, 0,
821                                  args_mse[argnum].entry_length);
822         }
823     }
824
825   if (!NILP (prev))
826     XCDR (prev) = last_tail;
827
828   RETURN_UNGCPRO (val);
829 }
830 \f
831 DEFUN ("copy-alist", Fcopy_alist, 1, 1, 0, /*
832 Return a copy of ALIST.
833 This is an alist which represents the same mapping from objects to objects,
834 but does not share the alist structure with ALIST.
835 The objects mapped (cars and cdrs of elements of the alist)
836 are shared, however.
837 Elements of ALIST that are not conses are also shared.
838 */
839        (alist))
840 {
841   Lisp_Object tail;
842
843   if (NILP (alist))
844     return alist;
845   CHECK_CONS (alist);
846
847   alist = concat (1, &alist, c_cons, 0);
848   for (tail = alist; CONSP (tail); tail = XCDR (tail))
849     {
850       Lisp_Object car = XCAR (tail);
851
852       if (CONSP (car))
853         XCAR (tail) = Fcons (XCAR (car), XCDR (car));
854     }
855   return alist;
856 }
857
858 DEFUN ("copy-tree", Fcopy_tree, 1, 2, 0, /*
859 Return a copy of a list and substructures.
860 The argument is copied, and any lists contained within it are copied
861 recursively.  Circularities and shared substructures are not preserved.
862 Second arg VECP causes vectors to be copied, too.  Strings and bit vectors
863 are not copied.
864 */
865        (arg, vecp))
866 {
867   return safe_copy_tree (arg, vecp, 0);
868 }
869
870 Lisp_Object
871 safe_copy_tree (Lisp_Object arg, Lisp_Object vecp, int depth)
872 {
873   if (depth > 200)
874     signal_simple_error ("Stack overflow in copy-tree", arg);
875     
876   if (CONSP (arg))
877     {
878       Lisp_Object rest;
879       rest = arg = Fcopy_sequence (arg);
880       while (CONSP (rest))
881         {
882           Lisp_Object elt = XCAR (rest);
883           QUIT;
884           if (CONSP (elt) || VECTORP (elt))
885             XCAR (rest) = safe_copy_tree (elt, vecp, depth + 1);
886           if (VECTORP (XCDR (rest))) /* hack for (a b . [c d]) */
887             XCDR (rest) = safe_copy_tree (XCDR (rest), vecp, depth +1);
888           rest = XCDR (rest);
889         }
890     }
891   else if (VECTORP (arg) && ! NILP (vecp))
892     {
893       int i = XVECTOR_LENGTH (arg);
894       int j;
895       arg = Fcopy_sequence (arg);
896       for (j = 0; j < i; j++)
897         {
898           Lisp_Object elt = XVECTOR_DATA (arg) [j];
899           QUIT;
900           if (CONSP (elt) || VECTORP (elt))
901             XVECTOR_DATA (arg) [j] = safe_copy_tree (elt, vecp, depth + 1);
902         }
903     }
904   return arg;
905 }
906
907 DEFUN ("substring", Fsubstring, 2, 3, 0, /*
908 Return the substring of STRING starting at START and ending before END.
909 END may be nil or omitted; then the substring runs to the end of STRING.
910 If START or END is negative, it counts from the end.
911 Relevant parts of the string-extent-data are copied to the new string.
912 */
913        (string, start, end))
914 {
915   Charcount ccstart, ccend;
916   Bytecount bstart, blen;
917   Lisp_Object val;
918
919   CHECK_STRING (string);
920   CHECK_INT (start);
921   get_string_range_char (string, start, end, &ccstart, &ccend,
922                          GB_HISTORICAL_STRING_BEHAVIOR);
923   bstart = charcount_to_bytecount (XSTRING_DATA (string), ccstart);
924   blen = charcount_to_bytecount (XSTRING_DATA (string) + bstart, ccend - ccstart);
925   val = make_string (XSTRING_DATA (string) + bstart, blen);
926   /* Copy any applicable extent information into the new string. */
927   copy_string_extents (val, string, 0, bstart, blen);
928   return val;
929 }
930
931 DEFUN ("subseq", Fsubseq, 2, 3, 0, /*
932 Return the subsequence of SEQUENCE starting at START and ending before END.
933 END may be omitted; then the subsequence runs to the end of SEQUENCE.
934 If START or END is negative, it counts from the end.
935 The returned subsequence is always of the same type as SEQUENCE.
936 If SEQUENCE is a string, relevant parts of the string-extent-data
937 are copied to the new string.
938 */
939        (sequence, start, end))
940 {
941   EMACS_INT len, s, e;
942
943   if (STRINGP (sequence))
944     return Fsubstring (sequence, start, end);
945
946   len = XINT (Flength (sequence));
947
948   CHECK_INT (start);
949   s = XINT (start);
950   if (s < 0)
951     s = len + s;
952
953   if (NILP (end))
954     e = len;
955   else
956     {
957       CHECK_INT (end);
958       e = XINT (end);
959       if (e < 0)
960         e = len + e;
961     }
962
963   if (!(0 <= s && s <= e && e <= len))
964     args_out_of_range_3 (sequence, make_int (s), make_int (e));
965
966   if (VECTORP (sequence))
967     {
968       Lisp_Object result = make_vector (e - s, Qnil);
969       EMACS_INT i;
970       Lisp_Object *in_elts  = XVECTOR_DATA (sequence);
971       Lisp_Object *out_elts = XVECTOR_DATA (result);
972
973       for (i = s; i < e; i++)
974         out_elts[i - s] = in_elts[i];
975       return result;
976     }
977   else if (LISTP (sequence))
978     {
979       Lisp_Object result = Qnil;
980       EMACS_INT i;
981
982       sequence = Fnthcdr (make_int (s), sequence);
983
984       for (i = s; i < e; i++)
985         {
986           result = Fcons (Fcar (sequence), result);
987           sequence = Fcdr (sequence);
988         }
989
990       return Fnreverse (result);
991     }
992   else if (BIT_VECTORP (sequence))
993     {
994       Lisp_Object result = make_bit_vector (e - s, Qzero);
995       EMACS_INT i;
996
997       for (i = s; i < e; i++)
998         set_bit_vector_bit (XBIT_VECTOR (result), i - s,
999                             bit_vector_bit (XBIT_VECTOR (sequence), i));
1000       return result;
1001     }
1002   else
1003     {
1004       abort (); /* unreachable, since Flength (sequence) did not get
1005                    an error */
1006       return Qnil;
1007     }
1008 }
1009
1010 \f
1011 DEFUN ("nthcdr", Fnthcdr, 2, 2, 0, /*
1012 Take cdr N times on LIST, and return the result.
1013 */
1014        (n, list))
1015 {
1016   REGISTER size_t i;
1017   REGISTER Lisp_Object tail = list;
1018   CHECK_NATNUM (n);
1019   for (i = XINT (n); i; i--)
1020     {
1021       if (CONSP (tail))
1022         tail = XCDR (tail);
1023       else if (NILP (tail))
1024         return Qnil;
1025       else
1026         {
1027           tail = wrong_type_argument (Qlistp, tail);
1028           i++;
1029         }
1030     }
1031   return tail;
1032 }
1033
1034 DEFUN ("nth", Fnth, 2, 2, 0, /*
1035 Return the Nth element of LIST.
1036 N counts from zero.  If LIST is not that long, nil is returned.
1037 */
1038        (n, list))
1039 {
1040   return Fcar (Fnthcdr (n, list));
1041 }
1042
1043 DEFUN ("elt", Felt, 2, 2, 0, /*
1044 Return element of SEQUENCE at index N.
1045 */
1046        (sequence, n))
1047 {
1048  retry:
1049   CHECK_INT_COERCE_CHAR (n); /* yuck! */
1050   if (LISTP (sequence))
1051     {
1052       Lisp_Object tem = Fnthcdr (n, sequence);
1053       /* #### Utterly, completely, fucking disgusting.
1054        * #### The whole point of "elt" is that it operates on
1055        * #### sequences, and does error- (bounds-) checking.
1056        */
1057       if (CONSP (tem))
1058         return XCAR (tem);
1059       else
1060 #if 1
1061         /* This is The Way It Has Always Been. */
1062         return Qnil;
1063 #else
1064         /* This is The Way Mly and Cltl2 say It Should Be. */
1065         args_out_of_range (sequence, n);
1066 #endif
1067     }
1068   else if (STRINGP     (sequence) ||
1069            VECTORP     (sequence) ||
1070            BIT_VECTORP (sequence))
1071     return Faref (sequence, n);
1072 #ifdef LOSING_BYTECODE
1073   else if (COMPILED_FUNCTIONP (sequence))
1074     {
1075       EMACS_INT idx = XINT (n);
1076       if (idx < 0)
1077         {
1078         lose:
1079           args_out_of_range (sequence, n);
1080         }
1081       /* Utter perversity */
1082       {
1083         Lisp_Compiled_Function *f = XCOMPILED_FUNCTION (sequence);
1084         switch (idx)
1085           {
1086           case COMPILED_ARGLIST:
1087             return compiled_function_arglist (f);
1088           case COMPILED_INSTRUCTIONS:
1089             return compiled_function_instructions (f);
1090           case COMPILED_CONSTANTS:
1091             return compiled_function_constants (f);
1092           case COMPILED_STACK_DEPTH:
1093             return compiled_function_stack_depth (f);
1094           case COMPILED_DOC_STRING:
1095             return compiled_function_documentation (f);
1096           case COMPILED_DOMAIN:
1097             return compiled_function_domain (f);
1098           case COMPILED_INTERACTIVE:
1099             if (f->flags.interactivep)
1100               return compiled_function_interactive (f);
1101             /* if we return nil, can't tell interactive with no args
1102                from noninteractive. */
1103             goto lose;
1104           default:
1105             goto lose;
1106           }
1107       }
1108     }
1109 #endif /* LOSING_BYTECODE */
1110   else
1111     {
1112       check_losing_bytecode ("elt", sequence);
1113       sequence = wrong_type_argument (Qsequencep, sequence);
1114       goto retry;
1115     }
1116 }
1117
1118 DEFUN ("last", Flast, 1, 2, 0, /*
1119 Return the tail of list LIST, of length N (default 1).
1120 LIST may be a dotted list, but not a circular list.
1121 Optional argument N must be a non-negative integer.
1122 If N is zero, then the atom that terminates the list is returned.
1123 If N is greater than the length of LIST, then LIST itself is returned.
1124 */
1125        (list, n))
1126 {
1127   EMACS_INT int_n, count;
1128   Lisp_Object retval, tortoise, hare;
1129
1130   CHECK_LIST (list);
1131
1132   if (NILP (n))
1133     int_n = 1;
1134   else
1135     {
1136       CHECK_NATNUM (n);
1137       int_n = XINT (n);
1138     }
1139
1140   for (retval = tortoise = hare = list, count = 0;
1141        CONSP (hare);
1142        hare = XCDR (hare),
1143          (int_n-- <= 0 ? ((void) (retval = XCDR (retval))) : (void)0),
1144          count++)
1145     {
1146       if (count < CIRCULAR_LIST_SUSPICION_LENGTH) continue;
1147
1148       if (count & 1)
1149         tortoise = XCDR (tortoise);
1150       if (EQ (hare, tortoise))
1151         signal_circular_list_error (list);
1152     }
1153
1154   return retval;
1155 }
1156
1157 DEFUN ("nbutlast", Fnbutlast, 1, 2, 0, /*
1158 Modify LIST to remove the last N (default 1) elements.
1159 If LIST has N or fewer elements, nil is returned and LIST is unmodified.
1160 */
1161        (list, n))
1162 {
1163   EMACS_INT int_n;
1164
1165   CHECK_LIST (list);
1166
1167   if (NILP (n))
1168     int_n = 1;
1169   else
1170     {
1171       CHECK_NATNUM (n);
1172       int_n = XINT (n);
1173     }
1174
1175   {
1176     Lisp_Object last_cons = list;
1177
1178     EXTERNAL_LIST_LOOP_1 (list)
1179       {
1180         if (int_n-- < 0)
1181           last_cons = XCDR (last_cons);
1182       }
1183
1184     if (int_n >= 0)
1185       return Qnil;
1186
1187     XCDR (last_cons) = Qnil;
1188     return list;
1189   }
1190 }
1191
1192 DEFUN ("butlast", Fbutlast, 1, 2, 0, /*
1193 Return a copy of LIST with the last N (default 1) elements removed.
1194 If LIST has N or fewer elements, nil is returned.
1195 */
1196        (list, n))
1197 {
1198   EMACS_INT int_n;
1199
1200   CHECK_LIST (list);
1201
1202   if (NILP (n))
1203     int_n = 1;
1204   else
1205     {
1206       CHECK_NATNUM (n);
1207       int_n = XINT (n);
1208     }
1209
1210   {
1211     Lisp_Object retval = Qnil;
1212     Lisp_Object tail = list;
1213
1214     EXTERNAL_LIST_LOOP_1 (list)
1215       {
1216         if (--int_n < 0)
1217           {
1218             retval = Fcons (XCAR (tail), retval);
1219             tail = XCDR (tail);
1220           }
1221       }
1222
1223     return Fnreverse (retval);
1224   }
1225 }
1226
1227 DEFUN ("member", Fmember, 2, 2, 0, /*
1228 Return non-nil if ELT is an element of LIST.  Comparison done with `equal'.
1229 The value is actually the tail of LIST whose car is ELT.
1230 */
1231        (elt, list))
1232 {
1233   EXTERNAL_LIST_LOOP_3 (list_elt, list, tail)
1234     {
1235       if (internal_equal (elt, list_elt, 0))
1236         return tail;
1237     }
1238   return Qnil;
1239 }
1240
1241 DEFUN ("old-member", Fold_member, 2, 2, 0, /*
1242 Return non-nil if ELT is an element of LIST.  Comparison done with `old-equal'.
1243 The value is actually the tail of LIST whose car is ELT.
1244 This function is provided only for byte-code compatibility with v19.
1245 Do not use it.
1246 */
1247        (elt, list))
1248 {
1249   EXTERNAL_LIST_LOOP_3 (list_elt, list, tail)
1250     {
1251       if (internal_old_equal (elt, list_elt, 0))
1252         return tail;
1253     }
1254   return Qnil;
1255 }
1256
1257 DEFUN ("memq", Fmemq, 2, 2, 0, /*
1258 Return non-nil if ELT is an element of LIST.  Comparison done with `eq'.
1259 The value is actually the tail of LIST whose car is ELT.
1260 */
1261        (elt, list))
1262 {
1263   EXTERNAL_LIST_LOOP_3 (list_elt, list, tail)
1264     {
1265       if (EQ_WITH_EBOLA_NOTICE (elt, list_elt))
1266         return tail;
1267     }
1268   return Qnil;
1269 }
1270
1271 DEFUN ("old-memq", Fold_memq, 2, 2, 0, /*
1272 Return non-nil if ELT is an element of LIST.  Comparison done with `old-eq'.
1273 The value is actually the tail of LIST whose car is ELT.
1274 This function is provided only for byte-code compatibility with v19.
1275 Do not use it.
1276 */
1277        (elt, list))
1278 {
1279   EXTERNAL_LIST_LOOP_3 (list_elt, list, tail)
1280     {
1281       if (HACKEQ_UNSAFE (elt, list_elt))
1282         return tail;
1283     }
1284   return Qnil;
1285 }
1286
1287 Lisp_Object
1288 memq_no_quit (Lisp_Object elt, Lisp_Object list)
1289 {
1290   LIST_LOOP_3 (list_elt, list, tail)
1291     {
1292       if (EQ_WITH_EBOLA_NOTICE (elt, list_elt))
1293         return tail;
1294     }
1295   return Qnil;
1296 }
1297
1298 DEFUN ("assoc", Fassoc, 2, 2, 0, /*
1299 Return non-nil if KEY is `equal' to the car of an element of ALIST.
1300 The value is actually the element of ALIST whose car equals KEY.
1301 */
1302        (key, alist))
1303 {
1304   /* This function can GC. */
1305   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1306     {
1307       if (internal_equal (key, elt_car, 0))
1308         return elt;
1309     }
1310   return Qnil;
1311 }
1312
1313 DEFUN ("old-assoc", Fold_assoc, 2, 2, 0, /*
1314 Return non-nil if KEY is `old-equal' to the car of an element of ALIST.
1315 The value is actually the element of ALIST whose car equals KEY.
1316 */
1317        (key, alist))
1318 {
1319   /* This function can GC. */
1320   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1321     {
1322       if (internal_old_equal (key, elt_car, 0))
1323         return elt;
1324     }
1325   return Qnil;
1326 }
1327
1328 Lisp_Object
1329 assoc_no_quit (Lisp_Object key, Lisp_Object alist)
1330 {
1331   int speccount = specpdl_depth ();
1332   specbind (Qinhibit_quit, Qt);
1333   return unbind_to (speccount, Fassoc (key, alist));
1334 }
1335
1336 DEFUN ("assq", Fassq, 2, 2, 0, /*
1337 Return non-nil if KEY is `eq' to the car of an element of ALIST.
1338 The value is actually the element of ALIST whose car is KEY.
1339 Elements of ALIST that are not conses are ignored.
1340 */
1341        (key, alist))
1342 {
1343   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1344     {
1345       if (EQ_WITH_EBOLA_NOTICE (key, elt_car))
1346         return elt;
1347     }
1348   return Qnil;
1349 }
1350
1351 DEFUN ("old-assq", Fold_assq, 2, 2, 0, /*
1352 Return non-nil if KEY is `old-eq' to the car of an element of ALIST.
1353 The value is actually the element of ALIST whose car is KEY.
1354 Elements of ALIST that are not conses are ignored.
1355 This function is provided only for byte-code compatibility with v19.
1356 Do not use it.
1357 */
1358        (key, alist))
1359 {
1360   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1361     {
1362       if (HACKEQ_UNSAFE (key, elt_car))
1363         return elt;
1364     }
1365   return Qnil;
1366 }
1367
1368 /* Like Fassq but never report an error and do not allow quits.
1369    Use only on lists known never to be circular.  */
1370
1371 Lisp_Object
1372 assq_no_quit (Lisp_Object key, Lisp_Object alist)
1373 {
1374   /* This cannot GC. */
1375   LIST_LOOP_2 (elt, alist)
1376     {
1377       Lisp_Object elt_car = XCAR (elt);
1378       if (EQ_WITH_EBOLA_NOTICE (key, elt_car))
1379         return elt;
1380     }
1381   return Qnil;
1382 }
1383
1384 DEFUN ("rassoc", Frassoc, 2, 2, 0, /*
1385 Return non-nil if VALUE is `equal' to the cdr of an element of ALIST.
1386 The value is actually the element of ALIST whose cdr equals VALUE.
1387 */
1388        (value, alist))
1389 {
1390   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1391     {
1392       if (internal_equal (value, elt_cdr, 0))
1393         return elt;
1394     }
1395   return Qnil;
1396 }
1397
1398 DEFUN ("old-rassoc", Fold_rassoc, 2, 2, 0, /*
1399 Return non-nil if VALUE is `old-equal' to the cdr of an element of ALIST.
1400 The value is actually the element of ALIST whose cdr equals VALUE.
1401 */
1402        (value, alist))
1403 {
1404   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1405     {
1406       if (internal_old_equal (value, elt_cdr, 0))
1407         return elt;
1408     }
1409   return Qnil;
1410 }
1411
1412 DEFUN ("rassq", Frassq, 2, 2, 0, /*
1413 Return non-nil if VALUE is `eq' to the cdr of an element of ALIST.
1414 The value is actually the element of ALIST whose cdr is VALUE.
1415 */
1416        (value, alist))
1417 {
1418   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1419     {
1420       if (EQ_WITH_EBOLA_NOTICE (value, elt_cdr))
1421         return elt;
1422     }
1423   return Qnil;
1424 }
1425
1426 DEFUN ("old-rassq", Fold_rassq, 2, 2, 0, /*
1427 Return non-nil if VALUE is `old-eq' to the cdr of an element of ALIST.
1428 The value is actually the element of ALIST whose cdr is VALUE.
1429 */
1430        (value, alist))
1431 {
1432   EXTERNAL_ALIST_LOOP_4 (elt, elt_car, elt_cdr, alist)
1433     {
1434       if (HACKEQ_UNSAFE (value, elt_cdr))
1435         return elt;
1436     }
1437   return Qnil;
1438 }
1439
1440 /* Like Frassq, but caller must ensure that ALIST is properly
1441    nil-terminated and ebola-free. */
1442 Lisp_Object
1443 rassq_no_quit (Lisp_Object value, Lisp_Object alist)
1444 {
1445   LIST_LOOP_2 (elt, alist)
1446     {
1447       Lisp_Object elt_cdr = XCDR (elt);
1448       if (EQ_WITH_EBOLA_NOTICE (value, elt_cdr))
1449         return elt;
1450     }
1451   return Qnil;
1452 }
1453
1454 \f
1455 DEFUN ("delete", Fdelete, 2, 2, 0, /*
1456 Delete by side effect any occurrences of ELT as a member of LIST.
1457 The modified LIST is returned.  Comparison is done with `equal'.
1458 If the first member of LIST is ELT, there is no way to remove it by side
1459 effect; therefore, write `(setq foo (delete element foo))' to be sure
1460 of changing the value of `foo'.
1461 Also see: `remove'.
1462 */
1463        (elt, list))
1464 {
1465   EXTERNAL_LIST_LOOP_DELETE_IF (list_elt, list,
1466                                 (internal_equal (elt, list_elt, 0)));
1467   return list;
1468 }
1469
1470 DEFUN ("old-delete", Fold_delete, 2, 2, 0, /*
1471 Delete by side effect any occurrences of ELT as a member of LIST.
1472 The modified LIST is returned.  Comparison is done with `old-equal'.
1473 If the first member of LIST is ELT, there is no way to remove it by side
1474 effect; therefore, write `(setq foo (old-delete element foo))' to be sure
1475 of changing the value of `foo'.
1476 */
1477        (elt, list))
1478 {
1479   EXTERNAL_LIST_LOOP_DELETE_IF (list_elt, list,
1480                                 (internal_old_equal (elt, list_elt, 0)));
1481   return list;
1482 }
1483
1484 DEFUN ("delq", Fdelq, 2, 2, 0, /*
1485 Delete by side effect any occurrences of ELT as a member of LIST.
1486 The modified LIST is returned.  Comparison is done with `eq'.
1487 If the first member of LIST is ELT, there is no way to remove it by side
1488 effect; therefore, write `(setq foo (delq element foo))' to be sure of
1489 changing the value of `foo'.
1490 */
1491        (elt, list))
1492 {
1493   EXTERNAL_LIST_LOOP_DELETE_IF (list_elt, list,
1494                                 (EQ_WITH_EBOLA_NOTICE (elt, list_elt)));
1495   return list;
1496 }
1497
1498 DEFUN ("old-delq", Fold_delq, 2, 2, 0, /*
1499 Delete by side effect any occurrences of ELT as a member of LIST.
1500 The modified LIST is returned.  Comparison is done with `old-eq'.
1501 If the first member of LIST is ELT, there is no way to remove it by side
1502 effect; therefore, write `(setq foo (old-delq element foo))' to be sure of
1503 changing the value of `foo'.
1504 */
1505        (elt, list))
1506 {
1507   EXTERNAL_LIST_LOOP_DELETE_IF (list_elt, list,
1508                                 (HACKEQ_UNSAFE (elt, list_elt)));
1509   return list;
1510 }
1511
1512 /* Like Fdelq, but caller must ensure that LIST is properly
1513    nil-terminated and ebola-free. */
1514
1515 Lisp_Object
1516 delq_no_quit (Lisp_Object elt, Lisp_Object list)
1517 {
1518   LIST_LOOP_DELETE_IF (list_elt, list,
1519                        (EQ_WITH_EBOLA_NOTICE (elt, list_elt)));
1520   return list;
1521 }
1522
1523 /* Be VERY careful with this.  This is like delq_no_quit() but
1524    also calls free_cons() on the removed conses.  You must be SURE
1525    that no pointers to the freed conses remain around (e.g.
1526    someone else is pointing to part of the list).  This function
1527    is useful on internal lists that are used frequently and where
1528    the actual list doesn't escape beyond known code bounds. */
1529
1530 Lisp_Object
1531 delq_no_quit_and_free_cons (Lisp_Object elt, Lisp_Object list)
1532 {
1533   REGISTER Lisp_Object tail = list;
1534   REGISTER Lisp_Object prev = Qnil;
1535
1536   while (!NILP (tail))
1537     {
1538       REGISTER Lisp_Object tem = XCAR (tail);
1539       if (EQ (elt, tem))
1540         {
1541           Lisp_Object cons_to_free = tail;
1542           if (NILP (prev))
1543             list = XCDR (tail);
1544           else
1545             XCDR (prev) = XCDR (tail);
1546           tail = XCDR (tail);
1547           free_cons (XCONS (cons_to_free));
1548         }
1549       else
1550         {
1551           prev = tail;
1552           tail = XCDR (tail);
1553         }
1554     }
1555   return list;
1556 }
1557
1558 DEFUN ("remassoc", Fremassoc, 2, 2, 0, /*
1559 Delete by side effect any elements of ALIST whose car is `equal' to KEY.
1560 The modified ALIST is returned.  If the first member of ALIST has a car
1561 that is `equal' to KEY, there is no way to remove it by side effect;
1562 therefore, write `(setq foo (remassoc key foo))' to be sure of changing
1563 the value of `foo'.
1564 */
1565        (key, alist))
1566 {
1567   EXTERNAL_LIST_LOOP_DELETE_IF (elt, alist,
1568                                 (CONSP (elt) &&
1569                                  internal_equal (key, XCAR (elt), 0)));
1570   return alist;
1571 }
1572
1573 Lisp_Object
1574 remassoc_no_quit (Lisp_Object key, Lisp_Object alist)
1575 {
1576   int speccount = specpdl_depth ();
1577   specbind (Qinhibit_quit, Qt);
1578   return unbind_to (speccount, Fremassoc (key, alist));
1579 }
1580
1581 DEFUN ("remassq", Fremassq, 2, 2, 0, /*
1582 Delete by side effect any elements of ALIST whose car is `eq' to KEY.
1583 The modified ALIST is returned.  If the first member of ALIST has a car
1584 that is `eq' to KEY, there is no way to remove it by side effect;
1585 therefore, write `(setq foo (remassq key foo))' to be sure of changing
1586 the value of `foo'.
1587 */
1588        (key, alist))
1589 {
1590   EXTERNAL_LIST_LOOP_DELETE_IF (elt, alist,
1591                                 (CONSP (elt) &&
1592                                  EQ_WITH_EBOLA_NOTICE (key, XCAR (elt))));
1593   return alist;
1594 }
1595
1596 /* no quit, no errors; be careful */
1597
1598 Lisp_Object
1599 remassq_no_quit (Lisp_Object key, Lisp_Object alist)
1600 {
1601   LIST_LOOP_DELETE_IF (elt, alist,
1602                        (CONSP (elt) &&
1603                         EQ_WITH_EBOLA_NOTICE (key, XCAR (elt))));
1604   return alist;
1605 }
1606
1607 DEFUN ("remrassoc", Fremrassoc, 2, 2, 0, /*
1608 Delete by side effect any elements of ALIST whose cdr is `equal' to VALUE.
1609 The modified ALIST is returned.  If the first member of ALIST has a car
1610 that is `equal' to VALUE, there is no way to remove it by side effect;
1611 therefore, write `(setq foo (remrassoc value foo))' to be sure of changing
1612 the value of `foo'.
1613 */
1614        (value, alist))
1615 {
1616   EXTERNAL_LIST_LOOP_DELETE_IF (elt, alist,
1617                                 (CONSP (elt) &&
1618                                  internal_equal (value, XCDR (elt), 0)));
1619   return alist;
1620 }
1621
1622 DEFUN ("remrassq", Fremrassq, 2, 2, 0, /*
1623 Delete by side effect any elements of ALIST whose cdr is `eq' to VALUE.
1624 The modified ALIST is returned.  If the first member of ALIST has a car
1625 that is `eq' to VALUE, there is no way to remove it by side effect;
1626 therefore, write `(setq foo (remrassq value foo))' to be sure of changing
1627 the value of `foo'.
1628 */
1629        (value, alist))
1630 {
1631   EXTERNAL_LIST_LOOP_DELETE_IF (elt, alist,
1632                                 (CONSP (elt) &&
1633                                  EQ_WITH_EBOLA_NOTICE (value, XCDR (elt))));
1634   return alist;
1635 }
1636
1637 /* Like Fremrassq, fast and unsafe; be careful */
1638 Lisp_Object
1639 remrassq_no_quit (Lisp_Object value, Lisp_Object alist)
1640 {
1641   LIST_LOOP_DELETE_IF (elt, alist,
1642                        (CONSP (elt) &&
1643                         EQ_WITH_EBOLA_NOTICE (value, XCDR (elt))));
1644   return alist;
1645 }
1646
1647 DEFUN ("nreverse", Fnreverse, 1, 1, 0, /*
1648 Reverse LIST by destructively modifying cdr pointers.
1649 Return the beginning of the reversed list.
1650 Also see: `reverse'.
1651 */
1652        (list))
1653 {
1654   struct gcpro gcpro1, gcpro2;
1655   REGISTER Lisp_Object prev = Qnil;
1656   REGISTER Lisp_Object tail = list;
1657
1658   /* We gcpro our args; see `nconc' */
1659   GCPRO2 (prev, tail);
1660   while (!NILP (tail))
1661     {
1662       REGISTER Lisp_Object next;
1663       CONCHECK_CONS (tail);
1664       next = XCDR (tail);
1665       XCDR (tail) = prev;
1666       prev = tail;
1667       tail = next;
1668     }
1669   UNGCPRO;
1670   return prev;
1671 }
1672
1673 DEFUN ("reverse", Freverse, 1, 1, 0, /*
1674 Reverse LIST, copying.  Return the beginning of the reversed list.
1675 See also the function `nreverse', which is used more often.
1676 */
1677        (list))
1678 {
1679   Lisp_Object reversed_list = Qnil;
1680   EXTERNAL_LIST_LOOP_2 (elt, list)
1681     {
1682       reversed_list = Fcons (elt, reversed_list);
1683     }
1684   return reversed_list;
1685 }
1686 \f
1687 static Lisp_Object list_merge (Lisp_Object org_l1, Lisp_Object org_l2,
1688                                Lisp_Object lisp_arg,
1689                                int (*pred_fn) (Lisp_Object, Lisp_Object,
1690                                                Lisp_Object lisp_arg));
1691
1692 Lisp_Object
1693 list_sort (Lisp_Object list,
1694            Lisp_Object lisp_arg,
1695            int (*pred_fn) (Lisp_Object, Lisp_Object,
1696                            Lisp_Object lisp_arg))
1697 {
1698   struct gcpro gcpro1, gcpro2, gcpro3;
1699   Lisp_Object back, tem;
1700   Lisp_Object front = list;
1701   Lisp_Object len = Flength (list);
1702
1703   if (XINT (len) < 2)
1704     return list;
1705
1706   len = make_int (XINT (len) / 2 - 1);
1707   tem = Fnthcdr (len, list);
1708   back = Fcdr (tem);
1709   Fsetcdr (tem, Qnil);
1710
1711   GCPRO3 (front, back, lisp_arg);
1712   front = list_sort (front, lisp_arg, pred_fn);
1713   back = list_sort (back, lisp_arg, pred_fn);
1714   UNGCPRO;
1715   return list_merge (front, back, lisp_arg, pred_fn);
1716 }
1717
1718 \f
1719 static int
1720 merge_pred_function (Lisp_Object obj1, Lisp_Object obj2,
1721                      Lisp_Object pred)
1722 {
1723   Lisp_Object tmp;
1724
1725   /* prevents the GC from happening in call2 */
1726   int speccount = specpdl_depth ();
1727 /* Emacs' GC doesn't actually relocate pointers, so this probably
1728    isn't strictly necessary */
1729   record_unwind_protect (restore_gc_inhibit,
1730                          make_int (gc_currently_forbidden));
1731   gc_currently_forbidden = 1;
1732   tmp = call2 (pred, obj1, obj2);
1733   unbind_to (speccount, Qnil);
1734
1735   if (NILP (tmp))
1736     return -1;
1737   else
1738     return 1;
1739 }
1740
1741 DEFUN ("sort", Fsort, 2, 2, 0, /*
1742 Sort LIST, stably, comparing elements using PREDICATE.
1743 Returns the sorted list.  LIST is modified by side effects.
1744 PREDICATE is called with two elements of LIST, and should return T
1745 if the first element is "less" than the second.
1746 */
1747        (list, predicate))
1748 {
1749   return list_sort (list, predicate, merge_pred_function);
1750 }
1751
1752 Lisp_Object
1753 merge (Lisp_Object org_l1, Lisp_Object org_l2,
1754        Lisp_Object pred)
1755 {
1756   return list_merge (org_l1, org_l2, pred, merge_pred_function);
1757 }
1758
1759
1760 static Lisp_Object
1761 list_merge (Lisp_Object org_l1, Lisp_Object org_l2,
1762             Lisp_Object lisp_arg,
1763             int (*pred_fn) (Lisp_Object, Lisp_Object, Lisp_Object lisp_arg))
1764 {
1765   Lisp_Object value;
1766   Lisp_Object tail;
1767   Lisp_Object tem;
1768   Lisp_Object l1, l2;
1769   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1770
1771   l1 = org_l1;
1772   l2 = org_l2;
1773   tail = Qnil;
1774   value = Qnil;
1775
1776   /* It is sufficient to protect org_l1 and org_l2.
1777      When l1 and l2 are updated, we copy the new values
1778      back into the org_ vars.  */
1779
1780   GCPRO4 (org_l1, org_l2, lisp_arg, value);
1781
1782   while (1)
1783     {
1784       if (NILP (l1))
1785         {
1786           UNGCPRO;
1787           if (NILP (tail))
1788             return l2;
1789           Fsetcdr (tail, l2);
1790           return value;
1791         }
1792       if (NILP (l2))
1793         {
1794           UNGCPRO;
1795           if (NILP (tail))
1796             return l1;
1797           Fsetcdr (tail, l1);
1798           return value;
1799         }
1800
1801       if (((*pred_fn) (Fcar (l2), Fcar (l1), lisp_arg)) < 0)
1802         {
1803           tem = l1;
1804           l1 = Fcdr (l1);
1805           org_l1 = l1;
1806         }
1807       else
1808         {
1809           tem = l2;
1810           l2 = Fcdr (l2);
1811           org_l2 = l2;
1812         }
1813       if (NILP (tail))
1814         value = tem;
1815       else
1816         Fsetcdr (tail, tem);
1817       tail = tem;
1818     }
1819 }
1820
1821 \f
1822 /************************************************************************/
1823 /*                      property-list functions                         */
1824 /************************************************************************/
1825
1826 /* For properties of text, we need to do order-insensitive comparison of
1827    plists.  That is, we need to compare two plists such that they are the
1828    same if they have the same set of keys, and equivalent values.
1829    So (a 1 b 2) would be equal to (b 2 a 1).
1830
1831    NIL_MEANS_NOT_PRESENT is as in `plists-eq' etc.
1832    LAXP means use `equal' for comparisons.
1833  */
1834 int
1835 plists_differ (Lisp_Object a, Lisp_Object b, int nil_means_not_present,
1836                int laxp, int depth)
1837 {
1838   int eqp = (depth == -1);      /* -1 as depth means use eq, not equal. */
1839   int la, lb, m, i, fill;
1840   Lisp_Object *keys, *vals;
1841   char *flags;
1842   Lisp_Object rest;
1843
1844   if (NILP (a) && NILP (b))
1845     return 0;
1846
1847   Fcheck_valid_plist (a);
1848   Fcheck_valid_plist (b);
1849
1850   la = XINT (Flength (a));
1851   lb = XINT (Flength (b));
1852   m = (la > lb ? la : lb);
1853   fill = 0;
1854   keys  = alloca_array (Lisp_Object, m);
1855   vals  = alloca_array (Lisp_Object, m);
1856   flags = alloca_array (char, m);
1857
1858   /* First extract the pairs from A. */
1859   for (rest = a; !NILP (rest); rest = XCDR (XCDR (rest)))
1860     {
1861       Lisp_Object k = XCAR (rest);
1862       Lisp_Object v = XCAR (XCDR (rest));
1863       /* Maybe be Ebolified. */
1864       if (nil_means_not_present && NILP (v)) continue;
1865       keys [fill] = k;
1866       vals [fill] = v;
1867       flags[fill] = 0;
1868       fill++;
1869     }
1870   /* Now iterate over B, and stop if we find something that's not in A,
1871      or that doesn't match.  As we match, mark them. */
1872   for (rest = b; !NILP (rest); rest = XCDR (XCDR (rest)))
1873     {
1874       Lisp_Object k = XCAR (rest);
1875       Lisp_Object v = XCAR (XCDR (rest));
1876       /* Maybe be Ebolified. */
1877       if (nil_means_not_present && NILP (v)) continue;
1878       for (i = 0; i < fill; i++)
1879         {
1880           if (!laxp ? EQ (k, keys [i]) : internal_equal (k, keys [i], depth))
1881             {
1882               if (eqp
1883                   /* We narrowly escaped being Ebolified here. */
1884                   ? !EQ_WITH_EBOLA_NOTICE (v, vals [i])
1885                   : !internal_equal (v, vals [i], depth))
1886                 /* a property in B has a different value than in A */
1887                 goto MISMATCH;
1888               flags [i] = 1;
1889               break;
1890             }
1891         }
1892       if (i == fill)
1893         /* there are some properties in B that are not in A */
1894         goto MISMATCH;
1895     }
1896   /* Now check to see that all the properties in A were also in B */
1897   for (i = 0; i < fill; i++)
1898     if (flags [i] == 0)
1899       goto MISMATCH;
1900
1901   /* Ok. */
1902   return 0;
1903
1904  MISMATCH:
1905   return 1;
1906 }
1907
1908 DEFUN ("plists-eq", Fplists_eq, 2, 3, 0, /*
1909 Return non-nil if property lists A and B are `eq'.
1910 A property list is an alternating list of keywords and values.
1911  This function does order-insensitive comparisons of the property lists:
1912  For example, the property lists '(a 1 b 2) and '(b 2 a 1) are equal.
1913  Comparison between values is done using `eq'.  See also `plists-equal'.
1914 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
1915  a nil value is ignored.  This feature is a virus that has infected
1916  old Lisp implementations, but should not be used except for backward
1917  compatibility.
1918 */
1919        (a, b, nil_means_not_present))
1920 {
1921   return (plists_differ (a, b, !NILP (nil_means_not_present), 0, -1)
1922           ? Qnil : Qt);
1923 }
1924
1925 DEFUN ("plists-equal", Fplists_equal, 2, 3, 0, /*
1926 Return non-nil if property lists A and B are `equal'.
1927 A property list is an alternating list of keywords and values.  This
1928  function does order-insensitive comparisons of the property lists: For
1929  example, the property lists '(a 1 b 2) and '(b 2 a 1) are equal.
1930  Comparison between values is done using `equal'.  See also `plists-eq'.
1931 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
1932  a nil value is ignored.  This feature is a virus that has infected
1933  old Lisp implementations, but should not be used except for backward
1934  compatibility.
1935 */
1936        (a, b, nil_means_not_present))
1937 {
1938   return (plists_differ (a, b, !NILP (nil_means_not_present), 0, 1)
1939           ? Qnil : Qt);
1940 }
1941
1942
1943 DEFUN ("lax-plists-eq", Flax_plists_eq, 2, 3, 0, /*
1944 Return non-nil if lax property lists A and B are `eq'.
1945 A property list is an alternating list of keywords and values.
1946  This function does order-insensitive comparisons of the property lists:
1947  For example, the property lists '(a 1 b 2) and '(b 2 a 1) are equal.
1948  Comparison between values is done using `eq'.  See also `plists-equal'.
1949 A lax property list is like a regular one except that comparisons between
1950  keywords is done using `equal' instead of `eq'.
1951 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
1952  a nil value is ignored.  This feature is a virus that has infected
1953  old Lisp implementations, but should not be used except for backward
1954  compatibility.
1955 */
1956        (a, b, nil_means_not_present))
1957 {
1958   return (plists_differ (a, b, !NILP (nil_means_not_present), 1, -1)
1959           ? Qnil : Qt);
1960 }
1961
1962 DEFUN ("lax-plists-equal", Flax_plists_equal, 2, 3, 0, /*
1963 Return non-nil if lax property lists A and B are `equal'.
1964 A property list is an alternating list of keywords and values.  This
1965  function does order-insensitive comparisons of the property lists: For
1966  example, the property lists '(a 1 b 2) and '(b 2 a 1) are equal.
1967  Comparison between values is done using `equal'.  See also `plists-eq'.
1968 A lax property list is like a regular one except that comparisons between
1969  keywords is done using `equal' instead of `eq'.
1970 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
1971  a nil value is ignored.  This feature is a virus that has infected
1972  old Lisp implementations, but should not be used except for backward
1973  compatibility.
1974 */
1975        (a, b, nil_means_not_present))
1976 {
1977   return (plists_differ (a, b, !NILP (nil_means_not_present), 1, 1)
1978           ? Qnil : Qt);
1979 }
1980
1981 /* Return the value associated with key PROPERTY in property list PLIST.
1982    Return nil if key not found.  This function is used for internal
1983    property lists that cannot be directly manipulated by the user.
1984    */
1985
1986 Lisp_Object
1987 internal_plist_get (Lisp_Object plist, Lisp_Object property)
1988 {
1989   Lisp_Object tail;
1990
1991   for (tail = plist; !NILP (tail); tail = XCDR (XCDR (tail)))
1992     {
1993       if (EQ (XCAR (tail), property))
1994         return XCAR (XCDR (tail));
1995     }
1996
1997   return Qunbound;
1998 }
1999
2000 /* Set PLIST's value for PROPERTY to VALUE.  Analogous to
2001    internal_plist_get(). */
2002
2003 void
2004 internal_plist_put (Lisp_Object *plist, Lisp_Object property,
2005                     Lisp_Object value)
2006 {
2007   Lisp_Object tail;
2008
2009   for (tail = *plist; !NILP (tail); tail = XCDR (XCDR (tail)))
2010     {
2011       if (EQ (XCAR (tail), property))
2012         {
2013           XCAR (XCDR (tail)) = value;
2014           return;
2015         }
2016     }
2017
2018   *plist = Fcons (property, Fcons (value, *plist));
2019 }
2020
2021 int
2022 internal_remprop (Lisp_Object *plist, Lisp_Object property)
2023 {
2024   Lisp_Object tail, prev;
2025
2026   for (tail = *plist, prev = Qnil;
2027        !NILP (tail);
2028        tail = XCDR (XCDR (tail)))
2029     {
2030       if (EQ (XCAR (tail), property))
2031         {
2032           if (NILP (prev))
2033             *plist = XCDR (XCDR (tail));
2034           else
2035             XCDR (XCDR (prev)) = XCDR (XCDR (tail));
2036           return 1;
2037         }
2038       else
2039         prev = tail;
2040     }
2041
2042   return 0;
2043 }
2044
2045 /* Called on a malformed property list.  BADPLACE should be some
2046    place where truncating will form a good list -- i.e. we shouldn't
2047    result in a list with an odd length. */
2048
2049 static Lisp_Object
2050 bad_bad_bunny (Lisp_Object *plist, Lisp_Object *badplace, Error_behavior errb)
2051 {
2052   if (ERRB_EQ (errb, ERROR_ME))
2053     return Fsignal (Qmalformed_property_list, list2 (*plist, *badplace));
2054   else
2055     {
2056       if (ERRB_EQ (errb, ERROR_ME_WARN))
2057         {
2058           warn_when_safe_lispobj
2059             (Qlist, Qwarning,
2060              list2 (build_string
2061                     ("Malformed property list -- list has been truncated"),
2062                     *plist));
2063           *badplace = Qnil;
2064         }
2065       return Qunbound;
2066     }
2067 }
2068
2069 /* Called on a circular property list.  BADPLACE should be some place
2070    where truncating will result in an even-length list, as above.
2071    If doesn't particularly matter where we truncate -- anywhere we
2072    truncate along the entire list will break the circularity, because
2073    it will create a terminus and the list currently doesn't have one.
2074 */
2075
2076 static Lisp_Object
2077 bad_bad_turtle (Lisp_Object *plist, Lisp_Object *badplace, Error_behavior errb)
2078 {
2079   if (ERRB_EQ (errb, ERROR_ME))
2080     return Fsignal (Qcircular_property_list, list1 (*plist));
2081   else
2082     {
2083       if (ERRB_EQ (errb, ERROR_ME_WARN))
2084         {
2085           warn_when_safe_lispobj
2086             (Qlist, Qwarning,
2087              list2 (build_string
2088                     ("Circular property list -- list has been truncated"),
2089                     *plist));
2090           *badplace = Qnil;
2091         }
2092       return Qunbound;
2093     }
2094 }
2095
2096 /* Advance the tortoise pointer by two (one iteration of a property-list
2097    loop) and the hare pointer by four and verify that no malformations
2098    or circularities exist.  If so, return zero and store a value into
2099    RETVAL that should be returned by the calling function.  Otherwise,
2100    return 1.  See external_plist_get().
2101  */
2102
2103 static int
2104 advance_plist_pointers (Lisp_Object *plist,
2105                         Lisp_Object **tortoise, Lisp_Object **hare,
2106                         Error_behavior errb, Lisp_Object *retval)
2107 {
2108   int i;
2109   Lisp_Object *tortsave = *tortoise;
2110
2111   /* Note that our "fixing" may be more brutal than necessary,
2112      but it's the user's own problem, not ours, if they went in and
2113      manually fucked up a plist. */
2114
2115   for (i = 0; i < 2; i++)
2116     {
2117       /* This is a standard iteration of a defensive-loop-checking
2118          loop.  We just do it twice because we want to advance past
2119          both the property and its value.
2120
2121          If the pointer indirection is confusing you, remember that
2122          one level of indirection on the hare and tortoise pointers
2123          is only due to pass-by-reference for this function.  The other
2124          level is so that the plist can be fixed in place. */
2125
2126       /* When we reach the end of a well-formed plist, **HARE is
2127          nil.  In that case, we don't do anything at all except
2128          advance TORTOISE by one.  Otherwise, we advance HARE
2129          by two (making sure it's OK to do so), then advance
2130          TORTOISE by one (it will always be OK to do so because
2131          the HARE is always ahead of the TORTOISE and will have
2132          already verified the path), then make sure TORTOISE and
2133          HARE don't contain the same non-nil object -- if the
2134          TORTOISE and the HARE ever meet, then obviously we're
2135          in a circularity, and if we're in a circularity, then
2136          the TORTOISE and the HARE can't cross paths without
2137          meeting, since the HARE only gains one step over the
2138          TORTOISE per iteration. */
2139
2140       if (!NILP (**hare))
2141         {
2142           Lisp_Object *haresave = *hare;
2143           if (!CONSP (**hare))
2144             {
2145               *retval = bad_bad_bunny (plist, haresave, errb);
2146               return 0;
2147             }
2148           *hare = &XCDR (**hare);
2149           /* In a non-plist, we'd check here for a nil value for
2150              **HARE, which is OK (it just means the list has an
2151              odd number of elements).  In a plist, it's not OK
2152              for the list to have an odd number of elements. */
2153           if (!CONSP (**hare))
2154             {
2155               *retval = bad_bad_bunny (plist, haresave, errb);
2156               return 0;
2157             }
2158           *hare = &XCDR (**hare);
2159         }
2160
2161       *tortoise = &XCDR (**tortoise);
2162       if (!NILP (**hare) && EQ (**tortoise, **hare))
2163         {
2164           *retval = bad_bad_turtle (plist, tortsave, errb);
2165           return 0;
2166         }
2167     }
2168
2169   return 1;
2170 }
2171
2172 /* Return the value of PROPERTY from PLIST, or Qunbound if
2173    property is not on the list.
2174
2175    PLIST is a Lisp-accessible property list, meaning that it
2176    has to be checked for malformations and circularities.
2177
2178    If ERRB is ERROR_ME, an error will be signalled.  Otherwise, the
2179    function will never signal an error; and if ERRB is ERROR_ME_WARN,
2180    on finding a malformation or a circularity, it issues a warning and
2181    attempts to silently fix the problem.
2182
2183    A pointer to PLIST is passed in so that PLIST can be successfully
2184    "fixed" even if the error is at the beginning of the plist. */
2185
2186 Lisp_Object
2187 external_plist_get (Lisp_Object *plist, Lisp_Object property,
2188                     int laxp, Error_behavior errb)
2189 {
2190   Lisp_Object *tortoise = plist;
2191   Lisp_Object *hare = plist;
2192
2193   while (!NILP (*tortoise))
2194     {
2195       Lisp_Object *tortsave = tortoise;
2196       Lisp_Object retval;
2197
2198       /* We do the standard tortoise/hare march.  We isolate the
2199          grungy stuff to do this in advance_plist_pointers(), though.
2200          To us, all this function does is advance the tortoise
2201          pointer by two and the hare pointer by four and make sure
2202          everything's OK.  We first advance the pointers and then
2203          check if a property matched; this ensures that our
2204          check for a matching property is safe. */
2205
2206       if (!advance_plist_pointers (plist, &tortoise, &hare, errb, &retval))
2207         return retval;
2208
2209       if (!laxp ? EQ (XCAR (*tortsave), property)
2210           : internal_equal (XCAR (*tortsave), property, 0))
2211         return XCAR (XCDR (*tortsave));
2212     }
2213
2214   return Qunbound;
2215 }
2216
2217 /* Set PLIST's value for PROPERTY to VALUE, given a possibly
2218    malformed or circular plist.  Analogous to external_plist_get(). */
2219
2220 void
2221 external_plist_put (Lisp_Object *plist, Lisp_Object property,
2222                     Lisp_Object value, int laxp, Error_behavior errb)
2223 {
2224   Lisp_Object *tortoise = plist;
2225   Lisp_Object *hare = plist;
2226
2227   while (!NILP (*tortoise))
2228     {
2229       Lisp_Object *tortsave = tortoise;
2230       Lisp_Object retval;
2231
2232       /* See above */
2233       if (!advance_plist_pointers (plist, &tortoise, &hare, errb, &retval))
2234         return;
2235
2236       if (!laxp ? EQ (XCAR (*tortsave), property)
2237           : internal_equal (XCAR (*tortsave), property, 0))
2238         {
2239           XCAR (XCDR (*tortsave)) = value;
2240           return;
2241         }
2242     }
2243
2244   *plist = Fcons (property, Fcons (value, *plist));
2245 }
2246
2247 int
2248 external_remprop (Lisp_Object *plist, Lisp_Object property,
2249                   int laxp, Error_behavior errb)
2250 {
2251   Lisp_Object *tortoise = plist;
2252   Lisp_Object *hare = plist;
2253
2254   while (!NILP (*tortoise))
2255     {
2256       Lisp_Object *tortsave = tortoise;
2257       Lisp_Object retval;
2258
2259       /* See above */
2260       if (!advance_plist_pointers (plist, &tortoise, &hare, errb, &retval))
2261         return 0;
2262
2263       if (!laxp ? EQ (XCAR (*tortsave), property)
2264           : internal_equal (XCAR (*tortsave), property, 0))
2265         {
2266           /* Now you see why it's so convenient to have that level
2267              of indirection. */
2268           *tortsave = XCDR (XCDR (*tortsave));
2269           return 1;
2270         }
2271     }
2272
2273   return 0;
2274 }
2275
2276 DEFUN ("plist-get", Fplist_get, 2, 3, 0, /*
2277 Extract a value from a property list.
2278 PLIST is a property list, which is a list of the form
2279 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2...).
2280 PROPERTY is usually a symbol.
2281 This function returns the value corresponding to the PROPERTY,
2282 or DEFAULT if PROPERTY is not one of the properties on the list.
2283 */
2284        (plist, property, default_))
2285 {
2286   Lisp_Object value = external_plist_get (&plist, property, 0, ERROR_ME);
2287   return UNBOUNDP (value) ? default_ : value;
2288 }
2289
2290 DEFUN ("plist-put", Fplist_put, 3, 3, 0, /*
2291 Change value in PLIST of PROPERTY to VALUE.
2292 PLIST is a property list, which is a list of the form
2293 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2 ...).
2294 PROPERTY is usually a symbol and VALUE is any object.
2295 If PROPERTY is already a property on the list, its value is set to VALUE,
2296 otherwise the new PROPERTY VALUE pair is added.
2297 The new plist is returned; use `(setq x (plist-put x property value))'
2298 to be sure to use the new value.  PLIST is modified by side effect.
2299 */
2300        (plist, property, value))
2301 {
2302   external_plist_put (&plist, property, value, 0, ERROR_ME);
2303   return plist;
2304 }
2305
2306 DEFUN ("plist-remprop", Fplist_remprop, 2, 2, 0, /*
2307 Remove from PLIST the property PROPERTY and its value.
2308 PLIST is a property list, which is a list of the form
2309 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2 ...).
2310 PROPERTY is usually a symbol.
2311 The new plist is returned; use `(setq x (plist-remprop x property))'
2312 to be sure to use the new value.  PLIST is modified by side effect.
2313 */
2314        (plist, property))
2315 {
2316   external_remprop (&plist, property, 0, ERROR_ME);
2317   return plist;
2318 }
2319
2320 DEFUN ("plist-member", Fplist_member, 2, 2, 0, /*
2321 Return t if PROPERTY has a value specified in PLIST.
2322 */
2323        (plist, property))
2324 {
2325   Lisp_Object value = Fplist_get (plist, property, Qunbound);
2326   return UNBOUNDP (value) ? Qnil : Qt;
2327 }
2328
2329 DEFUN ("check-valid-plist", Fcheck_valid_plist, 1, 1, 0, /*
2330 Given a plist, signal an error if there is anything wrong with it.
2331 This means that it's a malformed or circular plist.
2332 */
2333        (plist))
2334 {
2335   Lisp_Object *tortoise;
2336   Lisp_Object *hare;
2337
2338  start_over:
2339   tortoise = &plist;
2340   hare = &plist;
2341   while (!NILP (*tortoise))
2342     {
2343       Lisp_Object retval;
2344
2345       /* See above */
2346       if (!advance_plist_pointers (&plist, &tortoise, &hare, ERROR_ME,
2347                                    &retval))
2348         goto start_over;
2349     }
2350
2351   return Qnil;
2352 }
2353
2354 DEFUN ("valid-plist-p", Fvalid_plist_p, 1, 1, 0, /*
2355 Given a plist, return non-nil if its format is correct.
2356 If it returns nil, `check-valid-plist' will signal an error when given
2357 the plist; that means it's a malformed or circular plist.
2358 */
2359        (plist))
2360 {
2361   Lisp_Object *tortoise;
2362   Lisp_Object *hare;
2363
2364   tortoise = &plist;
2365   hare = &plist;
2366   while (!NILP (*tortoise))
2367     {
2368       Lisp_Object retval;
2369
2370       /* See above */
2371       if (!advance_plist_pointers (&plist, &tortoise, &hare, ERROR_ME_NOT,
2372                                    &retval))
2373         return Qnil;
2374     }
2375
2376   return Qt;
2377 }
2378
2379 DEFUN ("canonicalize-plist", Fcanonicalize_plist, 1, 2, 0, /*
2380 Destructively remove any duplicate entries from a plist.
2381 In such cases, the first entry applies.
2382
2383 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
2384  a nil value is removed.  This feature is a virus that has infected
2385  old Lisp implementations, but should not be used except for backward
2386  compatibility.
2387
2388 The new plist is returned.  If NIL-MEANS-NOT-PRESENT is given, the
2389  return value may not be EQ to the passed-in value, so make sure to
2390  `setq' the value back into where it came from.
2391 */
2392        (plist, nil_means_not_present))
2393 {
2394   Lisp_Object head = plist;
2395
2396   Fcheck_valid_plist (plist);
2397
2398   while (!NILP (plist))
2399     {
2400       Lisp_Object prop = Fcar (plist);
2401       Lisp_Object next = Fcdr (plist);
2402
2403       CHECK_CONS (next); /* just make doubly sure we catch any errors */
2404       if (!NILP (nil_means_not_present) && NILP (Fcar (next)))
2405         {
2406           if (EQ (head, plist))
2407             head = Fcdr (next);
2408           plist = Fcdr (next);
2409           continue;
2410         }
2411       /* external_remprop returns 1 if it removed any property.
2412          We have to loop till it didn't remove anything, in case
2413          the property occurs many times. */
2414       while (external_remprop (&XCDR (next), prop, 0, ERROR_ME))
2415         DO_NOTHING;
2416       plist = Fcdr (next);
2417     }
2418
2419   return head;
2420 }
2421
2422 DEFUN ("lax-plist-get", Flax_plist_get, 2, 3, 0, /*
2423 Extract a value from a lax property list.
2424 LAX-PLIST is a lax property list, which is a list of the form
2425 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2...), where comparisons between
2426 properties is done using `equal' instead of `eq'.
2427 PROPERTY is usually a symbol.
2428 This function returns the value corresponding to PROPERTY,
2429 or DEFAULT if PROPERTY is not one of the properties on the list.
2430 */
2431        (lax_plist, property, default_))
2432 {
2433   Lisp_Object value = external_plist_get (&lax_plist, property, 1, ERROR_ME);
2434   return UNBOUNDP (value) ? default_ : value;
2435 }
2436
2437 DEFUN ("lax-plist-put", Flax_plist_put, 3, 3, 0, /*
2438 Change value in LAX-PLIST of PROPERTY to VALUE.
2439 LAX-PLIST is a lax property list, which is a list of the form
2440 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2...), where comparisons between
2441 properties is done using `equal' instead of `eq'.
2442 PROPERTY is usually a symbol and VALUE is any object.
2443 If PROPERTY is already a property on the list, its value is set to
2444 VALUE, otherwise the new PROPERTY VALUE pair is added.
2445 The new plist is returned; use `(setq x (lax-plist-put x property value))'
2446 to be sure to use the new value.  LAX-PLIST is modified by side effect.
2447 */
2448        (lax_plist, property, value))
2449 {
2450   external_plist_put (&lax_plist, property, value, 1, ERROR_ME);
2451   return lax_plist;
2452 }
2453
2454 DEFUN ("lax-plist-remprop", Flax_plist_remprop, 2, 2, 0, /*
2455 Remove from LAX-PLIST the property PROPERTY and its value.
2456 LAX-PLIST is a lax property list, which is a list of the form
2457 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2...), where comparisons between
2458 properties is done using `equal' instead of `eq'.
2459 PROPERTY is usually a symbol.
2460 The new plist is returned; use `(setq x (lax-plist-remprop x property))'
2461 to be sure to use the new value.  LAX-PLIST is modified by side effect.
2462 */
2463        (lax_plist, property))
2464 {
2465   external_remprop (&lax_plist, property, 1, ERROR_ME);
2466   return lax_plist;
2467 }
2468
2469 DEFUN ("lax-plist-member", Flax_plist_member, 2, 2, 0, /*
2470 Return t if PROPERTY has a value specified in LAX-PLIST.
2471 LAX-PLIST is a lax property list, which is a list of the form
2472 \(PROPERTY1 VALUE1 PROPERTY2 VALUE2...), where comparisons between
2473 properties is done using `equal' instead of `eq'.
2474 */
2475        (lax_plist, property))
2476 {
2477   return UNBOUNDP (Flax_plist_get (lax_plist, property, Qunbound)) ? Qnil : Qt;
2478 }
2479
2480 DEFUN ("canonicalize-lax-plist", Fcanonicalize_lax_plist, 1, 2, 0, /*
2481 Destructively remove any duplicate entries from a lax plist.
2482 In such cases, the first entry applies.
2483
2484 If optional arg NIL-MEANS-NOT-PRESENT is non-nil, then a property with
2485  a nil value is removed.  This feature is a virus that has infected
2486  old Lisp implementations, but should not be used except for backward
2487  compatibility.
2488
2489 The new plist is returned.  If NIL-MEANS-NOT-PRESENT is given, the
2490  return value may not be EQ to the passed-in value, so make sure to
2491  `setq' the value back into where it came from.
2492 */
2493        (lax_plist, nil_means_not_present))
2494 {
2495   Lisp_Object head = lax_plist;
2496
2497   Fcheck_valid_plist (lax_plist);
2498
2499   while (!NILP (lax_plist))
2500     {
2501       Lisp_Object prop = Fcar (lax_plist);
2502       Lisp_Object next = Fcdr (lax_plist);
2503
2504       CHECK_CONS (next); /* just make doubly sure we catch any errors */
2505       if (!NILP (nil_means_not_present) && NILP (Fcar (next)))
2506         {
2507           if (EQ (head, lax_plist))
2508             head = Fcdr (next);
2509           lax_plist = Fcdr (next);
2510           continue;
2511         }
2512       /* external_remprop returns 1 if it removed any property.
2513          We have to loop till it didn't remove anything, in case
2514          the property occurs many times. */
2515       while (external_remprop (&XCDR (next), prop, 1, ERROR_ME))
2516         DO_NOTHING;
2517       lax_plist = Fcdr (next);
2518     }
2519
2520   return head;
2521 }
2522
2523 /* In C because the frame props stuff uses it */
2524
2525 DEFUN ("destructive-alist-to-plist", Fdestructive_alist_to_plist, 1, 1, 0, /*
2526 Convert association list ALIST into the equivalent property-list form.
2527 The plist is returned.  This converts from
2528
2529 \((a . 1) (b . 2) (c . 3))
2530
2531 into
2532
2533 \(a 1 b 2 c 3)
2534
2535 The original alist is destroyed in the process of constructing the plist.
2536 See also `alist-to-plist'.
2537 */
2538        (alist))
2539 {
2540   Lisp_Object head = alist;
2541   while (!NILP (alist))
2542     {
2543       /* remember the alist element. */
2544       Lisp_Object el = Fcar (alist);
2545
2546       Fsetcar (alist, Fcar (el));
2547       Fsetcar (el, Fcdr (el));
2548       Fsetcdr (el, Fcdr (alist));
2549       Fsetcdr (alist, el);
2550       alist = Fcdr (Fcdr (alist));
2551     }
2552
2553   return head;
2554 }
2555
2556 DEFUN ("get", Fget, 2, 3, 0, /*
2557 Return the value of OBJECT's PROPERTY property.
2558 This is the last VALUE stored with `(put OBJECT PROPERTY VALUE)'.
2559 If there is no such property, return optional third arg DEFAULT
2560 \(which defaults to `nil').  OBJECT can be a symbol, string, extent,
2561 face, or glyph.  See also `put', `remprop', and `object-plist'.
2562 */
2563        (object, property, default_))
2564 {
2565   /* Various places in emacs call Fget() and expect it not to quit,
2566      so don't quit. */
2567   Lisp_Object val;
2568
2569   if (LRECORDP (object) && XRECORD_LHEADER_IMPLEMENTATION (object)->getprop)
2570     val = XRECORD_LHEADER_IMPLEMENTATION (object)->getprop (object, property);
2571   else
2572     signal_simple_error ("Object type has no properties", object);
2573
2574   return UNBOUNDP (val) ? default_ : val;
2575 }
2576
2577 DEFUN ("put", Fput, 3, 3, 0, /*
2578 Set OBJECT's PROPERTY to VALUE.
2579 It can be subsequently retrieved with `(get OBJECT PROPERTY)'.
2580 OBJECT can be a symbol, face, extent, or string.
2581 For a string, no properties currently have predefined meanings.
2582 For the predefined properties for extents, see `set-extent-property'.
2583 For the predefined properties for faces, see `set-face-property'.
2584 See also `get', `remprop', and `object-plist'.
2585 */
2586        (object, property, value))
2587 {
2588   CHECK_LISP_WRITEABLE (object);
2589
2590   if (LRECORDP (object) && XRECORD_LHEADER_IMPLEMENTATION (object)->putprop)
2591     {
2592       if (! XRECORD_LHEADER_IMPLEMENTATION (object)->putprop
2593           (object, property, value))
2594         signal_simple_error ("Can't set property on object", property);
2595     }
2596   else
2597     signal_simple_error ("Object type has no settable properties", object);
2598
2599   return value;
2600 }
2601
2602 DEFUN ("remprop", Fremprop, 2, 2, 0, /*
2603 Remove, from OBJECT's property list, PROPERTY and its corresponding value.
2604 OBJECT can be a symbol, string, extent, face, or glyph.  Return non-nil
2605 if the property list was actually modified (i.e. if PROPERTY was present
2606 in the property list).  See also `get', `put', and `object-plist'.
2607 */
2608        (object, property))
2609 {
2610   int ret = 0;
2611
2612   CHECK_LISP_WRITEABLE (object);
2613
2614   if (LRECORDP (object) && XRECORD_LHEADER_IMPLEMENTATION (object)->remprop)
2615     {
2616       ret = XRECORD_LHEADER_IMPLEMENTATION (object)->remprop (object, property);
2617       if (ret == -1)
2618         signal_simple_error ("Can't remove property from object", property);
2619     }
2620   else
2621     signal_simple_error ("Object type has no removable properties", object);
2622
2623   return ret ? Qt : Qnil;
2624 }
2625
2626 DEFUN ("object-plist", Fobject_plist, 1, 1, 0, /*
2627 Return a property list of OBJECT's properties.
2628 For a symbol, this is equivalent to `symbol-plist'.
2629 OBJECT can be a symbol, string, extent, face, or glyph.
2630 Do not modify the returned property list directly;
2631 this may or may not have the desired effects.  Use `put' instead.
2632 */
2633        (object))
2634 {
2635   if (LRECORDP (object) && XRECORD_LHEADER_IMPLEMENTATION (object)->plist)
2636     return XRECORD_LHEADER_IMPLEMENTATION (object)->plist (object);
2637   else
2638     signal_simple_error ("Object type has no properties", object);
2639
2640   return Qnil;
2641 }
2642
2643 \f
2644 int
2645 internal_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
2646 {
2647   if (depth > 200)
2648     error ("Stack overflow in equal");
2649   QUIT;
2650   if (EQ_WITH_EBOLA_NOTICE (obj1, obj2))
2651     return 1;
2652   /* Note that (equal 20 20.0) should be nil */
2653   if (XTYPE (obj1) != XTYPE (obj2))
2654     return 0;
2655   if (LRECORDP (obj1))
2656     {
2657       const struct lrecord_implementation
2658         *imp1 = XRECORD_LHEADER_IMPLEMENTATION (obj1),
2659         *imp2 = XRECORD_LHEADER_IMPLEMENTATION (obj2);
2660
2661       return (imp1 == imp2) &&
2662         /* EQ-ness of the objects was noticed above */
2663         (imp1->equal && (imp1->equal) (obj1, obj2, depth));
2664     }
2665
2666   return 0;
2667 }
2668
2669 /* Note that we may be calling sub-objects that will use
2670    internal_equal() (instead of internal_old_equal()).  Oh well.
2671    We will get an Ebola note if there's any possibility of confusion,
2672    but that seems unlikely. */
2673
2674 static int
2675 internal_old_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
2676 {
2677   if (depth > 200)
2678     error ("Stack overflow in equal");
2679   QUIT;
2680   if (HACKEQ_UNSAFE (obj1, obj2))
2681     return 1;
2682   /* Note that (equal 20 20.0) should be nil */
2683   if (XTYPE (obj1) != XTYPE (obj2))
2684     return 0;
2685
2686   return internal_equal (obj1, obj2, depth);
2687 }
2688
2689 DEFUN ("equal", Fequal, 2, 2, 0, /*
2690 Return t if two Lisp objects have similar structure and contents.
2691 They must have the same data type.
2692 Conses are compared by comparing the cars and the cdrs.
2693 Vectors and strings are compared element by element.
2694 Numbers are compared by value.  Symbols must match exactly.
2695 */
2696        (object1, object2))
2697 {
2698   return internal_equal (object1, object2, 0) ? Qt : Qnil;
2699 }
2700
2701 DEFUN ("old-equal", Fold_equal, 2, 2, 0, /*
2702 Return t if two Lisp objects have similar structure and contents.
2703 They must have the same data type.
2704 \(Note, however, that an exception is made for characters and integers;
2705 this is known as the "char-int confoundance disease." See `eq' and
2706 `old-eq'.)
2707 This function is provided only for byte-code compatibility with v19.
2708 Do not use it.
2709 */
2710        (object1, object2))
2711 {
2712   return internal_old_equal (object1, object2, 0) ? Qt : Qnil;
2713 }
2714
2715 \f
2716 DEFUN ("fillarray", Ffillarray, 2, 2, 0, /*
2717 Destructively modify ARRAY by replacing each element with ITEM.
2718 ARRAY is a vector, bit vector, or string.
2719 */
2720        (array, item))
2721 {
2722  retry:
2723   if (STRINGP (array))
2724     {
2725       Lisp_String *s = XSTRING (array);
2726       Bytecount old_bytecount = string_length (s);
2727       Bytecount new_bytecount;
2728       Bytecount item_bytecount;
2729       Bufbyte item_buf[MAX_EMCHAR_LEN];
2730       Bufbyte *p;
2731       Bufbyte *end;
2732
2733       CHECK_CHAR_COERCE_INT (item);
2734       CHECK_LISP_WRITEABLE (array);
2735
2736       item_bytecount = set_charptr_emchar (item_buf, XCHAR (item));
2737       new_bytecount = item_bytecount * string_char_length (s);
2738
2739       resize_string (s, -1, new_bytecount - old_bytecount);
2740
2741       for (p = string_data (s), end = p + new_bytecount;
2742            p < end;
2743            p += item_bytecount)
2744         memcpy (p, item_buf, item_bytecount);
2745       *p = '\0';
2746
2747       bump_string_modiff (array);
2748     }
2749   else if (VECTORP (array))
2750     {
2751       Lisp_Object *p = XVECTOR_DATA (array);
2752       size_t len = XVECTOR_LENGTH (array);
2753       CHECK_LISP_WRITEABLE (array);
2754       while (len--)
2755         *p++ = item;
2756     }
2757   else if (BIT_VECTORP (array))
2758     {
2759       Lisp_Bit_Vector *v = XBIT_VECTOR (array);
2760       size_t len = bit_vector_length (v);
2761       int bit;
2762       CHECK_BIT (item);
2763       bit = XINT (item);
2764       CHECK_LISP_WRITEABLE (array);
2765       while (len--)
2766         set_bit_vector_bit (v, len, bit);
2767     }
2768   else
2769     {
2770       array = wrong_type_argument (Qarrayp, array);
2771       goto retry;
2772     }
2773   return array;
2774 }
2775
2776 Lisp_Object
2777 nconc2 (Lisp_Object arg1, Lisp_Object arg2)
2778 {
2779   Lisp_Object args[2];
2780   struct gcpro gcpro1;
2781   args[0] = arg1;
2782   args[1] = arg2;
2783
2784   GCPRO1 (args[0]);
2785   gcpro1.nvars = 2;
2786
2787   RETURN_UNGCPRO (bytecode_nconc2 (args));
2788 }
2789
2790 Lisp_Object
2791 bytecode_nconc2 (Lisp_Object *args)
2792 {
2793  retry:
2794
2795   if (CONSP (args[0]))
2796     {
2797       /* (setcdr (last args[0]) args[1]) */
2798       Lisp_Object tortoise, hare;
2799       size_t count;
2800
2801       for (hare = tortoise = args[0], count = 0;
2802            CONSP (XCDR (hare));
2803            hare = XCDR (hare), count++)
2804         {
2805           if (count < CIRCULAR_LIST_SUSPICION_LENGTH) continue;
2806
2807           if (count & 1)
2808             tortoise = XCDR (tortoise);
2809           if (EQ (hare, tortoise))
2810             signal_circular_list_error (args[0]);
2811         }
2812       XCDR (hare) = args[1];
2813       return args[0];
2814     }
2815   else if (NILP (args[0]))
2816     {
2817       return args[1];
2818     }
2819   else
2820     {
2821       args[0] = wrong_type_argument (args[0], Qlistp);
2822       goto retry;
2823     }
2824 }
2825
2826 DEFUN ("nconc", Fnconc, 0, MANY, 0, /*
2827 Concatenate any number of lists by altering them.
2828 Only the last argument is not altered, and need not be a list.
2829 Also see: `append'.
2830 If the first argument is nil, there is no way to modify it by side
2831 effect; therefore, write `(setq foo (nconc foo list))' to be sure of
2832 changing the value of `foo'.
2833 */
2834        (int nargs, Lisp_Object *args))
2835 {
2836   int argnum = 0;
2837   struct gcpro gcpro1;
2838
2839   /* The modus operandi in Emacs is "caller gc-protects args".
2840      However, nconc (particularly nconc2 ()) is called many times
2841      in Emacs on freshly created stuff (e.g. you see the idiom
2842      nconc2 (Fcopy_sequence (foo), bar) a lot).  So we help those
2843      callers out by protecting the args ourselves to save them
2844      a lot of temporary-variable grief. */
2845
2846   GCPRO1 (args[0]);
2847   gcpro1.nvars = nargs;
2848
2849   while (argnum < nargs)
2850     {
2851       Lisp_Object val;
2852     retry:
2853       val = args[argnum];
2854       if (CONSP (val))
2855         {
2856           /* `val' is the first cons, which will be our return value.  */
2857           /* `last_cons' will be the cons cell to mutate.  */
2858           Lisp_Object last_cons = val;
2859           Lisp_Object tortoise = val;
2860
2861           for (argnum++; argnum < nargs; argnum++)
2862             {
2863               Lisp_Object next = args[argnum];
2864             retry_next:
2865               if (CONSP (next) || argnum == nargs -1)
2866                 {
2867                   /* (setcdr (last val) next) */
2868                   size_t count;
2869
2870                   for (count = 0;
2871                        CONSP (XCDR (last_cons));
2872                        last_cons = XCDR (last_cons), count++)
2873                     {
2874                       if (count < CIRCULAR_LIST_SUSPICION_LENGTH) continue;
2875
2876                       if (count & 1)
2877                         tortoise = XCDR (tortoise);
2878                       if (EQ (last_cons, tortoise))
2879                         signal_circular_list_error (args[argnum-1]);
2880                     }
2881                   XCDR (last_cons) = next;
2882                 }
2883               else if (NILP (next))
2884                 {
2885                   continue;
2886                 }
2887               else
2888                 {
2889                   next = wrong_type_argument (Qlistp, next);
2890                   goto retry_next;
2891                 }
2892             }
2893           RETURN_UNGCPRO (val);
2894         }
2895       else if (NILP (val))
2896         argnum++;
2897       else if (argnum == nargs - 1) /* last arg? */
2898         RETURN_UNGCPRO (val);
2899       else
2900         {
2901           args[argnum] = wrong_type_argument (Qlistp, val);
2902           goto retry;
2903         }
2904     }
2905   RETURN_UNGCPRO (Qnil);  /* No non-nil args provided. */
2906 }
2907
2908 \f
2909 /* This is the guts of several mapping functions.
2910    Apply FUNCTION to each element of SEQUENCE, one by one,
2911    storing the results into elements of VALS, a C vector of Lisp_Objects.
2912    LENI is the length of VALS, which should also be the length of SEQUENCE.
2913
2914    If VALS is a null pointer, do not accumulate the results. */
2915
2916 static void
2917 mapcar1 (size_t leni, Lisp_Object *vals,
2918          Lisp_Object function, Lisp_Object sequence)
2919 {
2920   Lisp_Object result;
2921   Lisp_Object args[2];
2922   struct gcpro gcpro1;
2923
2924   if (vals)
2925     {
2926       GCPRO1 (vals[0]);
2927       gcpro1.nvars = 0;
2928     }
2929
2930   args[0] = function;
2931
2932   if (LISTP (sequence))
2933     {
2934       /* A devious `function' could either:
2935          - insert garbage into the list in front of us, causing XCDR to crash
2936          - amputate the list behind us using (setcdr), causing the remaining
2937            elts to lose their GCPRO status.
2938
2939          if (vals != 0) we avoid this by copying the elts into the
2940          `vals' array.  By a stroke of luck, `vals' is exactly large
2941          enough to hold the elts left to be traversed as well as the
2942          results computed so far.
2943
2944          if (vals == 0) we don't have any free space available and
2945          don't want to eat up any more stack with alloca().
2946          So we use EXTERNAL_LIST_LOOP_3_NO_DECLARE and GCPRO the tail. */
2947
2948       if (vals)
2949         {
2950           Lisp_Object *val = vals;
2951           size_t i;
2952
2953           LIST_LOOP_2 (elt, sequence)
2954               *val++ = elt;
2955
2956           gcpro1.nvars = leni;
2957
2958           for (i = 0; i < leni; i++)
2959             {
2960               args[1] = vals[i];
2961               vals[i] = Ffuncall (2, args);
2962             }
2963         }
2964       else
2965         {
2966           Lisp_Object elt, tail;
2967           EMACS_INT len_unused;
2968           struct gcpro ngcpro1;
2969
2970           NGCPRO1 (tail);
2971
2972           {
2973             EXTERNAL_LIST_LOOP_4_NO_DECLARE (elt, sequence, tail, len_unused)
2974               {
2975                 args[1] = elt;
2976                 Ffuncall (2, args);
2977               }
2978           }
2979
2980           NUNGCPRO;
2981         }
2982     }
2983   else if (VECTORP (sequence))
2984     {
2985       Lisp_Object *objs = XVECTOR_DATA (sequence);
2986       size_t i;
2987       for (i = 0; i < leni; i++)
2988         {
2989           args[1] = *objs++;
2990           result = Ffuncall (2, args);
2991           if (vals) vals[gcpro1.nvars++] = result;
2992         }
2993     }
2994   else if (STRINGP (sequence))
2995     {
2996       /* The string data of `sequence' might be relocated during GC. */
2997       Bytecount slen = XSTRING_LENGTH (sequence);
2998       Bufbyte *p = alloca_array (Bufbyte, slen);
2999       Bufbyte *end = p + slen;
3000
3001       memcpy (p, XSTRING_DATA (sequence), slen);
3002
3003       while (p < end)
3004         {
3005           args[1] = make_char (charptr_emchar (p));
3006           INC_CHARPTR (p);
3007           result = Ffuncall (2, args);
3008           if (vals) vals[gcpro1.nvars++] = result;
3009         }
3010     }
3011   else if (BIT_VECTORP (sequence))
3012     {
3013       Lisp_Bit_Vector *v = XBIT_VECTOR (sequence);
3014       size_t i;
3015       for (i = 0; i < leni; i++)
3016         {
3017           args[1] = make_int (bit_vector_bit (v, i));
3018           result = Ffuncall (2, args);
3019           if (vals) vals[gcpro1.nvars++] = result;
3020         }
3021     }
3022   else
3023     abort (); /* unreachable, since Flength (sequence) did not get an error */
3024
3025   if (vals)
3026     UNGCPRO;
3027 }
3028
3029 DEFUN ("mapconcat", Fmapconcat, 3, 3, 0, /*
3030 Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
3031 In between each pair of results, insert SEPARATOR.  Thus, using " " as
3032 SEPARATOR results in spaces between the values returned by FUNCTION.
3033 SEQUENCE may be a list, a vector, a bit vector, or a string.
3034 */
3035        (function, sequence, separator))
3036 {
3037   EMACS_INT len = XINT (Flength (sequence));
3038   Lisp_Object *args;
3039   EMACS_INT i;
3040   EMACS_INT nargs = len + len - 1;
3041
3042   if (len == 0) return build_string ("");
3043
3044   args = alloca_array (Lisp_Object, nargs);
3045
3046   mapcar1 (len, args, function, sequence);
3047
3048   for (i = len - 1; i >= 0; i--)
3049     args[i + i] = args[i];
3050
3051   for (i = 1; i < nargs; i += 2)
3052     args[i] = separator;
3053
3054   return Fconcat (nargs, args);
3055 }
3056
3057 DEFUN ("mapcar", Fmapcar, 2, 2, 0, /*
3058 Apply FUNCTION to each element of SEQUENCE; return a list of the results.
3059 The result is a list of the same length as SEQUENCE.
3060 SEQUENCE may be a list, a vector, a bit vector, or a string.
3061 */
3062        (function, sequence))
3063 {
3064   size_t len = XINT (Flength (sequence));
3065   Lisp_Object *args = alloca_array (Lisp_Object, len);
3066
3067   mapcar1 (len, args, function, sequence);
3068
3069   return Flist (len, args);
3070 }
3071
3072 DEFUN ("mapvector", Fmapvector, 2, 2, 0, /*
3073 Apply FUNCTION to each element of SEQUENCE; return a vector of the results.
3074 The result is a vector of the same length as SEQUENCE.
3075 SEQUENCE may be a list, a vector, a bit vector, or a string.
3076 */
3077        (function, sequence))
3078 {
3079   size_t len = XINT (Flength (sequence));
3080   Lisp_Object result = make_vector (len, Qnil);
3081   struct gcpro gcpro1;
3082
3083   GCPRO1 (result);
3084   mapcar1 (len, XVECTOR_DATA (result), function, sequence);
3085   UNGCPRO;
3086
3087   return result;
3088 }
3089
3090 DEFUN ("mapc-internal", Fmapc_internal, 2, 2, 0, /*
3091 Apply FUNCTION to each element of SEQUENCE.
3092 SEQUENCE may be a list, a vector, a bit vector, or a string.
3093 This function is like `mapcar' but does not accumulate the results,
3094 which is more efficient if you do not use the results.
3095
3096 The difference between this and `mapc' is that `mapc' supports all
3097 the spiffy Common Lisp arguments.  You should normally use `mapc'.
3098 */
3099        (function, sequence))
3100 {
3101   mapcar1 (XINT (Flength (sequence)), 0, function, sequence);
3102
3103   return sequence;
3104 }
3105
3106 \f
3107
3108
3109 DEFUN ("replace-list", Freplace_list, 2, 2, 0, /*
3110 Destructively replace the list OLD with NEW.
3111 This is like (copy-sequence NEW) except that it reuses the
3112 conses in OLD as much as possible.  If OLD and NEW are the same
3113 length, no consing will take place.
3114 */
3115        (old, new))
3116 {
3117   Lisp_Object tail, oldtail = old, prevoldtail = Qnil;
3118
3119   EXTERNAL_LIST_LOOP (tail, new)
3120     {
3121       if (!NILP (oldtail))
3122         {
3123           CHECK_CONS (oldtail);
3124           XCAR (oldtail) = XCAR (tail);
3125         }
3126       else if (!NILP (prevoldtail))
3127         {
3128           XCDR (prevoldtail) = Fcons (XCAR (tail), Qnil);
3129           prevoldtail = XCDR (prevoldtail);
3130         }
3131       else
3132         old = oldtail = Fcons (XCAR (tail), Qnil);
3133
3134       if (!NILP (oldtail))
3135         {
3136           prevoldtail = oldtail;
3137           oldtail = XCDR (oldtail);
3138         }
3139     }
3140
3141   if (!NILP (prevoldtail))
3142     XCDR (prevoldtail) = Qnil;
3143   else
3144     old = Qnil;
3145
3146   return old;
3147 }
3148
3149 \f
3150 /* #### this function doesn't belong in this file! */
3151
3152 #ifdef HAVE_GETLOADAVG
3153 #ifdef HAVE_SYS_LOADAVG_H
3154 #include <sys/loadavg.h>
3155 #endif
3156 #else
3157 int getloadavg (double loadavg[], int nelem); /* Defined in getloadavg.c */
3158 #endif
3159
3160 DEFUN ("load-average", Fload_average, 0, 1, 0, /*
3161 Return list of 1 minute, 5 minute and 15 minute load averages.
3162 Each of the three load averages is multiplied by 100,
3163 then converted to integer.
3164
3165 When USE-FLOATS is non-nil, floats will be used instead of integers.
3166 These floats are not multiplied by 100.
3167
3168 If the 5-minute or 15-minute load averages are not available, return a
3169 shortened list, containing only those averages which are available.
3170
3171 On some systems, this won't work due to permissions on /dev/kmem,
3172 in which case you can't use this.
3173 */
3174        (use_floats))
3175 {
3176   double load_ave[3];
3177   int loads = getloadavg (load_ave, countof (load_ave));
3178   Lisp_Object ret = Qnil;
3179
3180   if (loads == -2)
3181     error ("load-average not implemented for this operating system");
3182   else if (loads < 0)
3183     signal_simple_error ("Could not get load-average",
3184                          lisp_strerror (errno));
3185
3186   while (loads-- > 0)
3187     {
3188       Lisp_Object load = (NILP (use_floats) ?
3189                           make_int ((int) (100.0 * load_ave[loads]))
3190                           : make_float (load_ave[loads]));
3191       ret = Fcons (load, ret);
3192     }
3193   return ret;
3194 }
3195
3196 \f
3197 Lisp_Object Vfeatures;
3198
3199 DEFUN ("featurep", Ffeaturep, 1, 1, 0, /*
3200 Return non-nil if feature FEXP is present in this Emacs.
3201 Use this to conditionalize execution of lisp code based on the
3202  presence or absence of emacs or environment extensions.
3203 FEXP can be a symbol, a number, or a list.
3204 If it is a symbol, that symbol is looked up in the `features' variable,
3205  and non-nil will be returned if found.
3206 If it is a number, the function will return non-nil if this Emacs
3207  has an equal or greater version number than FEXP.
3208 If it is a list whose car is the symbol `and', it will return
3209  non-nil if all the features in its cdr are non-nil.
3210 If it is a list whose car is the symbol `or', it will return non-nil
3211  if any of the features in its cdr are non-nil.
3212 If it is a list whose car is the symbol `not', it will return
3213  non-nil if the feature is not present.
3214
3215 Examples:
3216
3217   (featurep 'xemacs)
3218     => ; Non-nil on XEmacs.
3219
3220   (featurep '(and xemacs gnus))
3221     => ; Non-nil on XEmacs with Gnus loaded.
3222
3223   (featurep '(or tty-frames (and emacs 19.30)))
3224     => ; Non-nil if this Emacs supports TTY frames.
3225
3226   (featurep '(or (and xemacs 19.15) (and emacs 19.34)))
3227     => ; Non-nil on XEmacs 19.15 and later, or FSF Emacs 19.34 and later.
3228
3229   (featurep '(and xemacs 21.02))
3230     => ; Non-nil on XEmacs 21.2 and later.
3231
3232 NOTE: The advanced arguments of this function (anything other than a
3233 symbol) are not yet supported by FSF Emacs.  If you feel they are useful
3234 for supporting multiple Emacs variants, lobby Richard Stallman at
3235 <bug-gnu-emacs@gnu.org>.
3236 */
3237        (fexp))
3238 {
3239 #ifndef FEATUREP_SYNTAX
3240   CHECK_SYMBOL (fexp);
3241   return NILP (Fmemq (fexp, Vfeatures)) ? Qnil : Qt;
3242 #else  /* FEATUREP_SYNTAX */
3243   static double featurep_emacs_version;
3244
3245   /* Brute force translation from Erik Naggum's lisp function. */
3246   if (SYMBOLP (fexp))
3247     {
3248       /* Original definition */
3249       return NILP (Fmemq (fexp, Vfeatures)) ? Qnil : Qt;
3250     }
3251   else if (INTP (fexp) || FLOATP (fexp))
3252     {
3253       double d = extract_float (fexp);
3254
3255       if (featurep_emacs_version == 0.0)
3256         {
3257           featurep_emacs_version = XINT (Vemacs_major_version) +
3258             (XINT (Vemacs_minor_version) / 100.0);
3259         }
3260       return featurep_emacs_version >= d ? Qt : Qnil;
3261     }
3262   else if (CONSP (fexp))
3263     {
3264       Lisp_Object tem = XCAR (fexp);
3265       if (EQ (tem, Qnot))
3266         {
3267           Lisp_Object negate;
3268
3269           tem = XCDR (fexp);
3270           negate = Fcar (tem);
3271           if (!NILP (tem))
3272             return NILP (call1 (Qfeaturep, negate)) ? Qt : Qnil;
3273           else
3274             return Fsignal (Qinvalid_read_syntax, list1 (tem));
3275         }
3276       else if (EQ (tem, Qand))
3277         {
3278           tem = XCDR (fexp);
3279           /* Use Fcar/Fcdr for error-checking. */
3280           while (!NILP (tem) && !NILP (call1 (Qfeaturep, Fcar (tem))))
3281             {
3282               tem = Fcdr (tem);
3283             }
3284           return NILP (tem) ? Qt : Qnil;
3285         }
3286       else if (EQ (tem, Qor))
3287         {
3288           tem = XCDR (fexp);
3289           /* Use Fcar/Fcdr for error-checking. */
3290           while (!NILP (tem) && NILP (call1 (Qfeaturep, Fcar (tem))))
3291             {
3292               tem = Fcdr (tem);
3293             }
3294           return NILP (tem) ? Qnil : Qt;
3295         }
3296       else
3297         {
3298           return Fsignal (Qinvalid_read_syntax, list1 (XCDR (fexp)));
3299         }
3300     }
3301   else
3302     {
3303       return Fsignal (Qinvalid_read_syntax, list1 (fexp));
3304     }
3305 }
3306 #endif /* FEATUREP_SYNTAX */
3307
3308 DEFUN ("provide", Fprovide, 1, 1, 0, /*
3309 Announce that FEATURE is a feature of the current Emacs.
3310 This function updates the value of the variable `features'.
3311 */
3312        (feature))
3313 {
3314   Lisp_Object tem;
3315   CHECK_SYMBOL (feature);
3316   if (!NILP (Vautoload_queue))
3317     Vautoload_queue = Fcons (Fcons (Vfeatures, Qnil), Vautoload_queue);
3318   tem = Fmemq (feature, Vfeatures);
3319   if (NILP (tem))
3320     Vfeatures = Fcons (feature, Vfeatures);
3321   LOADHIST_ATTACH (Fcons (Qprovide, feature));
3322   return feature;
3323 }
3324
3325 DEFUN ("require", Frequire, 1, 2, 0, /*
3326 If feature FEATURE is not loaded, load it from FILENAME.
3327 If FEATURE is not a member of the list `features', then the feature
3328 is not loaded; so load the file FILENAME.
3329 If FILENAME is omitted, the printname of FEATURE is used as the file name.
3330 */
3331        (feature, filename))
3332 {
3333   Lisp_Object tem;
3334   CHECK_SYMBOL (feature);
3335   tem = Fmemq (feature, Vfeatures);
3336   LOADHIST_ATTACH (Fcons (Qrequire, feature));
3337   if (!NILP (tem))
3338     return feature;
3339   else
3340     {
3341       int speccount = specpdl_depth ();
3342
3343       /* Value saved here is to be restored into Vautoload_queue */
3344       record_unwind_protect (un_autoload, Vautoload_queue);
3345       Vautoload_queue = Qt;
3346
3347       call4 (Qload, NILP (filename) ? Fsymbol_name (feature) : filename,
3348              Qnil, Qt, Qnil);
3349
3350       tem = Fmemq (feature, Vfeatures);
3351       if (NILP (tem))
3352         error ("Required feature %s was not provided",
3353                string_data (XSYMBOL (feature)->name));
3354
3355       /* Once loading finishes, don't undo it.  */
3356       Vautoload_queue = Qt;
3357       return unbind_to (speccount, feature);
3358     }
3359 }
3360 \f
3361 /* base64 encode/decode functions.
3362
3363    Originally based on code from GNU recode.  Ported to FSF Emacs by
3364    Lars Magne Ingebrigtsen and Karl Heuer.  Ported to XEmacs and
3365    subsequently heavily hacked by Hrvoje Niksic.  */
3366
3367 #define MIME_LINE_LENGTH 72
3368
3369 #define IS_ASCII(Character) \
3370   ((Character) < 128)
3371 #define IS_BASE64(Character) \
3372   (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3373
3374 /* Table of characters coding the 64 values.  */
3375 static char base64_value_to_char[64] =
3376 {
3377   'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',     /*  0- 9 */
3378   'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',     /* 10-19 */
3379   'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',     /* 20-29 */
3380   'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',     /* 30-39 */
3381   'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',     /* 40-49 */
3382   'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',     /* 50-59 */
3383   '8', '9', '+', '/'                                    /* 60-63 */
3384 };
3385
3386 /* Table of base64 values for first 128 characters.  */
3387 static short base64_char_to_value[128] =
3388 {
3389   -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,      /*   0-  9 */
3390   -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,      /*  10- 19 */
3391   -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,      /*  20- 29 */
3392   -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,      /*  30- 39 */
3393   -1,  -1,  -1,  62,  -1,  -1,  -1,  63,  52,  53,      /*  40- 49 */
3394   54,  55,  56,  57,  58,  59,  60,  61,  -1,  -1,      /*  50- 59 */
3395   -1,  -1,  -1,  -1,  -1,  0,   1,   2,   3,   4,       /*  60- 69 */
3396   5,   6,   7,   8,   9,   10,  11,  12,  13,  14,      /*  70- 79 */
3397   15,  16,  17,  18,  19,  20,  21,  22,  23,  24,      /*  80- 89 */
3398   25,  -1,  -1,  -1,  -1,  -1,  -1,  26,  27,  28,      /*  90- 99 */
3399   29,  30,  31,  32,  33,  34,  35,  36,  37,  38,      /* 100-109 */
3400   39,  40,  41,  42,  43,  44,  45,  46,  47,  48,      /* 110-119 */
3401   49,  50,  51,  -1,  -1,  -1,  -1,  -1                 /* 120-127 */
3402 };
3403
3404 /* The following diagram shows the logical steps by which three octets
3405    get transformed into four base64 characters.
3406
3407                  .--------.  .--------.  .--------.
3408                  |aaaaaabb|  |bbbbcccc|  |ccdddddd|
3409                  `--------'  `--------'  `--------'
3410                     6   2      4   4       2   6
3411                .--------+--------+--------+--------.
3412                |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3413                `--------+--------+--------+--------'
3414
3415                .--------+--------+--------+--------.
3416                |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3417                `--------+--------+--------+--------'
3418
3419    The octets are divided into 6 bit chunks, which are then encoded into
3420    base64 characters.  */
3421
3422 #define ADVANCE_INPUT(c, stream)                                \
3423  ((ec = Lstream_get_emchar (stream)) == -1 ? 0 :                \
3424   ((ec > 255) ?                                                 \
3425    (signal_simple_error ("Non-ascii character in base64 input", \
3426                          make_char (ec)), 0)                    \
3427    : (c = (Bufbyte)ec), 1))
3428
3429 static Bytind
3430 base64_encode_1 (Lstream *istream, Bufbyte *to, int line_break)
3431 {
3432   EMACS_INT counter = 0;
3433   Bufbyte *e = to;
3434   Emchar ec;
3435   unsigned int value;
3436
3437   while (1)
3438     {
3439       Bufbyte c;
3440       if (!ADVANCE_INPUT (c, istream))
3441         break;
3442
3443       /* Wrap line every 76 characters.  */
3444       if (line_break)
3445         {
3446           if (counter < MIME_LINE_LENGTH / 4)
3447             counter++;
3448           else
3449             {
3450               *e++ = '\n';
3451               counter = 1;
3452             }
3453         }
3454
3455       /* Process first byte of a triplet.  */
3456       *e++ = base64_value_to_char[0x3f & c >> 2];
3457       value = (0x03 & c) << 4;
3458
3459       /* Process second byte of a triplet.  */
3460       if (!ADVANCE_INPUT (c, istream))
3461         {
3462           *e++ = base64_value_to_char[value];
3463           *e++ = '=';
3464           *e++ = '=';
3465           break;
3466         }
3467
3468       *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3469       value = (0x0f & c) << 2;
3470
3471       /* Process third byte of a triplet.  */
3472       if (!ADVANCE_INPUT (c, istream))
3473         {
3474           *e++ = base64_value_to_char[value];
3475           *e++ = '=';
3476           break;
3477         }
3478
3479       *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3480       *e++ = base64_value_to_char[0x3f & c];
3481     }
3482
3483   return e - to;
3484 }
3485 #undef ADVANCE_INPUT
3486
3487 /* Get next character from the stream, except that non-base64
3488    characters are ignored.  This is in accordance with rfc2045.  EC
3489    should be an Emchar, so that it can hold -1 as the value for EOF.  */
3490 #define ADVANCE_INPUT_IGNORE_NONBASE64(ec, stream, streampos) do {      \
3491   ec = Lstream_get_emchar (stream);                                     \
3492   ++streampos;                                                          \
3493   /* IS_BASE64 may not be called with negative arguments so check for   \
3494      EOF first. */                                                      \
3495   if (ec < 0 || IS_BASE64 (ec) || ec == '=')                            \
3496     break;                                                              \
3497 } while (1)
3498
3499 #define STORE_BYTE(pos, val, ccnt) do {                                 \
3500   pos += set_charptr_emchar (pos, (Emchar)((unsigned char)(val)));      \
3501   ++ccnt;                                                               \
3502 } while (0)
3503
3504 static Bytind
3505 base64_decode_1 (Lstream *istream, Bufbyte *to, Charcount *ccptr)
3506 {
3507   Charcount ccnt = 0;
3508   Bufbyte *e = to;
3509   EMACS_INT streampos = 0;
3510
3511   while (1)
3512     {
3513       Emchar ec;
3514       unsigned long value;
3515
3516       /* Process first byte of a quadruplet.  */
3517       ADVANCE_INPUT_IGNORE_NONBASE64 (ec, istream, streampos);
3518       if (ec < 0)
3519         break;
3520       if (ec == '=')
3521         signal_simple_error ("Illegal `=' character while decoding base64",
3522                              make_int (streampos));
3523       value = base64_char_to_value[ec] << 18;
3524
3525       /* Process second byte of a quadruplet.  */
3526       ADVANCE_INPUT_IGNORE_NONBASE64 (ec, istream, streampos);
3527       if (ec < 0)
3528         error ("Premature EOF while decoding base64");
3529       if (ec == '=')
3530         signal_simple_error ("Illegal `=' character while decoding base64",
3531                              make_int (streampos));
3532       value |= base64_char_to_value[ec] << 12;
3533       STORE_BYTE (e, value >> 16, ccnt);
3534
3535       /* Process third byte of a quadruplet.  */
3536       ADVANCE_INPUT_IGNORE_NONBASE64 (ec, istream, streampos);
3537       if (ec < 0)
3538         error ("Premature EOF while decoding base64");
3539
3540       if (ec == '=')
3541         {
3542           ADVANCE_INPUT_IGNORE_NONBASE64 (ec, istream, streampos);
3543           if (ec < 0)
3544             error ("Premature EOF while decoding base64");
3545           if (ec != '=')
3546             signal_simple_error ("Padding `=' expected but not found while decoding base64",
3547                                  make_int (streampos));
3548           continue;
3549         }
3550
3551       value |= base64_char_to_value[ec] << 6;
3552       STORE_BYTE (e, 0xff & value >> 8, ccnt);
3553
3554       /* Process fourth byte of a quadruplet.  */
3555       ADVANCE_INPUT_IGNORE_NONBASE64 (ec, istream, streampos);
3556       if (ec < 0)
3557         error ("Premature EOF while decoding base64");
3558       if (ec == '=')
3559         continue;
3560
3561       value |= base64_char_to_value[ec];
3562       STORE_BYTE (e, 0xff & value, ccnt);
3563     }
3564
3565   *ccptr = ccnt;
3566   return e - to;
3567 }
3568 #undef ADVANCE_INPUT
3569 #undef ADVANCE_INPUT_IGNORE_NONBASE64
3570 #undef STORE_BYTE
3571
3572 static Lisp_Object
3573 free_malloced_ptr (Lisp_Object unwind_obj)
3574 {
3575   void *ptr = (void *)get_opaque_ptr (unwind_obj);
3576   xfree (ptr);
3577   free_opaque_ptr (unwind_obj);
3578   return Qnil;
3579 }
3580
3581 /* Don't use alloca for regions larger than this, lest we overflow
3582    the stack.  */
3583 #define MAX_ALLOCA 65536
3584
3585 /* We need to setup proper unwinding, because there is a number of
3586    ways these functions can blow up, and we don't want to have memory
3587    leaks in those cases.  */
3588 #define XMALLOC_OR_ALLOCA(ptr, len, type) do {                  \
3589   size_t XOA_len = (len);                                       \
3590   if (XOA_len > MAX_ALLOCA)                                     \
3591     {                                                           \
3592       ptr = xnew_array (type, XOA_len);                         \
3593       record_unwind_protect (free_malloced_ptr,                 \
3594                              make_opaque_ptr ((void *)ptr));    \
3595     }                                                           \
3596   else                                                          \
3597     ptr = alloca_array (type, XOA_len);                         \
3598 } while (0)
3599
3600 #define XMALLOC_UNBIND(ptr, len, speccount) do {                \
3601   if ((len) > MAX_ALLOCA)                                       \
3602     unbind_to (speccount, Qnil);                                \
3603 } while (0)
3604
3605 DEFUN ("base64-encode-region", Fbase64_encode_region, 2, 3, "r", /*
3606 Base64-encode the region between START and END.
3607 Return the length of the encoded text.
3608 Optional third argument NO-LINE-BREAK means do not break long lines
3609 into shorter lines.
3610 */
3611        (start, end, no_line_break))
3612 {
3613   Bufbyte *encoded;
3614   Bytind encoded_length;
3615   Charcount allength, length;
3616   struct buffer *buf = current_buffer;
3617   Bufpos begv, zv, old_pt = BUF_PT (buf);
3618   Lisp_Object input;
3619   int speccount = specpdl_depth();
3620
3621   get_buffer_range_char (buf, start, end, &begv, &zv, 0);
3622   barf_if_buffer_read_only (buf, begv, zv);
3623
3624   /* We need to allocate enough room for encoding the text.
3625      We need 33 1/3% more space, plus a newline every 76
3626      characters, and then we round up. */
3627   length = zv - begv;
3628   allength = length + length/3 + 1;
3629   allength += allength / MIME_LINE_LENGTH + 1 + 6;
3630
3631   input = make_lisp_buffer_input_stream (buf, begv, zv, 0);
3632   /* We needn't multiply allength with MAX_EMCHAR_LEN because all the
3633      base64 characters will be single-byte.  */
3634   XMALLOC_OR_ALLOCA (encoded, allength, Bufbyte);
3635   encoded_length = base64_encode_1 (XLSTREAM (input), encoded,
3636                                     NILP (no_line_break));
3637   if (encoded_length > allength)
3638     abort ();
3639   Lstream_delete (XLSTREAM (input));
3640
3641   /* Now we have encoded the region, so we insert the new contents
3642      and delete the old.  (Insert first in order to preserve markers.)  */
3643   buffer_insert_raw_string_1 (buf, begv, encoded, encoded_length, 0);
3644   XMALLOC_UNBIND (encoded, allength, speccount);
3645   buffer_delete_range (buf, begv + encoded_length, zv + encoded_length, 0);
3646
3647   /* Simulate FSF Emacs implementation of this function: if point was
3648      in the region, place it at the beginning.  */
3649   if (old_pt >= begv && old_pt < zv)
3650     BUF_SET_PT (buf, begv);
3651
3652   /* We return the length of the encoded text. */
3653   return make_int (encoded_length);
3654 }
3655
3656 DEFUN ("base64-encode-string", Fbase64_encode_string, 1, 2, 0, /*
3657 Base64 encode STRING and return the result.
3658 Optional argument NO-LINE-BREAK means do not break long lines
3659 into shorter lines.
3660 */
3661        (string, no_line_break))
3662 {
3663   Charcount allength, length;
3664   Bytind encoded_length;
3665   Bufbyte *encoded;
3666   Lisp_Object input, result;
3667   int speccount = specpdl_depth();
3668
3669   CHECK_STRING (string);
3670
3671   length = XSTRING_CHAR_LENGTH (string);
3672   allength = length + length/3 + 1;
3673   allength += allength / MIME_LINE_LENGTH + 1 + 6;
3674
3675   input = make_lisp_string_input_stream (string, 0, -1);
3676   XMALLOC_OR_ALLOCA (encoded, allength, Bufbyte);
3677   encoded_length = base64_encode_1 (XLSTREAM (input), encoded,
3678                                     NILP (no_line_break));
3679   if (encoded_length > allength)
3680     abort ();
3681   Lstream_delete (XLSTREAM (input));
3682   result = make_string (encoded, encoded_length);
3683   XMALLOC_UNBIND (encoded, allength, speccount);
3684   return result;
3685 }
3686
3687 DEFUN ("base64-decode-region", Fbase64_decode_region, 2, 2, "r", /*
3688 Base64-decode the region between START and END.
3689 Return the length of the decoded text.
3690 If the region can't be decoded, return nil and don't modify the buffer.
3691 Characters out of the base64 alphabet are ignored.
3692 */
3693        (start, end))
3694 {
3695   struct buffer *buf = current_buffer;
3696   Bufpos begv, zv, old_pt = BUF_PT (buf);
3697   Bufbyte *decoded;
3698   Bytind decoded_length;
3699   Charcount length, cc_decoded_length;
3700   Lisp_Object input;
3701   int speccount = specpdl_depth();
3702
3703   get_buffer_range_char (buf, start, end, &begv, &zv, 0);
3704   barf_if_buffer_read_only (buf, begv, zv);
3705
3706   length = zv - begv;
3707
3708   input = make_lisp_buffer_input_stream (buf, begv, zv, 0);
3709   /* We need to allocate enough room for decoding the text. */
3710   XMALLOC_OR_ALLOCA (decoded, length * MAX_EMCHAR_LEN, Bufbyte);
3711   decoded_length = base64_decode_1 (XLSTREAM (input), decoded, &cc_decoded_length);
3712   if (decoded_length > length * MAX_EMCHAR_LEN)
3713     abort ();
3714   Lstream_delete (XLSTREAM (input));
3715
3716   /* Now we have decoded the region, so we insert the new contents
3717      and delete the old.  (Insert first in order to preserve markers.)  */
3718   BUF_SET_PT (buf, begv);
3719   buffer_insert_raw_string_1 (buf, begv, decoded, decoded_length, 0);
3720   XMALLOC_UNBIND (decoded, length * MAX_EMCHAR_LEN, speccount);
3721   buffer_delete_range (buf, begv + cc_decoded_length,
3722                        zv + cc_decoded_length, 0);
3723
3724   /* Simulate FSF Emacs implementation of this function: if point was
3725      in the region, place it at the beginning.  */
3726   if (old_pt >= begv && old_pt < zv)
3727     BUF_SET_PT (buf, begv);
3728
3729   return make_int (cc_decoded_length);
3730 }
3731
3732 DEFUN ("base64-decode-string", Fbase64_decode_string, 1, 1, 0, /*
3733 Base64-decode STRING and return the result.
3734 Characters out of the base64 alphabet are ignored.
3735 */
3736        (string))
3737 {
3738   Bufbyte *decoded;
3739   Bytind decoded_length;
3740   Charcount length, cc_decoded_length;
3741   Lisp_Object input, result;
3742   int speccount = specpdl_depth();
3743
3744   CHECK_STRING (string);
3745
3746   length = XSTRING_CHAR_LENGTH (string);
3747   /* We need to allocate enough room for decoding the text. */
3748   XMALLOC_OR_ALLOCA (decoded, length * MAX_EMCHAR_LEN, Bufbyte);
3749
3750   input = make_lisp_string_input_stream (string, 0, -1);
3751   decoded_length = base64_decode_1 (XLSTREAM (input), decoded,
3752                                     &cc_decoded_length);
3753   if (decoded_length > length * MAX_EMCHAR_LEN)
3754     abort ();
3755   Lstream_delete (XLSTREAM (input));
3756
3757   result = make_string (decoded, decoded_length);
3758   XMALLOC_UNBIND (decoded, length * MAX_EMCHAR_LEN, speccount);
3759   return result;
3760 }
3761 \f
3762 Lisp_Object Qyes_or_no_p;
3763
3764 void
3765 syms_of_fns (void)
3766 {
3767   INIT_LRECORD_IMPLEMENTATION (bit_vector);
3768
3769   defsymbol (&Qstring_lessp, "string-lessp");
3770   defsymbol (&Qidentity, "identity");
3771   defsymbol (&Qyes_or_no_p, "yes-or-no-p");
3772
3773   DEFSUBR (Fidentity);
3774   DEFSUBR (Frandom);
3775   DEFSUBR (Flength);
3776   DEFSUBR (Fsafe_length);
3777   DEFSUBR (Fstring_equal);
3778   DEFSUBR (Fstring_lessp);
3779   DEFSUBR (Fstring_modified_tick);
3780   DEFSUBR (Fappend);
3781   DEFSUBR (Fconcat);
3782   DEFSUBR (Fvconcat);
3783   DEFSUBR (Fbvconcat);
3784   DEFSUBR (Fcopy_list);
3785   DEFSUBR (Fcopy_sequence);
3786   DEFSUBR (Fcopy_alist);
3787   DEFSUBR (Fcopy_tree);
3788   DEFSUBR (Fsubstring);
3789   DEFSUBR (Fsubseq);
3790   DEFSUBR (Fnthcdr);
3791   DEFSUBR (Fnth);
3792   DEFSUBR (Felt);
3793   DEFSUBR (Flast);
3794   DEFSUBR (Fbutlast);
3795   DEFSUBR (Fnbutlast);
3796   DEFSUBR (Fmember);
3797   DEFSUBR (Fold_member);
3798   DEFSUBR (Fmemq);
3799   DEFSUBR (Fold_memq);
3800   DEFSUBR (Fassoc);
3801   DEFSUBR (Fold_assoc);
3802   DEFSUBR (Fassq);
3803   DEFSUBR (Fold_assq);
3804   DEFSUBR (Frassoc);
3805   DEFSUBR (Fold_rassoc);
3806   DEFSUBR (Frassq);
3807   DEFSUBR (Fold_rassq);
3808   DEFSUBR (Fdelete);
3809   DEFSUBR (Fold_delete);
3810   DEFSUBR (Fdelq);
3811   DEFSUBR (Fold_delq);
3812   DEFSUBR (Fremassoc);
3813   DEFSUBR (Fremassq);
3814   DEFSUBR (Fremrassoc);
3815   DEFSUBR (Fremrassq);
3816   DEFSUBR (Fnreverse);
3817   DEFSUBR (Freverse);
3818   DEFSUBR (Fsort);
3819   DEFSUBR (Fplists_eq);
3820   DEFSUBR (Fplists_equal);
3821   DEFSUBR (Flax_plists_eq);
3822   DEFSUBR (Flax_plists_equal);
3823   DEFSUBR (Fplist_get);
3824   DEFSUBR (Fplist_put);
3825   DEFSUBR (Fplist_remprop);
3826   DEFSUBR (Fplist_member);
3827   DEFSUBR (Fcheck_valid_plist);
3828   DEFSUBR (Fvalid_plist_p);
3829   DEFSUBR (Fcanonicalize_plist);
3830   DEFSUBR (Flax_plist_get);
3831   DEFSUBR (Flax_plist_put);
3832   DEFSUBR (Flax_plist_remprop);
3833   DEFSUBR (Flax_plist_member);
3834   DEFSUBR (Fcanonicalize_lax_plist);
3835   DEFSUBR (Fdestructive_alist_to_plist);
3836   DEFSUBR (Fget);
3837   DEFSUBR (Fput);
3838   DEFSUBR (Fremprop);
3839   DEFSUBR (Fobject_plist);
3840   DEFSUBR (Fequal);
3841   DEFSUBR (Fold_equal);
3842   DEFSUBR (Ffillarray);
3843   DEFSUBR (Fnconc);
3844   DEFSUBR (Fmapcar);
3845   DEFSUBR (Fmapvector);
3846   DEFSUBR (Fmapc_internal);
3847   DEFSUBR (Fmapconcat);
3848   DEFSUBR (Freplace_list);
3849   DEFSUBR (Fload_average);
3850   DEFSUBR (Ffeaturep);
3851   DEFSUBR (Frequire);
3852   DEFSUBR (Fprovide);
3853   DEFSUBR (Fbase64_encode_region);
3854   DEFSUBR (Fbase64_encode_string);
3855   DEFSUBR (Fbase64_decode_region);
3856   DEFSUBR (Fbase64_decode_string);
3857 }
3858
3859 void
3860 init_provide_once (void)
3861 {
3862   DEFVAR_LISP ("features", &Vfeatures /*
3863 A list of symbols which are the features of the executing emacs.
3864 Used by `featurep' and `require', and altered by `provide'.
3865 */ );
3866   Vfeatures = Qnil;
3867
3868   Fprovide (intern ("base64"));
3869 }