Move #include "systime.h" before <sys/resource.h>.
[bpt/emacs.git] / src / editfns.c
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98,1999,2000,01,02,03,2004
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; 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
23 #include <config.h>
24 #include <sys/types.h>
25 #include <stdio.h>
26
27 #ifdef VMS
28 #include "vms-pwd.h"
29 #else
30 #include <pwd.h>
31 #endif
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 /* systime.h includes <sys/time.h> which, on some systems, is required
38 for <sys/resource.h>; thus systime.h must be included before
39 <sys/resource.h> */
40 #include "systime.h"
41
42 #if defined HAVE_SYS_RESOURCE_H
43 #include <sys/resource.h>
44 #endif
45
46 #include <ctype.h>
47
48 #include "lisp.h"
49 #include "intervals.h"
50 #include "buffer.h"
51 #include "charset.h"
52 #include "coding.h"
53 #include "frame.h"
54 #include "window.h"
55
56 #ifdef STDC_HEADERS
57 #include <float.h>
58 #define MAX_10_EXP DBL_MAX_10_EXP
59 #else
60 #define MAX_10_EXP 310
61 #endif
62
63 #ifndef NULL
64 #define NULL 0
65 #endif
66
67 #ifndef USE_CRT_DLL
68 extern char **environ;
69 #endif
70
71 extern Lisp_Object make_time P_ ((time_t));
72 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
73 const struct tm *, int));
74 static int tm_diff P_ ((struct tm *, struct tm *));
75 static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
76 static void update_buffer_properties P_ ((int, int));
77 static Lisp_Object region_limit P_ ((int));
78 int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
79 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
80 size_t, const struct tm *, int));
81 static void general_insert_function P_ ((void (*) (const unsigned char *, int),
82 void (*) (Lisp_Object, int, int, int,
83 int, int),
84 int, int, Lisp_Object *));
85 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
86 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
87 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
88
89 #ifdef HAVE_INDEX
90 extern char *index P_ ((const char *, int));
91 #endif
92
93 Lisp_Object Vbuffer_access_fontify_functions;
94 Lisp_Object Qbuffer_access_fontify_functions;
95 Lisp_Object Vbuffer_access_fontified_property;
96
97 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
98
99 /* Non-nil means don't stop at field boundary in text motion commands. */
100
101 Lisp_Object Vinhibit_field_text_motion;
102
103 /* Some static data, and a function to initialize it for each run */
104
105 Lisp_Object Vsystem_name;
106 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
107 Lisp_Object Vuser_full_name; /* full name of current user */
108 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
109
110 /* Symbol for the text property used to mark fields. */
111
112 Lisp_Object Qfield;
113
114 /* A special value for Qfield properties. */
115
116 Lisp_Object Qboundary;
117
118
119 void
120 init_editfns ()
121 {
122 char *user_name;
123 register unsigned char *p;
124 struct passwd *pw; /* password entry for the current user */
125 Lisp_Object tem;
126
127 /* Set up system_name even when dumping. */
128 init_system_name ();
129
130 #ifndef CANNOT_DUMP
131 /* Don't bother with this on initial start when just dumping out */
132 if (!initialized)
133 return;
134 #endif /* not CANNOT_DUMP */
135
136 pw = (struct passwd *) getpwuid (getuid ());
137 #ifdef MSDOS
138 /* We let the real user name default to "root" because that's quite
139 accurate on MSDOG and because it lets Emacs find the init file.
140 (The DVX libraries override the Djgpp libraries here.) */
141 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
142 #else
143 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
144 #endif
145
146 /* Get the effective user name, by consulting environment variables,
147 or the effective uid if those are unset. */
148 user_name = (char *) getenv ("LOGNAME");
149 if (!user_name)
150 #ifdef WINDOWSNT
151 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
152 #else /* WINDOWSNT */
153 user_name = (char *) getenv ("USER");
154 #endif /* WINDOWSNT */
155 if (!user_name)
156 {
157 pw = (struct passwd *) getpwuid (geteuid ());
158 user_name = (char *) (pw ? pw->pw_name : "unknown");
159 }
160 Vuser_login_name = build_string (user_name);
161
162 /* If the user name claimed in the environment vars differs from
163 the real uid, use the claimed name to find the full name. */
164 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
165 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
166 : Vuser_login_name);
167
168 p = (unsigned char *) getenv ("NAME");
169 if (p)
170 Vuser_full_name = build_string (p);
171 else if (NILP (Vuser_full_name))
172 Vuser_full_name = build_string ("unknown");
173 }
174 \f
175 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
176 doc: /* Convert arg CHAR to a string containing that character.
177 usage: (char-to-string CHAR) */)
178 (character)
179 Lisp_Object character;
180 {
181 int len;
182 unsigned char str[MAX_MULTIBYTE_LENGTH];
183
184 CHECK_NUMBER (character);
185
186 len = (SINGLE_BYTE_CHAR_P (XFASTINT (character))
187 ? (*str = (unsigned char)(XFASTINT (character)), 1)
188 : char_to_string (XFASTINT (character), str));
189 return make_string_from_bytes (str, 1, len);
190 }
191
192 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
193 doc: /* Convert arg STRING to a character, the first character of that string.
194 A multibyte character is handled correctly. */)
195 (string)
196 register Lisp_Object string;
197 {
198 register Lisp_Object val;
199 CHECK_STRING (string);
200 if (SCHARS (string))
201 {
202 if (STRING_MULTIBYTE (string))
203 XSETFASTINT (val, STRING_CHAR (SDATA (string), SBYTES (string)));
204 else
205 XSETFASTINT (val, SREF (string, 0));
206 }
207 else
208 XSETFASTINT (val, 0);
209 return val;
210 }
211 \f
212 static Lisp_Object
213 buildmark (charpos, bytepos)
214 int charpos, bytepos;
215 {
216 register Lisp_Object mark;
217 mark = Fmake_marker ();
218 set_marker_both (mark, Qnil, charpos, bytepos);
219 return mark;
220 }
221
222 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
223 doc: /* Return value of point, as an integer.
224 Beginning of buffer is position (point-min). */)
225 ()
226 {
227 Lisp_Object temp;
228 XSETFASTINT (temp, PT);
229 return temp;
230 }
231
232 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
233 doc: /* Return value of point, as a marker object. */)
234 ()
235 {
236 return buildmark (PT, PT_BYTE);
237 }
238
239 int
240 clip_to_bounds (lower, num, upper)
241 int lower, num, upper;
242 {
243 if (num < lower)
244 return lower;
245 else if (num > upper)
246 return upper;
247 else
248 return num;
249 }
250
251 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
252 doc: /* Set point to POSITION, a number or marker.
253 Beginning of buffer is position (point-min), end is (point-max).
254 If the position is in the middle of a multibyte form,
255 the actual point is set at the head of the multibyte form
256 except in the case that `enable-multibyte-characters' is nil. */)
257 (position)
258 register Lisp_Object position;
259 {
260 int pos;
261
262 if (MARKERP (position)
263 && current_buffer == XMARKER (position)->buffer)
264 {
265 pos = marker_position (position);
266 if (pos < BEGV)
267 SET_PT_BOTH (BEGV, BEGV_BYTE);
268 else if (pos > ZV)
269 SET_PT_BOTH (ZV, ZV_BYTE);
270 else
271 SET_PT_BOTH (pos, marker_byte_position (position));
272
273 return position;
274 }
275
276 CHECK_NUMBER_COERCE_MARKER (position);
277
278 pos = clip_to_bounds (BEGV, XINT (position), ZV);
279 SET_PT (pos);
280 return position;
281 }
282
283
284 /* Return the start or end position of the region.
285 BEGINNINGP non-zero means return the start.
286 If there is no region active, signal an error. */
287
288 static Lisp_Object
289 region_limit (beginningp)
290 int beginningp;
291 {
292 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
293 Lisp_Object m;
294
295 if (!NILP (Vtransient_mark_mode)
296 && NILP (Vmark_even_if_inactive)
297 && NILP (current_buffer->mark_active))
298 Fsignal (Qmark_inactive, Qnil);
299
300 m = Fmarker_position (current_buffer->mark);
301 if (NILP (m))
302 error ("The mark is not set now, so there is no region");
303
304 if ((PT < XFASTINT (m)) == (beginningp != 0))
305 m = make_number (PT);
306 return m;
307 }
308
309 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
310 doc: /* Return position of beginning of region, as an integer. */)
311 ()
312 {
313 return region_limit (1);
314 }
315
316 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
317 doc: /* Return position of end of region, as an integer. */)
318 ()
319 {
320 return region_limit (0);
321 }
322
323 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
324 doc: /* Return this buffer's mark, as a marker object.
325 Watch out! Moving this marker changes the mark position.
326 If you set the marker not to point anywhere, the buffer will have no mark. */)
327 ()
328 {
329 return current_buffer->mark;
330 }
331
332 \f
333 /* Find all the overlays in the current buffer that touch position POS.
334 Return the number found, and store them in a vector in VEC
335 of length LEN. */
336
337 static int
338 overlays_around (pos, vec, len)
339 int pos;
340 Lisp_Object *vec;
341 int len;
342 {
343 Lisp_Object overlay, start, end;
344 struct Lisp_Overlay *tail;
345 int startpos, endpos;
346 int idx = 0;
347
348 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
349 {
350 XSETMISC (overlay, tail);
351
352 end = OVERLAY_END (overlay);
353 endpos = OVERLAY_POSITION (end);
354 if (endpos < pos)
355 break;
356 start = OVERLAY_START (overlay);
357 startpos = OVERLAY_POSITION (start);
358 if (startpos <= pos)
359 {
360 if (idx < len)
361 vec[idx] = overlay;
362 /* Keep counting overlays even if we can't return them all. */
363 idx++;
364 }
365 }
366
367 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
368 {
369 XSETMISC (overlay, tail);
370
371 start = OVERLAY_START (overlay);
372 startpos = OVERLAY_POSITION (start);
373 if (pos < startpos)
374 break;
375 end = OVERLAY_END (overlay);
376 endpos = OVERLAY_POSITION (end);
377 if (pos <= endpos)
378 {
379 if (idx < len)
380 vec[idx] = overlay;
381 idx++;
382 }
383 }
384
385 return idx;
386 }
387
388 /* Return the value of property PROP, in OBJECT at POSITION.
389 It's the value of PROP that a char inserted at POSITION would get.
390 OBJECT is optional and defaults to the current buffer.
391 If OBJECT is a buffer, then overlay properties are considered as well as
392 text properties.
393 If OBJECT is a window, then that window's buffer is used, but
394 window-specific overlays are considered only if they are associated
395 with OBJECT. */
396 Lisp_Object
397 get_pos_property (position, prop, object)
398 Lisp_Object position, object;
399 register Lisp_Object prop;
400 {
401 CHECK_NUMBER_COERCE_MARKER (position);
402
403 if (NILP (object))
404 XSETBUFFER (object, current_buffer);
405 else if (WINDOWP (object))
406 object = XWINDOW (object)->buffer;
407
408 if (!BUFFERP (object))
409 /* pos-property only makes sense in buffers right now, since strings
410 have no overlays and no notion of insertion for which stickiness
411 could be obeyed. */
412 return Fget_text_property (position, prop, object);
413 else
414 {
415 int posn = XINT (position);
416 int noverlays;
417 Lisp_Object *overlay_vec, tem;
418 struct buffer *obuf = current_buffer;
419
420 set_buffer_temp (XBUFFER (object));
421
422 /* First try with room for 40 overlays. */
423 noverlays = 40;
424 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
425 noverlays = overlays_around (posn, overlay_vec, noverlays);
426
427 /* If there are more than 40,
428 make enough space for all, and try again. */
429 if (noverlays > 40)
430 {
431 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
432 noverlays = overlays_around (posn, overlay_vec, noverlays);
433 }
434 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
435
436 set_buffer_temp (obuf);
437
438 /* Now check the overlays in order of decreasing priority. */
439 while (--noverlays >= 0)
440 {
441 Lisp_Object ol = overlay_vec[noverlays];
442 tem = Foverlay_get (ol, prop);
443 if (!NILP (tem))
444 {
445 /* Check the overlay is indeed active at point. */
446 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
447 if ((OVERLAY_POSITION (start) == posn
448 && XMARKER (start)->insertion_type == 1)
449 || (OVERLAY_POSITION (finish) == posn
450 && XMARKER (finish)->insertion_type == 0))
451 ; /* The overlay will not cover a char inserted at point. */
452 else
453 {
454 return tem;
455 }
456 }
457 }
458
459 { /* Now check the text-properties. */
460 int stickiness = text_property_stickiness (prop, position, object);
461 if (stickiness > 0)
462 return Fget_text_property (position, prop, object);
463 else if (stickiness < 0
464 && XINT (position) > BUF_BEGV (XBUFFER (object)))
465 return Fget_text_property (make_number (XINT (position) - 1),
466 prop, object);
467 else
468 return Qnil;
469 }
470 }
471 }
472
473 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
474 the value of point is used instead. If BEG or END null,
475 means don't store the beginning or end of the field.
476
477 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
478 results; they do not effect boundary behavior.
479
480 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
481 position of a field, then the beginning of the previous field is
482 returned instead of the beginning of POS's field (since the end of a
483 field is actually also the beginning of the next input field, this
484 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
485 true case, if two fields are separated by a field with the special
486 value `boundary', and POS lies within it, then the two separated
487 fields are considered to be adjacent, and POS between them, when
488 finding the beginning and ending of the "merged" field.
489
490 Either BEG or END may be 0, in which case the corresponding value
491 is not stored. */
492
493 static void
494 find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
495 Lisp_Object pos;
496 Lisp_Object merge_at_boundary;
497 Lisp_Object beg_limit, end_limit;
498 int *beg, *end;
499 {
500 /* Fields right before and after the point. */
501 Lisp_Object before_field, after_field;
502 /* 1 if POS counts as the start of a field. */
503 int at_field_start = 0;
504 /* 1 if POS counts as the end of a field. */
505 int at_field_end = 0;
506
507 if (NILP (pos))
508 XSETFASTINT (pos, PT);
509 else
510 CHECK_NUMBER_COERCE_MARKER (pos);
511
512 after_field
513 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
514 before_field
515 = (XFASTINT (pos) > BEGV
516 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
517 Qfield, Qnil, NULL)
518 : Qnil);
519
520 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
521 and POS is at beginning of a field, which can also be interpreted
522 as the end of the previous field. Note that the case where if
523 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
524 more natural one; then we avoid treating the beginning of a field
525 specially. */
526 if (NILP (merge_at_boundary))
527 {
528 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
529 if (!EQ (field, after_field))
530 at_field_end = 1;
531 if (!EQ (field, before_field))
532 at_field_start = 1;
533 if (NILP (field) && at_field_start && at_field_end)
534 /* If an inserted char would have a nil field while the surrounding
535 text is non-nil, we're probably not looking at a
536 zero-length field, but instead at a non-nil field that's
537 not intended for editing (such as comint's prompts). */
538 at_field_end = at_field_start = 0;
539 }
540
541 /* Note about special `boundary' fields:
542
543 Consider the case where the point (`.') is between the fields `x' and `y':
544
545 xxxx.yyyy
546
547 In this situation, if merge_at_boundary is true, we consider the
548 `x' and `y' fields as forming one big merged field, and so the end
549 of the field is the end of `y'.
550
551 However, if `x' and `y' are separated by a special `boundary' field
552 (a field with a `field' char-property of 'boundary), then we ignore
553 this special field when merging adjacent fields. Here's the same
554 situation, but with a `boundary' field between the `x' and `y' fields:
555
556 xxx.BBBByyyy
557
558 Here, if point is at the end of `x', the beginning of `y', or
559 anywhere in-between (within the `boundary' field), we merge all
560 three fields and consider the beginning as being the beginning of
561 the `x' field, and the end as being the end of the `y' field. */
562
563 if (beg)
564 {
565 if (at_field_start)
566 /* POS is at the edge of a field, and we should consider it as
567 the beginning of the following field. */
568 *beg = XFASTINT (pos);
569 else
570 /* Find the previous field boundary. */
571 {
572 Lisp_Object p = pos;
573 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
574 /* Skip a `boundary' field. */
575 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
576 beg_limit);
577
578 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
579 beg_limit);
580 *beg = NILP (p) ? BEGV : XFASTINT (p);
581 }
582 }
583
584 if (end)
585 {
586 if (at_field_end)
587 /* POS is at the edge of a field, and we should consider it as
588 the end of the previous field. */
589 *end = XFASTINT (pos);
590 else
591 /* Find the next field boundary. */
592 {
593 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
594 /* Skip a `boundary' field. */
595 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
596 end_limit);
597
598 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
599 end_limit);
600 *end = NILP (pos) ? ZV : XFASTINT (pos);
601 }
602 }
603 }
604
605 \f
606 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
607 doc: /* Delete the field surrounding POS.
608 A field is a region of text with the same `field' property.
609 If POS is nil, the value of point is used for POS. */)
610 (pos)
611 Lisp_Object pos;
612 {
613 int beg, end;
614 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
615 if (beg != end)
616 del_range (beg, end);
617 return Qnil;
618 }
619
620 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
621 doc: /* Return the contents of the field surrounding POS as a string.
622 A field is a region of text with the same `field' property.
623 If POS is nil, the value of point is used for POS. */)
624 (pos)
625 Lisp_Object pos;
626 {
627 int beg, end;
628 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
629 return make_buffer_string (beg, end, 1);
630 }
631
632 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
633 doc: /* Return the contents of the field around POS, without text-properties.
634 A field is a region of text with the same `field' property.
635 If POS is nil, the value of point is used for POS. */)
636 (pos)
637 Lisp_Object pos;
638 {
639 int beg, end;
640 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
641 return make_buffer_string (beg, end, 0);
642 }
643
644 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
645 doc: /* Return the beginning of the field surrounding POS.
646 A field is a region of text with the same `field' property.
647 If POS is nil, the value of point is used for POS.
648 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
649 field, then the beginning of the *previous* field is returned.
650 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
651 is before LIMIT, then LIMIT will be returned instead. */)
652 (pos, escape_from_edge, limit)
653 Lisp_Object pos, escape_from_edge, limit;
654 {
655 int beg;
656 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
657 return make_number (beg);
658 }
659
660 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
661 doc: /* Return the end of the field surrounding POS.
662 A field is a region of text with the same `field' property.
663 If POS is nil, the value of point is used for POS.
664 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
665 then the end of the *following* field is returned.
666 If LIMIT is non-nil, it is a buffer position; if the end of the field
667 is after LIMIT, then LIMIT will be returned instead. */)
668 (pos, escape_from_edge, limit)
669 Lisp_Object pos, escape_from_edge, limit;
670 {
671 int end;
672 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
673 return make_number (end);
674 }
675
676 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
677 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
678
679 A field is a region of text with the same `field' property.
680 If NEW-POS is nil, then the current point is used instead, and set to the
681 constrained position if that is different.
682
683 If OLD-POS is at the boundary of two fields, then the allowable
684 positions for NEW-POS depends on the value of the optional argument
685 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
686 constrained to the field that has the same `field' char-property
687 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
688 is non-nil, NEW-POS is constrained to the union of the two adjacent
689 fields. Additionally, if two fields are separated by another field with
690 the special value `boundary', then any point within this special field is
691 also considered to be `on the boundary'.
692
693 If the optional argument ONLY-IN-LINE is non-nil and constraining
694 NEW-POS would move it to a different line, NEW-POS is returned
695 unconstrained. This useful for commands that move by line, like
696 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
697 only in the case where they can still move to the right line.
698
699 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
700 a non-nil property of that name, then any field boundaries are ignored.
701
702 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
703 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
704 Lisp_Object new_pos, old_pos;
705 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
706 {
707 /* If non-zero, then the original point, before re-positioning. */
708 int orig_point = 0;
709
710 if (NILP (new_pos))
711 /* Use the current point, and afterwards, set it. */
712 {
713 orig_point = PT;
714 XSETFASTINT (new_pos, PT);
715 }
716
717 if (NILP (Vinhibit_field_text_motion)
718 && !EQ (new_pos, old_pos)
719 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
720 || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
721 && (NILP (inhibit_capture_property)
722 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
723 /* NEW_POS is not within the same field as OLD_POS; try to
724 move NEW_POS so that it is. */
725 {
726 int fwd, shortage;
727 Lisp_Object field_bound;
728
729 CHECK_NUMBER_COERCE_MARKER (new_pos);
730 CHECK_NUMBER_COERCE_MARKER (old_pos);
731
732 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
733
734 if (fwd)
735 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
736 else
737 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
738
739 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
740 other side of NEW_POS, which would mean that NEW_POS is
741 already acceptable, and it's not necessary to constrain it
742 to FIELD_BOUND. */
743 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
744 /* NEW_POS should be constrained, but only if either
745 ONLY_IN_LINE is nil (in which case any constraint is OK),
746 or NEW_POS and FIELD_BOUND are on the same line (in which
747 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
748 && (NILP (only_in_line)
749 /* This is the ONLY_IN_LINE case, check that NEW_POS and
750 FIELD_BOUND are on the same line by seeing whether
751 there's an intervening newline or not. */
752 || (scan_buffer ('\n',
753 XFASTINT (new_pos), XFASTINT (field_bound),
754 fwd ? -1 : 1, &shortage, 1),
755 shortage != 0)))
756 /* Constrain NEW_POS to FIELD_BOUND. */
757 new_pos = field_bound;
758
759 if (orig_point && XFASTINT (new_pos) != orig_point)
760 /* The NEW_POS argument was originally nil, so automatically set PT. */
761 SET_PT (XFASTINT (new_pos));
762 }
763
764 return new_pos;
765 }
766
767 \f
768 DEFUN ("line-beginning-position",
769 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
770 doc: /* Return the character position of the first character on the current line.
771 With argument N not nil or 1, move forward N - 1 lines first.
772 If scan reaches end of buffer, return that position.
773
774 The scan does not cross a field boundary unless doing so would move
775 beyond there to a different line; if N is nil or 1, and scan starts at a
776 field boundary, the scan stops as soon as it starts. To ignore field
777 boundaries bind `inhibit-field-text-motion' to t.
778
779 This function does not move point. */)
780 (n)
781 Lisp_Object n;
782 {
783 int orig, orig_byte, end;
784
785 if (NILP (n))
786 XSETFASTINT (n, 1);
787 else
788 CHECK_NUMBER (n);
789
790 orig = PT;
791 orig_byte = PT_BYTE;
792 Fforward_line (make_number (XINT (n) - 1));
793 end = PT;
794
795 SET_PT_BOTH (orig, orig_byte);
796
797 /* Return END constrained to the current input field. */
798 return Fconstrain_to_field (make_number (end), make_number (orig),
799 XINT (n) != 1 ? Qt : Qnil,
800 Qt, Qnil);
801 }
802
803 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
804 doc: /* Return the character position of the last character on the current line.
805 With argument N not nil or 1, move forward N - 1 lines first.
806 If scan reaches end of buffer, return that position.
807
808 The scan does not cross a field boundary unless doing so would move
809 beyond there to a different line; if N is nil or 1, and scan starts at a
810 field boundary, the scan stops as soon as it starts. To ignore field
811 boundaries bind `inhibit-field-text-motion' to t.
812
813 This function does not move point. */)
814 (n)
815 Lisp_Object n;
816 {
817 int end_pos;
818 int orig = PT;
819
820 if (NILP (n))
821 XSETFASTINT (n, 1);
822 else
823 CHECK_NUMBER (n);
824
825 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
826
827 /* Return END_POS constrained to the current input field. */
828 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
829 Qnil, Qt, Qnil);
830 }
831
832 \f
833 Lisp_Object
834 save_excursion_save ()
835 {
836 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
837 == current_buffer);
838
839 return Fcons (Fpoint_marker (),
840 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
841 Fcons (visible ? Qt : Qnil,
842 Fcons (current_buffer->mark_active,
843 selected_window))));
844 }
845
846 Lisp_Object
847 save_excursion_restore (info)
848 Lisp_Object info;
849 {
850 Lisp_Object tem, tem1, omark, nmark;
851 struct gcpro gcpro1, gcpro2, gcpro3;
852 int visible_p;
853
854 tem = Fmarker_buffer (XCAR (info));
855 /* If buffer being returned to is now deleted, avoid error */
856 /* Otherwise could get error here while unwinding to top level
857 and crash */
858 /* In that case, Fmarker_buffer returns nil now. */
859 if (NILP (tem))
860 return Qnil;
861
862 omark = nmark = Qnil;
863 GCPRO3 (info, omark, nmark);
864
865 Fset_buffer (tem);
866
867 /* Point marker. */
868 tem = XCAR (info);
869 Fgoto_char (tem);
870 unchain_marker (XMARKER (tem));
871
872 /* Mark marker. */
873 info = XCDR (info);
874 tem = XCAR (info);
875 omark = Fmarker_position (current_buffer->mark);
876 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
877 nmark = Fmarker_position (tem);
878 unchain_marker (XMARKER (tem));
879
880 /* visible */
881 info = XCDR (info);
882 visible_p = !NILP (XCAR (info));
883
884 #if 0 /* We used to make the current buffer visible in the selected window
885 if that was true previously. That avoids some anomalies.
886 But it creates others, and it wasn't documented, and it is simpler
887 and cleaner never to alter the window/buffer connections. */
888 tem1 = Fcar (tem);
889 if (!NILP (tem1)
890 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
891 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
892 #endif /* 0 */
893
894 /* Mark active */
895 info = XCDR (info);
896 tem = XCAR (info);
897 tem1 = current_buffer->mark_active;
898 current_buffer->mark_active = tem;
899
900 if (!NILP (Vrun_hooks))
901 {
902 /* If mark is active now, and either was not active
903 or was at a different place, run the activate hook. */
904 if (! NILP (current_buffer->mark_active))
905 {
906 if (! EQ (omark, nmark))
907 call1 (Vrun_hooks, intern ("activate-mark-hook"));
908 }
909 /* If mark has ceased to be active, run deactivate hook. */
910 else if (! NILP (tem1))
911 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
912 }
913
914 /* If buffer was visible in a window, and a different window was
915 selected, and the old selected window is still showing this
916 buffer, restore point in that window. */
917 tem = XCDR (info);
918 if (visible_p
919 && !EQ (tem, selected_window)
920 && (tem1 = XWINDOW (tem)->buffer,
921 (/* Window is live... */
922 BUFFERP (tem1)
923 /* ...and it shows the current buffer. */
924 && XBUFFER (tem1) == current_buffer)))
925 Fset_window_point (tem, make_number (PT));
926
927 UNGCPRO;
928 return Qnil;
929 }
930
931 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
932 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
933 Executes BODY just like `progn'.
934 The values of point, mark and the current buffer are restored
935 even in case of abnormal exit (throw or error).
936 The state of activation of the mark is also restored.
937
938 This construct does not save `deactivate-mark', and therefore
939 functions that change the buffer will still cause deactivation
940 of the mark at the end of the command. To prevent that, bind
941 `deactivate-mark' with `let'.
942
943 usage: (save-excursion &rest BODY) */)
944 (args)
945 Lisp_Object args;
946 {
947 register Lisp_Object val;
948 int count = SPECPDL_INDEX ();
949
950 record_unwind_protect (save_excursion_restore, save_excursion_save ());
951
952 val = Fprogn (args);
953 return unbind_to (count, val);
954 }
955
956 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
957 doc: /* Save the current buffer; execute BODY; restore the current buffer.
958 Executes BODY just like `progn'.
959 usage: (save-current-buffer &rest BODY) */)
960 (args)
961 Lisp_Object args;
962 {
963 Lisp_Object val;
964 int count = SPECPDL_INDEX ();
965
966 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
967
968 val = Fprogn (args);
969 return unbind_to (count, val);
970 }
971 \f
972 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
973 doc: /* Return the number of characters in the current buffer.
974 If BUFFER, return the number of characters in that buffer instead. */)
975 (buffer)
976 Lisp_Object buffer;
977 {
978 if (NILP (buffer))
979 return make_number (Z - BEG);
980 else
981 {
982 CHECK_BUFFER (buffer);
983 return make_number (BUF_Z (XBUFFER (buffer))
984 - BUF_BEG (XBUFFER (buffer)));
985 }
986 }
987
988 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
989 doc: /* Return the minimum permissible value of point in the current buffer.
990 This is 1, unless narrowing (a buffer restriction) is in effect. */)
991 ()
992 {
993 Lisp_Object temp;
994 XSETFASTINT (temp, BEGV);
995 return temp;
996 }
997
998 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
999 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1000 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1001 ()
1002 {
1003 return buildmark (BEGV, BEGV_BYTE);
1004 }
1005
1006 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1007 doc: /* Return the maximum permissible value of point in the current buffer.
1008 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1009 is in effect, in which case it is less. */)
1010 ()
1011 {
1012 Lisp_Object temp;
1013 XSETFASTINT (temp, ZV);
1014 return temp;
1015 }
1016
1017 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1018 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1019 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1020 is in effect, in which case it is less. */)
1021 ()
1022 {
1023 return buildmark (ZV, ZV_BYTE);
1024 }
1025
1026 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1027 doc: /* Return the position of the gap, in the current buffer.
1028 See also `gap-size'. */)
1029 ()
1030 {
1031 Lisp_Object temp;
1032 XSETFASTINT (temp, GPT);
1033 return temp;
1034 }
1035
1036 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1037 doc: /* Return the size of the current buffer's gap.
1038 See also `gap-position'. */)
1039 ()
1040 {
1041 Lisp_Object temp;
1042 XSETFASTINT (temp, GAP_SIZE);
1043 return temp;
1044 }
1045
1046 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1047 doc: /* Return the byte position for character position POSITION.
1048 If POSITION is out of range, the value is nil. */)
1049 (position)
1050 Lisp_Object position;
1051 {
1052 CHECK_NUMBER_COERCE_MARKER (position);
1053 if (XINT (position) < BEG || XINT (position) > Z)
1054 return Qnil;
1055 return make_number (CHAR_TO_BYTE (XINT (position)));
1056 }
1057
1058 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1059 doc: /* Return the character position for byte position BYTEPOS.
1060 If BYTEPOS is out of range, the value is nil. */)
1061 (bytepos)
1062 Lisp_Object bytepos;
1063 {
1064 CHECK_NUMBER (bytepos);
1065 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1066 return Qnil;
1067 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1068 }
1069 \f
1070 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1071 doc: /* Return the character following point, as a number.
1072 At the end of the buffer or accessible region, return 0. */)
1073 ()
1074 {
1075 Lisp_Object temp;
1076 if (PT >= ZV)
1077 XSETFASTINT (temp, 0);
1078 else
1079 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1080 return temp;
1081 }
1082
1083 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1084 doc: /* Return the character preceding point, as a number.
1085 At the beginning of the buffer or accessible region, return 0. */)
1086 ()
1087 {
1088 Lisp_Object temp;
1089 if (PT <= BEGV)
1090 XSETFASTINT (temp, 0);
1091 else if (!NILP (current_buffer->enable_multibyte_characters))
1092 {
1093 int pos = PT_BYTE;
1094 DEC_POS (pos);
1095 XSETFASTINT (temp, FETCH_CHAR (pos));
1096 }
1097 else
1098 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1099 return temp;
1100 }
1101
1102 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1103 doc: /* Return t if point is at the beginning of the buffer.
1104 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1105 ()
1106 {
1107 if (PT == BEGV)
1108 return Qt;
1109 return Qnil;
1110 }
1111
1112 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1113 doc: /* Return t if point is at the end of the buffer.
1114 If the buffer is narrowed, this means the end of the narrowed part. */)
1115 ()
1116 {
1117 if (PT == ZV)
1118 return Qt;
1119 return Qnil;
1120 }
1121
1122 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1123 doc: /* Return t if point is at the beginning of a line. */)
1124 ()
1125 {
1126 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1127 return Qt;
1128 return Qnil;
1129 }
1130
1131 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1132 doc: /* Return t if point is at the end of a line.
1133 `End of a line' includes point being at the end of the buffer. */)
1134 ()
1135 {
1136 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1137 return Qt;
1138 return Qnil;
1139 }
1140
1141 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1142 doc: /* Return character in current buffer at position POS.
1143 POS is an integer or a marker and defaults to point.
1144 If POS is out of range, the value is nil. */)
1145 (pos)
1146 Lisp_Object pos;
1147 {
1148 register int pos_byte;
1149
1150 if (NILP (pos))
1151 {
1152 pos_byte = PT_BYTE;
1153 XSETFASTINT (pos, PT);
1154 }
1155
1156 if (MARKERP (pos))
1157 {
1158 pos_byte = marker_byte_position (pos);
1159 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1160 return Qnil;
1161 }
1162 else
1163 {
1164 CHECK_NUMBER_COERCE_MARKER (pos);
1165 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1166 return Qnil;
1167
1168 pos_byte = CHAR_TO_BYTE (XINT (pos));
1169 }
1170
1171 return make_number (FETCH_CHAR (pos_byte));
1172 }
1173
1174 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1175 doc: /* Return character in current buffer preceding position POS.
1176 POS is an integer or a marker and defaults to point.
1177 If POS is out of range, the value is nil. */)
1178 (pos)
1179 Lisp_Object pos;
1180 {
1181 register Lisp_Object val;
1182 register int pos_byte;
1183
1184 if (NILP (pos))
1185 {
1186 pos_byte = PT_BYTE;
1187 XSETFASTINT (pos, PT);
1188 }
1189
1190 if (MARKERP (pos))
1191 {
1192 pos_byte = marker_byte_position (pos);
1193
1194 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1195 return Qnil;
1196 }
1197 else
1198 {
1199 CHECK_NUMBER_COERCE_MARKER (pos);
1200
1201 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1202 return Qnil;
1203
1204 pos_byte = CHAR_TO_BYTE (XINT (pos));
1205 }
1206
1207 if (!NILP (current_buffer->enable_multibyte_characters))
1208 {
1209 DEC_POS (pos_byte);
1210 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1211 }
1212 else
1213 {
1214 pos_byte--;
1215 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1216 }
1217 return val;
1218 }
1219 \f
1220 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1221 doc: /* Return the name under which the user logged in, as a string.
1222 This is based on the effective uid, not the real uid.
1223 Also, if the environment variables LOGNAME or USER are set,
1224 that determines the value of this function.
1225
1226 If optional argument UID is an integer, return the login name of the user
1227 with that uid, or nil if there is no such user. */)
1228 (uid)
1229 Lisp_Object uid;
1230 {
1231 struct passwd *pw;
1232
1233 /* Set up the user name info if we didn't do it before.
1234 (That can happen if Emacs is dumpable
1235 but you decide to run `temacs -l loadup' and not dump. */
1236 if (INTEGERP (Vuser_login_name))
1237 init_editfns ();
1238
1239 if (NILP (uid))
1240 return Vuser_login_name;
1241
1242 CHECK_NUMBER (uid);
1243 pw = (struct passwd *) getpwuid (XINT (uid));
1244 return (pw ? build_string (pw->pw_name) : Qnil);
1245 }
1246
1247 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1248 0, 0, 0,
1249 doc: /* Return the name of the user's real uid, as a string.
1250 This ignores the environment variables LOGNAME and USER, so it differs from
1251 `user-login-name' when running under `su'. */)
1252 ()
1253 {
1254 /* Set up the user name info if we didn't do it before.
1255 (That can happen if Emacs is dumpable
1256 but you decide to run `temacs -l loadup' and not dump. */
1257 if (INTEGERP (Vuser_login_name))
1258 init_editfns ();
1259 return Vuser_real_login_name;
1260 }
1261
1262 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1263 doc: /* Return the effective uid of Emacs.
1264 Value is an integer or float, depending on the value. */)
1265 ()
1266 {
1267 return make_fixnum_or_float (geteuid ());
1268 }
1269
1270 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1271 doc: /* Return the real uid of Emacs.
1272 Value is an integer or float, depending on the value. */)
1273 ()
1274 {
1275 return make_fixnum_or_float (getuid ());
1276 }
1277
1278 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1279 doc: /* Return the full name of the user logged in, as a string.
1280 If the full name corresponding to Emacs's userid is not known,
1281 return "unknown".
1282
1283 If optional argument UID is an integer or float, return the full name
1284 of the user with that uid, or nil if there is no such user.
1285 If UID is a string, return the full name of the user with that login
1286 name, or nil if there is no such user. */)
1287 (uid)
1288 Lisp_Object uid;
1289 {
1290 struct passwd *pw;
1291 register unsigned char *p, *q;
1292 Lisp_Object full;
1293
1294 if (NILP (uid))
1295 return Vuser_full_name;
1296 else if (NUMBERP (uid))
1297 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1298 else if (STRINGP (uid))
1299 pw = (struct passwd *) getpwnam (SDATA (uid));
1300 else
1301 error ("Invalid UID specification");
1302
1303 if (!pw)
1304 return Qnil;
1305
1306 p = (unsigned char *) USER_FULL_NAME;
1307 /* Chop off everything after the first comma. */
1308 q = (unsigned char *) index (p, ',');
1309 full = make_string (p, q ? q - p : strlen (p));
1310
1311 #ifdef AMPERSAND_FULL_NAME
1312 p = SDATA (full);
1313 q = (unsigned char *) index (p, '&');
1314 /* Substitute the login name for the &, upcasing the first character. */
1315 if (q)
1316 {
1317 register unsigned char *r;
1318 Lisp_Object login;
1319
1320 login = Fuser_login_name (make_number (pw->pw_uid));
1321 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1322 bcopy (p, r, q - p);
1323 r[q - p] = 0;
1324 strcat (r, SDATA (login));
1325 r[q - p] = UPCASE (r[q - p]);
1326 strcat (r, q + 1);
1327 full = build_string (r);
1328 }
1329 #endif /* AMPERSAND_FULL_NAME */
1330
1331 return full;
1332 }
1333
1334 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1335 doc: /* Return the name of the machine you are running on, as a string. */)
1336 ()
1337 {
1338 return Vsystem_name;
1339 }
1340
1341 /* For the benefit of callers who don't want to include lisp.h */
1342
1343 char *
1344 get_system_name ()
1345 {
1346 if (STRINGP (Vsystem_name))
1347 return (char *) SDATA (Vsystem_name);
1348 else
1349 return "";
1350 }
1351
1352 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1353 doc: /* Return the process ID of Emacs, as an integer. */)
1354 ()
1355 {
1356 return make_number (getpid ());
1357 }
1358
1359 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1360 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1361 The time is returned as a list of three integers. The first has the
1362 most significant 16 bits of the seconds, while the second has the
1363 least significant 16 bits. The third integer gives the microsecond
1364 count.
1365
1366 The microsecond count is zero on systems that do not provide
1367 resolution finer than a second. */)
1368 ()
1369 {
1370 EMACS_TIME t;
1371 Lisp_Object result[3];
1372
1373 EMACS_GET_TIME (t);
1374 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1375 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1376 XSETINT (result[2], EMACS_USECS (t));
1377
1378 return Flist (3, result);
1379 }
1380
1381 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1382 0, 0, 0,
1383 doc: /* Return the current run time used by Emacs.
1384 The time is returned as a list of three integers. The first has the
1385 most significant 16 bits of the seconds, while the second has the
1386 least significant 16 bits. The third integer gives the microsecond
1387 count.
1388
1389 On systems that can't determine the run time, get-internal-run-time
1390 does the same thing as current-time. The microsecond count is zero on
1391 systems that do not provide resolution finer than a second. */)
1392 ()
1393 {
1394 #ifdef HAVE_GETRUSAGE
1395 struct rusage usage;
1396 Lisp_Object result[3];
1397 int secs, usecs;
1398
1399 if (getrusage (RUSAGE_SELF, &usage) < 0)
1400 /* This shouldn't happen. What action is appropriate? */
1401 Fsignal (Qerror, Qnil);
1402
1403 /* Sum up user time and system time. */
1404 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1405 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1406 if (usecs >= 1000000)
1407 {
1408 usecs -= 1000000;
1409 secs++;
1410 }
1411
1412 XSETINT (result[0], (secs >> 16) & 0xffff);
1413 XSETINT (result[1], (secs >> 0) & 0xffff);
1414 XSETINT (result[2], usecs);
1415
1416 return Flist (3, result);
1417 #else
1418 return Fcurrent_time ();
1419 #endif
1420 }
1421 \f
1422
1423 int
1424 lisp_time_argument (specified_time, result, usec)
1425 Lisp_Object specified_time;
1426 time_t *result;
1427 int *usec;
1428 {
1429 if (NILP (specified_time))
1430 {
1431 if (usec)
1432 {
1433 EMACS_TIME t;
1434
1435 EMACS_GET_TIME (t);
1436 *usec = EMACS_USECS (t);
1437 *result = EMACS_SECS (t);
1438 return 1;
1439 }
1440 else
1441 return time (result) != -1;
1442 }
1443 else
1444 {
1445 Lisp_Object high, low;
1446 high = Fcar (specified_time);
1447 CHECK_NUMBER (high);
1448 low = Fcdr (specified_time);
1449 if (CONSP (low))
1450 {
1451 if (usec)
1452 {
1453 Lisp_Object usec_l = Fcdr (low);
1454 if (CONSP (usec_l))
1455 usec_l = Fcar (usec_l);
1456 if (NILP (usec_l))
1457 *usec = 0;
1458 else
1459 {
1460 CHECK_NUMBER (usec_l);
1461 *usec = XINT (usec_l);
1462 }
1463 }
1464 low = Fcar (low);
1465 }
1466 else if (usec)
1467 *usec = 0;
1468 CHECK_NUMBER (low);
1469 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1470 return *result >> 16 == XINT (high);
1471 }
1472 }
1473
1474 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1475 doc: /* Return the current time, as a float number of seconds since the epoch.
1476 If SPECIFIED-TIME is given, it is the time to convert to float
1477 instead of the current time. The argument should have the form
1478 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1479 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1480 have the form (HIGH . LOW), but this is considered obsolete.
1481
1482 WARNING: Since the result is floating point, it may not be exact.
1483 Do not use this function if precise time stamps are required. */)
1484 (specified_time)
1485 Lisp_Object specified_time;
1486 {
1487 time_t sec;
1488 int usec;
1489
1490 if (! lisp_time_argument (specified_time, &sec, &usec))
1491 error ("Invalid time specification");
1492
1493 return make_float ((sec * 1e6 + usec) / 1e6);
1494 }
1495
1496 /* Write information into buffer S of size MAXSIZE, according to the
1497 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1498 Default to Universal Time if UT is nonzero, local time otherwise.
1499 Return the number of bytes written, not including the terminating
1500 '\0'. If S is NULL, nothing will be written anywhere; so to
1501 determine how many bytes would be written, use NULL for S and
1502 ((size_t) -1) for MAXSIZE.
1503
1504 This function behaves like emacs_strftimeu, except it allows null
1505 bytes in FORMAT. */
1506 static size_t
1507 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1508 char *s;
1509 size_t maxsize;
1510 const char *format;
1511 size_t format_len;
1512 const struct tm *tp;
1513 int ut;
1514 {
1515 size_t total = 0;
1516
1517 /* Loop through all the null-terminated strings in the format
1518 argument. Normally there's just one null-terminated string, but
1519 there can be arbitrarily many, concatenated together, if the
1520 format contains '\0' bytes. emacs_strftimeu stops at the first
1521 '\0' byte so we must invoke it separately for each such string. */
1522 for (;;)
1523 {
1524 size_t len;
1525 size_t result;
1526
1527 if (s)
1528 s[0] = '\1';
1529
1530 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1531
1532 if (s)
1533 {
1534 if (result == 0 && s[0] != '\0')
1535 return 0;
1536 s += result + 1;
1537 }
1538
1539 maxsize -= result + 1;
1540 total += result;
1541 len = strlen (format);
1542 if (len == format_len)
1543 return total;
1544 total++;
1545 format += len + 1;
1546 format_len -= len + 1;
1547 }
1548 }
1549
1550 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1551 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1552 TIME is specified as (HIGH LOW . IGNORED), as returned by
1553 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1554 is also still accepted.
1555 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1556 as Universal Time; nil means describe TIME in the local time zone.
1557 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1558 by text that describes the specified date and time in TIME:
1559
1560 %Y is the year, %y within the century, %C the century.
1561 %G is the year corresponding to the ISO week, %g within the century.
1562 %m is the numeric month.
1563 %b and %h are the locale's abbreviated month name, %B the full name.
1564 %d is the day of the month, zero-padded, %e is blank-padded.
1565 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1566 %a is the locale's abbreviated name of the day of week, %A the full name.
1567 %U is the week number starting on Sunday, %W starting on Monday,
1568 %V according to ISO 8601.
1569 %j is the day of the year.
1570
1571 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1572 only blank-padded, %l is like %I blank-padded.
1573 %p is the locale's equivalent of either AM or PM.
1574 %M is the minute.
1575 %S is the second.
1576 %Z is the time zone name, %z is the numeric form.
1577 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1578
1579 %c is the locale's date and time format.
1580 %x is the locale's "preferred" date format.
1581 %D is like "%m/%d/%y".
1582
1583 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1584 %X is the locale's "preferred" time format.
1585
1586 Finally, %n is a newline, %t is a tab, %% is a literal %.
1587
1588 Certain flags and modifiers are available with some format controls.
1589 The flags are `_', `-', `^' and `#'. For certain characters X,
1590 %_X is like %X, but padded with blanks; %-X is like %X,
1591 but without padding. %^X is like %X, but with all textual
1592 characters up-cased; %#X is like %X, but with letter-case of
1593 all textual characters reversed.
1594 %NX (where N stands for an integer) is like %X,
1595 but takes up at least N (a number) positions.
1596 The modifiers are `E' and `O'. For certain characters X,
1597 %EX is a locale's alternative version of %X;
1598 %OX is like %X, but uses the locale's number symbols.
1599
1600 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1601 (format_string, time, universal)
1602 Lisp_Object format_string, time, universal;
1603 {
1604 time_t value;
1605 int size;
1606 struct tm *tm;
1607 int ut = ! NILP (universal);
1608
1609 CHECK_STRING (format_string);
1610
1611 if (! lisp_time_argument (time, &value, NULL))
1612 error ("Invalid time specification");
1613
1614 format_string = code_convert_string_norecord (format_string,
1615 Vlocale_coding_system, 1);
1616
1617 /* This is probably enough. */
1618 size = SBYTES (format_string) * 6 + 50;
1619
1620 tm = ut ? gmtime (&value) : localtime (&value);
1621 if (! tm)
1622 error ("Specified time is not representable");
1623
1624 synchronize_system_time_locale ();
1625
1626 while (1)
1627 {
1628 char *buf = (char *) alloca (size + 1);
1629 int result;
1630
1631 buf[0] = '\1';
1632 result = emacs_memftimeu (buf, size, SDATA (format_string),
1633 SBYTES (format_string),
1634 tm, ut);
1635 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1636 return code_convert_string_norecord (make_string (buf, result),
1637 Vlocale_coding_system, 0);
1638
1639 /* If buffer was too small, make it bigger and try again. */
1640 result = emacs_memftimeu (NULL, (size_t) -1,
1641 SDATA (format_string),
1642 SBYTES (format_string),
1643 tm, ut);
1644 size = result + 1;
1645 }
1646 }
1647
1648 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1649 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1650 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1651 as from `current-time' and `file-attributes', or `nil' to use the
1652 current time. The obsolete form (HIGH . LOW) is also still accepted.
1653 The list has the following nine members: SEC is an integer between 0
1654 and 60; SEC is 60 for a leap second, which only some operating systems
1655 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1656 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1657 integer between 1 and 12. YEAR is an integer indicating the
1658 four-digit year. DOW is the day of week, an integer between 0 and 6,
1659 where 0 is Sunday. DST is t if daylight savings time is effect,
1660 otherwise nil. ZONE is an integer indicating the number of seconds
1661 east of Greenwich. (Note that Common Lisp has different meanings for
1662 DOW and ZONE.) */)
1663 (specified_time)
1664 Lisp_Object specified_time;
1665 {
1666 time_t time_spec;
1667 struct tm save_tm;
1668 struct tm *decoded_time;
1669 Lisp_Object list_args[9];
1670
1671 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1672 error ("Invalid time specification");
1673
1674 decoded_time = localtime (&time_spec);
1675 if (! decoded_time)
1676 error ("Specified time is not representable");
1677 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1678 XSETFASTINT (list_args[1], decoded_time->tm_min);
1679 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1680 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1681 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1682 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1683 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1684 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1685
1686 /* Make a copy, in case gmtime modifies the struct. */
1687 save_tm = *decoded_time;
1688 decoded_time = gmtime (&time_spec);
1689 if (decoded_time == 0)
1690 list_args[8] = Qnil;
1691 else
1692 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1693 return Flist (9, list_args);
1694 }
1695
1696 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1697 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1698 This is the reverse operation of `decode-time', which see.
1699 ZONE defaults to the current time zone rule. This can
1700 be a string or t (as from `set-time-zone-rule'), or it can be a list
1701 \(as from `current-time-zone') or an integer (as from `decode-time')
1702 applied without consideration for daylight savings time.
1703
1704 You can pass more than 7 arguments; then the first six arguments
1705 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1706 The intervening arguments are ignored.
1707 This feature lets (apply 'encode-time (decode-time ...)) work.
1708
1709 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1710 for example, a DAY of 0 means the day preceding the given month.
1711 Year numbers less than 100 are treated just like other year numbers.
1712 If you want them to stand for years in this century, you must do that yourself.
1713
1714 Years before 1970 are not guaranteed to work. On some systems,
1715 year values as low as 1901 do work.
1716
1717 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1718 (nargs, args)
1719 int nargs;
1720 register Lisp_Object *args;
1721 {
1722 time_t time;
1723 struct tm tm;
1724 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1725
1726 CHECK_NUMBER (args[0]); /* second */
1727 CHECK_NUMBER (args[1]); /* minute */
1728 CHECK_NUMBER (args[2]); /* hour */
1729 CHECK_NUMBER (args[3]); /* day */
1730 CHECK_NUMBER (args[4]); /* month */
1731 CHECK_NUMBER (args[5]); /* year */
1732
1733 tm.tm_sec = XINT (args[0]);
1734 tm.tm_min = XINT (args[1]);
1735 tm.tm_hour = XINT (args[2]);
1736 tm.tm_mday = XINT (args[3]);
1737 tm.tm_mon = XINT (args[4]) - 1;
1738 tm.tm_year = XINT (args[5]) - 1900;
1739 tm.tm_isdst = -1;
1740
1741 if (CONSP (zone))
1742 zone = Fcar (zone);
1743 if (NILP (zone))
1744 time = mktime (&tm);
1745 else
1746 {
1747 char tzbuf[100];
1748 char *tzstring;
1749 char **oldenv = environ, **newenv;
1750
1751 if (EQ (zone, Qt))
1752 tzstring = "UTC0";
1753 else if (STRINGP (zone))
1754 tzstring = (char *) SDATA (zone);
1755 else if (INTEGERP (zone))
1756 {
1757 int abszone = abs (XINT (zone));
1758 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1759 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1760 tzstring = tzbuf;
1761 }
1762 else
1763 error ("Invalid time zone specification");
1764
1765 /* Set TZ before calling mktime; merely adjusting mktime's returned
1766 value doesn't suffice, since that would mishandle leap seconds. */
1767 set_time_zone_rule (tzstring);
1768
1769 time = mktime (&tm);
1770
1771 /* Restore TZ to previous value. */
1772 newenv = environ;
1773 environ = oldenv;
1774 xfree (newenv);
1775 #ifdef LOCALTIME_CACHE
1776 tzset ();
1777 #endif
1778 }
1779
1780 if (time == (time_t) -1)
1781 error ("Specified time is not representable");
1782
1783 return make_time (time);
1784 }
1785
1786 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1787 doc: /* Return the current time, as a human-readable string.
1788 Programs can use this function to decode a time,
1789 since the number of columns in each field is fixed.
1790 The format is `Sun Sep 16 01:03:52 1973'.
1791 However, see also the functions `decode-time' and `format-time-string'
1792 which provide a much more powerful and general facility.
1793
1794 If SPECIFIED-TIME is given, it is a time to format instead of the
1795 current time. The argument should have the form (HIGH LOW . IGNORED).
1796 Thus, you can use times obtained from `current-time' and from
1797 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1798 but this is considered obsolete. */)
1799 (specified_time)
1800 Lisp_Object specified_time;
1801 {
1802 time_t value;
1803 char buf[30];
1804 register char *tem;
1805
1806 if (! lisp_time_argument (specified_time, &value, NULL))
1807 value = -1;
1808 tem = (char *) ctime (&value);
1809
1810 strncpy (buf, tem, 24);
1811 buf[24] = 0;
1812
1813 return build_string (buf);
1814 }
1815
1816 #define TM_YEAR_BASE 1900
1817
1818 /* Yield A - B, measured in seconds.
1819 This function is copied from the GNU C Library. */
1820 static int
1821 tm_diff (a, b)
1822 struct tm *a, *b;
1823 {
1824 /* Compute intervening leap days correctly even if year is negative.
1825 Take care to avoid int overflow in leap day calculations,
1826 but it's OK to assume that A and B are close to each other. */
1827 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1828 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1829 int a100 = a4 / 25 - (a4 % 25 < 0);
1830 int b100 = b4 / 25 - (b4 % 25 < 0);
1831 int a400 = a100 >> 2;
1832 int b400 = b100 >> 2;
1833 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1834 int years = a->tm_year - b->tm_year;
1835 int days = (365 * years + intervening_leap_days
1836 + (a->tm_yday - b->tm_yday));
1837 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1838 + (a->tm_min - b->tm_min))
1839 + (a->tm_sec - b->tm_sec));
1840 }
1841
1842 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1843 doc: /* Return the offset and name for the local time zone.
1844 This returns a list of the form (OFFSET NAME).
1845 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1846 A negative value means west of Greenwich.
1847 NAME is a string giving the name of the time zone.
1848 If SPECIFIED-TIME is given, the time zone offset is determined from it
1849 instead of using the current time. The argument should have the form
1850 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1851 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1852 have the form (HIGH . LOW), but this is considered obsolete.
1853
1854 Some operating systems cannot provide all this information to Emacs;
1855 in this case, `current-time-zone' returns a list containing nil for
1856 the data it can't find. */)
1857 (specified_time)
1858 Lisp_Object specified_time;
1859 {
1860 time_t value;
1861 struct tm *t;
1862 struct tm gmt;
1863
1864 if (lisp_time_argument (specified_time, &value, NULL)
1865 && (t = gmtime (&value)) != 0
1866 && (gmt = *t, t = localtime (&value)) != 0)
1867 {
1868 int offset = tm_diff (t, &gmt);
1869 char *s = 0;
1870 char buf[6];
1871 #ifdef HAVE_TM_ZONE
1872 if (t->tm_zone)
1873 s = (char *)t->tm_zone;
1874 #else /* not HAVE_TM_ZONE */
1875 #ifdef HAVE_TZNAME
1876 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1877 s = tzname[t->tm_isdst];
1878 #endif
1879 #endif /* not HAVE_TM_ZONE */
1880
1881 #if defined HAVE_TM_ZONE || defined HAVE_TZNAME
1882 if (s)
1883 {
1884 /* On Japanese w32, we can get a Japanese string as time
1885 zone name. Don't accept that. */
1886 char *p;
1887 for (p = s; *p && (isalnum ((unsigned char)*p) || *p == ' '); ++p)
1888 ;
1889 if (p == s || *p)
1890 s = NULL;
1891 }
1892 #endif
1893
1894 if (!s)
1895 {
1896 /* No local time zone name is available; use "+-NNNN" instead. */
1897 int am = (offset < 0 ? -offset : offset) / 60;
1898 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1899 s = buf;
1900 }
1901 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1902 }
1903 else
1904 return Fmake_list (make_number (2), Qnil);
1905 }
1906
1907 /* This holds the value of `environ' produced by the previous
1908 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1909 has never been called. */
1910 static char **environbuf;
1911
1912 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1913 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
1914 If TZ is nil, use implementation-defined default time zone information.
1915 If TZ is t, use Universal Time. */)
1916 (tz)
1917 Lisp_Object tz;
1918 {
1919 char *tzstring;
1920
1921 if (NILP (tz))
1922 tzstring = 0;
1923 else if (EQ (tz, Qt))
1924 tzstring = "UTC0";
1925 else
1926 {
1927 CHECK_STRING (tz);
1928 tzstring = (char *) SDATA (tz);
1929 }
1930
1931 set_time_zone_rule (tzstring);
1932 if (environbuf)
1933 free (environbuf);
1934 environbuf = environ;
1935
1936 return Qnil;
1937 }
1938
1939 #ifdef LOCALTIME_CACHE
1940
1941 /* These two values are known to load tz files in buggy implementations,
1942 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1943 Their values shouldn't matter in non-buggy implementations.
1944 We don't use string literals for these strings,
1945 since if a string in the environment is in readonly
1946 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1947 See Sun bugs 1113095 and 1114114, ``Timezone routines
1948 improperly modify environment''. */
1949
1950 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1951 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1952
1953 #endif
1954
1955 /* Set the local time zone rule to TZSTRING.
1956 This allocates memory into `environ', which it is the caller's
1957 responsibility to free. */
1958
1959 void
1960 set_time_zone_rule (tzstring)
1961 char *tzstring;
1962 {
1963 int envptrs;
1964 char **from, **to, **newenv;
1965
1966 /* Make the ENVIRON vector longer with room for TZSTRING. */
1967 for (from = environ; *from; from++)
1968 continue;
1969 envptrs = from - environ + 2;
1970 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1971 + (tzstring ? strlen (tzstring) + 4 : 0));
1972
1973 /* Add TZSTRING to the end of environ, as a value for TZ. */
1974 if (tzstring)
1975 {
1976 char *t = (char *) (to + envptrs);
1977 strcpy (t, "TZ=");
1978 strcat (t, tzstring);
1979 *to++ = t;
1980 }
1981
1982 /* Copy the old environ vector elements into NEWENV,
1983 but don't copy the TZ variable.
1984 So we have only one definition of TZ, which came from TZSTRING. */
1985 for (from = environ; *from; from++)
1986 if (strncmp (*from, "TZ=", 3) != 0)
1987 *to++ = *from;
1988 *to = 0;
1989
1990 environ = newenv;
1991
1992 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1993 the TZ variable is stored. If we do not have a TZSTRING,
1994 TO points to the vector slot which has the terminating null. */
1995
1996 #ifdef LOCALTIME_CACHE
1997 {
1998 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1999 "US/Pacific" that loads a tz file, then changes to a value like
2000 "XXX0" that does not load a tz file, and then changes back to
2001 its original value, the last change is (incorrectly) ignored.
2002 Also, if TZ changes twice in succession to values that do
2003 not load a tz file, tzset can dump core (see Sun bug#1225179).
2004 The following code works around these bugs. */
2005
2006 if (tzstring)
2007 {
2008 /* Temporarily set TZ to a value that loads a tz file
2009 and that differs from tzstring. */
2010 char *tz = *newenv;
2011 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2012 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2013 tzset ();
2014 *newenv = tz;
2015 }
2016 else
2017 {
2018 /* The implied tzstring is unknown, so temporarily set TZ to
2019 two different values that each load a tz file. */
2020 *to = set_time_zone_rule_tz1;
2021 to[1] = 0;
2022 tzset ();
2023 *to = set_time_zone_rule_tz2;
2024 tzset ();
2025 *to = 0;
2026 }
2027
2028 /* Now TZ has the desired value, and tzset can be invoked safely. */
2029 }
2030
2031 tzset ();
2032 #endif
2033 }
2034 \f
2035 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2036 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2037 type of object is Lisp_String). INHERIT is passed to
2038 INSERT_FROM_STRING_FUNC as the last argument. */
2039
2040 static void
2041 general_insert_function (insert_func, insert_from_string_func,
2042 inherit, nargs, args)
2043 void (*insert_func) P_ ((const unsigned char *, int));
2044 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
2045 int inherit, nargs;
2046 register Lisp_Object *args;
2047 {
2048 register int argnum;
2049 register Lisp_Object val;
2050
2051 for (argnum = 0; argnum < nargs; argnum++)
2052 {
2053 val = args[argnum];
2054 retry:
2055 if (INTEGERP (val))
2056 {
2057 unsigned char str[MAX_MULTIBYTE_LENGTH];
2058 int len;
2059
2060 if (!NILP (current_buffer->enable_multibyte_characters))
2061 len = CHAR_STRING (XFASTINT (val), str);
2062 else
2063 {
2064 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
2065 ? XINT (val)
2066 : multibyte_char_to_unibyte (XINT (val), Qnil));
2067 len = 1;
2068 }
2069 (*insert_func) (str, len);
2070 }
2071 else if (STRINGP (val))
2072 {
2073 (*insert_from_string_func) (val, 0, 0,
2074 SCHARS (val),
2075 SBYTES (val),
2076 inherit);
2077 }
2078 else
2079 {
2080 val = wrong_type_argument (Qchar_or_string_p, val);
2081 goto retry;
2082 }
2083 }
2084 }
2085
2086 void
2087 insert1 (arg)
2088 Lisp_Object arg;
2089 {
2090 Finsert (1, &arg);
2091 }
2092
2093
2094 /* Callers passing one argument to Finsert need not gcpro the
2095 argument "array", since the only element of the array will
2096 not be used after calling insert or insert_from_string, so
2097 we don't care if it gets trashed. */
2098
2099 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2100 doc: /* Insert the arguments, either strings or characters, at point.
2101 Point and before-insertion markers move forward to end up
2102 after the inserted text.
2103 Any other markers at the point of insertion remain before the text.
2104
2105 If the current buffer is multibyte, unibyte strings are converted
2106 to multibyte for insertion (see `string-make-multibyte').
2107 If the current buffer is unibyte, multibyte strings are converted
2108 to unibyte for insertion (see `string-make-unibyte').
2109
2110 When operating on binary data, it may be necessary to preserve the
2111 original bytes of a unibyte string when inserting it into a multibyte
2112 buffer; to accomplish this, apply `string-as-multibyte' to the string
2113 and insert the result.
2114
2115 usage: (insert &rest ARGS) */)
2116 (nargs, args)
2117 int nargs;
2118 register Lisp_Object *args;
2119 {
2120 general_insert_function (insert, insert_from_string, 0, nargs, args);
2121 return Qnil;
2122 }
2123
2124 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2125 0, MANY, 0,
2126 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2127 Point and before-insertion markers move forward to end up
2128 after the inserted text.
2129 Any other markers at the point of insertion remain before the text.
2130
2131 If the current buffer is multibyte, unibyte strings are converted
2132 to multibyte for insertion (see `unibyte-char-to-multibyte').
2133 If the current buffer is unibyte, multibyte strings are converted
2134 to unibyte for insertion.
2135
2136 usage: (insert-and-inherit &rest ARGS) */)
2137 (nargs, args)
2138 int nargs;
2139 register Lisp_Object *args;
2140 {
2141 general_insert_function (insert_and_inherit, insert_from_string, 1,
2142 nargs, args);
2143 return Qnil;
2144 }
2145
2146 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2147 doc: /* Insert strings or characters at point, relocating markers after the text.
2148 Point and markers move forward to end up after the inserted text.
2149
2150 If the current buffer is multibyte, unibyte strings are converted
2151 to multibyte for insertion (see `unibyte-char-to-multibyte').
2152 If the current buffer is unibyte, multibyte strings are converted
2153 to unibyte for insertion.
2154
2155 usage: (insert-before-markers &rest ARGS) */)
2156 (nargs, args)
2157 int nargs;
2158 register Lisp_Object *args;
2159 {
2160 general_insert_function (insert_before_markers,
2161 insert_from_string_before_markers, 0,
2162 nargs, args);
2163 return Qnil;
2164 }
2165
2166 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2167 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2168 doc: /* Insert text at point, relocating markers and inheriting properties.
2169 Point and markers move forward to end up after the inserted text.
2170
2171 If the current buffer is multibyte, unibyte strings are converted
2172 to multibyte for insertion (see `unibyte-char-to-multibyte').
2173 If the current buffer is unibyte, multibyte strings are converted
2174 to unibyte for insertion.
2175
2176 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2177 (nargs, args)
2178 int nargs;
2179 register Lisp_Object *args;
2180 {
2181 general_insert_function (insert_before_markers_and_inherit,
2182 insert_from_string_before_markers, 1,
2183 nargs, args);
2184 return Qnil;
2185 }
2186 \f
2187 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2188 doc: /* Insert COUNT (second arg) copies of CHARACTER (first arg).
2189 Both arguments are required.
2190 Point, and before-insertion markers, are relocated as in the function `insert'.
2191 The optional third arg INHERIT, if non-nil, says to inherit text properties
2192 from adjoining text, if those properties are sticky. */)
2193 (character, count, inherit)
2194 Lisp_Object character, count, inherit;
2195 {
2196 register unsigned char *string;
2197 register int strlen;
2198 register int i, n;
2199 int len;
2200 unsigned char str[MAX_MULTIBYTE_LENGTH];
2201
2202 CHECK_NUMBER (character);
2203 CHECK_NUMBER (count);
2204
2205 if (!NILP (current_buffer->enable_multibyte_characters))
2206 len = CHAR_STRING (XFASTINT (character), str);
2207 else
2208 str[0] = XFASTINT (character), len = 1;
2209 n = XINT (count) * len;
2210 if (n <= 0)
2211 return Qnil;
2212 strlen = min (n, 256 * len);
2213 string = (unsigned char *) alloca (strlen);
2214 for (i = 0; i < strlen; i++)
2215 string[i] = str[i % len];
2216 while (n >= strlen)
2217 {
2218 QUIT;
2219 if (!NILP (inherit))
2220 insert_and_inherit (string, strlen);
2221 else
2222 insert (string, strlen);
2223 n -= strlen;
2224 }
2225 if (n > 0)
2226 {
2227 if (!NILP (inherit))
2228 insert_and_inherit (string, n);
2229 else
2230 insert (string, n);
2231 }
2232 return Qnil;
2233 }
2234
2235 \f
2236 /* Making strings from buffer contents. */
2237
2238 /* Return a Lisp_String containing the text of the current buffer from
2239 START to END. If text properties are in use and the current buffer
2240 has properties in the range specified, the resulting string will also
2241 have them, if PROPS is nonzero.
2242
2243 We don't want to use plain old make_string here, because it calls
2244 make_uninit_string, which can cause the buffer arena to be
2245 compacted. make_string has no way of knowing that the data has
2246 been moved, and thus copies the wrong data into the string. This
2247 doesn't effect most of the other users of make_string, so it should
2248 be left as is. But we should use this function when conjuring
2249 buffer substrings. */
2250
2251 Lisp_Object
2252 make_buffer_string (start, end, props)
2253 int start, end;
2254 int props;
2255 {
2256 int start_byte = CHAR_TO_BYTE (start);
2257 int end_byte = CHAR_TO_BYTE (end);
2258
2259 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2260 }
2261
2262 /* Return a Lisp_String containing the text of the current buffer from
2263 START / START_BYTE to END / END_BYTE.
2264
2265 If text properties are in use and the current buffer
2266 has properties in the range specified, the resulting string will also
2267 have them, if PROPS is nonzero.
2268
2269 We don't want to use plain old make_string here, because it calls
2270 make_uninit_string, which can cause the buffer arena to be
2271 compacted. make_string has no way of knowing that the data has
2272 been moved, and thus copies the wrong data into the string. This
2273 doesn't effect most of the other users of make_string, so it should
2274 be left as is. But we should use this function when conjuring
2275 buffer substrings. */
2276
2277 Lisp_Object
2278 make_buffer_string_both (start, start_byte, end, end_byte, props)
2279 int start, start_byte, end, end_byte;
2280 int props;
2281 {
2282 Lisp_Object result, tem, tem1;
2283
2284 if (start < GPT && GPT < end)
2285 move_gap (start);
2286
2287 if (! NILP (current_buffer->enable_multibyte_characters))
2288 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2289 else
2290 result = make_uninit_string (end - start);
2291 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
2292 end_byte - start_byte);
2293
2294 /* If desired, update and copy the text properties. */
2295 if (props)
2296 {
2297 update_buffer_properties (start, end);
2298
2299 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2300 tem1 = Ftext_properties_at (make_number (start), Qnil);
2301
2302 if (XINT (tem) != end || !NILP (tem1))
2303 copy_intervals_to_string (result, current_buffer, start,
2304 end - start);
2305 }
2306
2307 return result;
2308 }
2309
2310 /* Call Vbuffer_access_fontify_functions for the range START ... END
2311 in the current buffer, if necessary. */
2312
2313 static void
2314 update_buffer_properties (start, end)
2315 int start, end;
2316 {
2317 /* If this buffer has some access functions,
2318 call them, specifying the range of the buffer being accessed. */
2319 if (!NILP (Vbuffer_access_fontify_functions))
2320 {
2321 Lisp_Object args[3];
2322 Lisp_Object tem;
2323
2324 args[0] = Qbuffer_access_fontify_functions;
2325 XSETINT (args[1], start);
2326 XSETINT (args[2], end);
2327
2328 /* But don't call them if we can tell that the work
2329 has already been done. */
2330 if (!NILP (Vbuffer_access_fontified_property))
2331 {
2332 tem = Ftext_property_any (args[1], args[2],
2333 Vbuffer_access_fontified_property,
2334 Qnil, Qnil);
2335 if (! NILP (tem))
2336 Frun_hook_with_args (3, args);
2337 }
2338 else
2339 Frun_hook_with_args (3, args);
2340 }
2341 }
2342
2343 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2344 doc: /* Return the contents of part of the current buffer as a string.
2345 The two arguments START and END are character positions;
2346 they can be in either order.
2347 The string returned is multibyte if the buffer is multibyte.
2348
2349 This function copies the text properties of that part of the buffer
2350 into the result string; if you don't want the text properties,
2351 use `buffer-substring-no-properties' instead. */)
2352 (start, end)
2353 Lisp_Object start, end;
2354 {
2355 register int b, e;
2356
2357 validate_region (&start, &end);
2358 b = XINT (start);
2359 e = XINT (end);
2360
2361 return make_buffer_string (b, e, 1);
2362 }
2363
2364 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2365 Sbuffer_substring_no_properties, 2, 2, 0,
2366 doc: /* Return the characters of part of the buffer, without the text properties.
2367 The two arguments START and END are character positions;
2368 they can be in either order. */)
2369 (start, end)
2370 Lisp_Object start, end;
2371 {
2372 register int b, e;
2373
2374 validate_region (&start, &end);
2375 b = XINT (start);
2376 e = XINT (end);
2377
2378 return make_buffer_string (b, e, 0);
2379 }
2380
2381 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2382 doc: /* Return the contents of the current buffer as a string.
2383 If narrowing is in effect, this function returns only the visible part
2384 of the buffer. */)
2385 ()
2386 {
2387 return make_buffer_string (BEGV, ZV, 1);
2388 }
2389
2390 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2391 1, 3, 0,
2392 doc: /* Insert before point a substring of the contents of BUFFER.
2393 BUFFER may be a buffer or a buffer name.
2394 Arguments START and END are character positions specifying the substring.
2395 They default to the values of (point-min) and (point-max) in BUFFER. */)
2396 (buffer, start, end)
2397 Lisp_Object buffer, start, end;
2398 {
2399 register int b, e, temp;
2400 register struct buffer *bp, *obuf;
2401 Lisp_Object buf;
2402
2403 buf = Fget_buffer (buffer);
2404 if (NILP (buf))
2405 nsberror (buffer);
2406 bp = XBUFFER (buf);
2407 if (NILP (bp->name))
2408 error ("Selecting deleted buffer");
2409
2410 if (NILP (start))
2411 b = BUF_BEGV (bp);
2412 else
2413 {
2414 CHECK_NUMBER_COERCE_MARKER (start);
2415 b = XINT (start);
2416 }
2417 if (NILP (end))
2418 e = BUF_ZV (bp);
2419 else
2420 {
2421 CHECK_NUMBER_COERCE_MARKER (end);
2422 e = XINT (end);
2423 }
2424
2425 if (b > e)
2426 temp = b, b = e, e = temp;
2427
2428 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2429 args_out_of_range (start, end);
2430
2431 obuf = current_buffer;
2432 set_buffer_internal_1 (bp);
2433 update_buffer_properties (b, e);
2434 set_buffer_internal_1 (obuf);
2435
2436 insert_from_buffer (bp, b, e - b, 0);
2437 return Qnil;
2438 }
2439
2440 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2441 6, 6, 0,
2442 doc: /* Compare two substrings of two buffers; return result as number.
2443 the value is -N if first string is less after N-1 chars,
2444 +N if first string is greater after N-1 chars, or 0 if strings match.
2445 Each substring is represented as three arguments: BUFFER, START and END.
2446 That makes six args in all, three for each substring.
2447
2448 The value of `case-fold-search' in the current buffer
2449 determines whether case is significant or ignored. */)
2450 (buffer1, start1, end1, buffer2, start2, end2)
2451 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2452 {
2453 register int begp1, endp1, begp2, endp2, temp;
2454 register struct buffer *bp1, *bp2;
2455 register Lisp_Object *trt
2456 = (!NILP (current_buffer->case_fold_search)
2457 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2458 int chars = 0;
2459 int i1, i2, i1_byte, i2_byte;
2460
2461 /* Find the first buffer and its substring. */
2462
2463 if (NILP (buffer1))
2464 bp1 = current_buffer;
2465 else
2466 {
2467 Lisp_Object buf1;
2468 buf1 = Fget_buffer (buffer1);
2469 if (NILP (buf1))
2470 nsberror (buffer1);
2471 bp1 = XBUFFER (buf1);
2472 if (NILP (bp1->name))
2473 error ("Selecting deleted buffer");
2474 }
2475
2476 if (NILP (start1))
2477 begp1 = BUF_BEGV (bp1);
2478 else
2479 {
2480 CHECK_NUMBER_COERCE_MARKER (start1);
2481 begp1 = XINT (start1);
2482 }
2483 if (NILP (end1))
2484 endp1 = BUF_ZV (bp1);
2485 else
2486 {
2487 CHECK_NUMBER_COERCE_MARKER (end1);
2488 endp1 = XINT (end1);
2489 }
2490
2491 if (begp1 > endp1)
2492 temp = begp1, begp1 = endp1, endp1 = temp;
2493
2494 if (!(BUF_BEGV (bp1) <= begp1
2495 && begp1 <= endp1
2496 && endp1 <= BUF_ZV (bp1)))
2497 args_out_of_range (start1, end1);
2498
2499 /* Likewise for second substring. */
2500
2501 if (NILP (buffer2))
2502 bp2 = current_buffer;
2503 else
2504 {
2505 Lisp_Object buf2;
2506 buf2 = Fget_buffer (buffer2);
2507 if (NILP (buf2))
2508 nsberror (buffer2);
2509 bp2 = XBUFFER (buf2);
2510 if (NILP (bp2->name))
2511 error ("Selecting deleted buffer");
2512 }
2513
2514 if (NILP (start2))
2515 begp2 = BUF_BEGV (bp2);
2516 else
2517 {
2518 CHECK_NUMBER_COERCE_MARKER (start2);
2519 begp2 = XINT (start2);
2520 }
2521 if (NILP (end2))
2522 endp2 = BUF_ZV (bp2);
2523 else
2524 {
2525 CHECK_NUMBER_COERCE_MARKER (end2);
2526 endp2 = XINT (end2);
2527 }
2528
2529 if (begp2 > endp2)
2530 temp = begp2, begp2 = endp2, endp2 = temp;
2531
2532 if (!(BUF_BEGV (bp2) <= begp2
2533 && begp2 <= endp2
2534 && endp2 <= BUF_ZV (bp2)))
2535 args_out_of_range (start2, end2);
2536
2537 i1 = begp1;
2538 i2 = begp2;
2539 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2540 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2541
2542 while (i1 < endp1 && i2 < endp2)
2543 {
2544 /* When we find a mismatch, we must compare the
2545 characters, not just the bytes. */
2546 int c1, c2;
2547
2548 QUIT;
2549
2550 if (! NILP (bp1->enable_multibyte_characters))
2551 {
2552 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2553 BUF_INC_POS (bp1, i1_byte);
2554 i1++;
2555 }
2556 else
2557 {
2558 c1 = BUF_FETCH_BYTE (bp1, i1);
2559 c1 = unibyte_char_to_multibyte (c1);
2560 i1++;
2561 }
2562
2563 if (! NILP (bp2->enable_multibyte_characters))
2564 {
2565 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2566 BUF_INC_POS (bp2, i2_byte);
2567 i2++;
2568 }
2569 else
2570 {
2571 c2 = BUF_FETCH_BYTE (bp2, i2);
2572 c2 = unibyte_char_to_multibyte (c2);
2573 i2++;
2574 }
2575
2576 if (trt)
2577 {
2578 c1 = XINT (trt[c1]);
2579 c2 = XINT (trt[c2]);
2580 }
2581 if (c1 < c2)
2582 return make_number (- 1 - chars);
2583 if (c1 > c2)
2584 return make_number (chars + 1);
2585
2586 chars++;
2587 }
2588
2589 /* The strings match as far as they go.
2590 If one is shorter, that one is less. */
2591 if (chars < endp1 - begp1)
2592 return make_number (chars + 1);
2593 else if (chars < endp2 - begp2)
2594 return make_number (- chars - 1);
2595
2596 /* Same length too => they are equal. */
2597 return make_number (0);
2598 }
2599 \f
2600 static Lisp_Object
2601 subst_char_in_region_unwind (arg)
2602 Lisp_Object arg;
2603 {
2604 return current_buffer->undo_list = arg;
2605 }
2606
2607 static Lisp_Object
2608 subst_char_in_region_unwind_1 (arg)
2609 Lisp_Object arg;
2610 {
2611 return current_buffer->filename = arg;
2612 }
2613
2614 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2615 Ssubst_char_in_region, 4, 5, 0,
2616 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2617 If optional arg NOUNDO is non-nil, don't record this change for undo
2618 and don't mark the buffer as really changed.
2619 Both characters must have the same length of multi-byte form. */)
2620 (start, end, fromchar, tochar, noundo)
2621 Lisp_Object start, end, fromchar, tochar, noundo;
2622 {
2623 register int pos, pos_byte, stop, i, len, end_byte;
2624 int changed = 0;
2625 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2626 unsigned char *p;
2627 int count = SPECPDL_INDEX ();
2628 #define COMBINING_NO 0
2629 #define COMBINING_BEFORE 1
2630 #define COMBINING_AFTER 2
2631 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2632 int maybe_byte_combining = COMBINING_NO;
2633 int last_changed = 0;
2634 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2635
2636 validate_region (&start, &end);
2637 CHECK_NUMBER (fromchar);
2638 CHECK_NUMBER (tochar);
2639
2640 if (multibyte_p)
2641 {
2642 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2643 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2644 error ("Characters in subst-char-in-region have different byte-lengths");
2645 if (!ASCII_BYTE_P (*tostr))
2646 {
2647 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2648 complete multibyte character, it may be combined with the
2649 after bytes. If it is in the range 0xA0..0xFF, it may be
2650 combined with the before and after bytes. */
2651 if (!CHAR_HEAD_P (*tostr))
2652 maybe_byte_combining = COMBINING_BOTH;
2653 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2654 maybe_byte_combining = COMBINING_AFTER;
2655 }
2656 }
2657 else
2658 {
2659 len = 1;
2660 fromstr[0] = XFASTINT (fromchar);
2661 tostr[0] = XFASTINT (tochar);
2662 }
2663
2664 pos = XINT (start);
2665 pos_byte = CHAR_TO_BYTE (pos);
2666 stop = CHAR_TO_BYTE (XINT (end));
2667 end_byte = stop;
2668
2669 /* If we don't want undo, turn off putting stuff on the list.
2670 That's faster than getting rid of things,
2671 and it prevents even the entry for a first change.
2672 Also inhibit locking the file. */
2673 if (!NILP (noundo))
2674 {
2675 record_unwind_protect (subst_char_in_region_unwind,
2676 current_buffer->undo_list);
2677 current_buffer->undo_list = Qt;
2678 /* Don't do file-locking. */
2679 record_unwind_protect (subst_char_in_region_unwind_1,
2680 current_buffer->filename);
2681 current_buffer->filename = Qnil;
2682 }
2683
2684 if (pos_byte < GPT_BYTE)
2685 stop = min (stop, GPT_BYTE);
2686 while (1)
2687 {
2688 int pos_byte_next = pos_byte;
2689
2690 if (pos_byte >= stop)
2691 {
2692 if (pos_byte >= end_byte) break;
2693 stop = end_byte;
2694 }
2695 p = BYTE_POS_ADDR (pos_byte);
2696 if (multibyte_p)
2697 INC_POS (pos_byte_next);
2698 else
2699 ++pos_byte_next;
2700 if (pos_byte_next - pos_byte == len
2701 && p[0] == fromstr[0]
2702 && (len == 1
2703 || (p[1] == fromstr[1]
2704 && (len == 2 || (p[2] == fromstr[2]
2705 && (len == 3 || p[3] == fromstr[3]))))))
2706 {
2707 if (! changed)
2708 {
2709 changed = pos;
2710 modify_region (current_buffer, changed, XINT (end));
2711
2712 if (! NILP (noundo))
2713 {
2714 if (MODIFF - 1 == SAVE_MODIFF)
2715 SAVE_MODIFF++;
2716 if (MODIFF - 1 == current_buffer->auto_save_modified)
2717 current_buffer->auto_save_modified++;
2718 }
2719 }
2720
2721 /* Take care of the case where the new character
2722 combines with neighboring bytes. */
2723 if (maybe_byte_combining
2724 && (maybe_byte_combining == COMBINING_AFTER
2725 ? (pos_byte_next < Z_BYTE
2726 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2727 : ((pos_byte_next < Z_BYTE
2728 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2729 || (pos_byte > BEG_BYTE
2730 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2731 {
2732 Lisp_Object tem, string;
2733
2734 struct gcpro gcpro1;
2735
2736 tem = current_buffer->undo_list;
2737 GCPRO1 (tem);
2738
2739 /* Make a multibyte string containing this single character. */
2740 string = make_multibyte_string (tostr, 1, len);
2741 /* replace_range is less efficient, because it moves the gap,
2742 but it handles combining correctly. */
2743 replace_range (pos, pos + 1, string,
2744 0, 0, 1);
2745 pos_byte_next = CHAR_TO_BYTE (pos);
2746 if (pos_byte_next > pos_byte)
2747 /* Before combining happened. We should not increment
2748 POS. So, to cancel the later increment of POS,
2749 decrease it now. */
2750 pos--;
2751 else
2752 INC_POS (pos_byte_next);
2753
2754 if (! NILP (noundo))
2755 current_buffer->undo_list = tem;
2756
2757 UNGCPRO;
2758 }
2759 else
2760 {
2761 if (NILP (noundo))
2762 record_change (pos, 1);
2763 for (i = 0; i < len; i++) *p++ = tostr[i];
2764 }
2765 last_changed = pos + 1;
2766 }
2767 pos_byte = pos_byte_next;
2768 pos++;
2769 }
2770
2771 if (changed)
2772 {
2773 signal_after_change (changed,
2774 last_changed - changed, last_changed - changed);
2775 update_compositions (changed, last_changed, CHECK_ALL);
2776 }
2777
2778 unbind_to (count, Qnil);
2779 return Qnil;
2780 }
2781
2782 DEFUN ("translate-region-internal", Ftranslate_region_internal,
2783 Stranslate_region_internal, 3, 3, 0,
2784 doc: /* Internal use only.
2785 From START to END, translate characters according to TABLE.
2786 TABLE is a string; the Nth character in it is the mapping
2787 for the character with code N.
2788 It returns the number of characters changed. */)
2789 (start, end, table)
2790 Lisp_Object start;
2791 Lisp_Object end;
2792 register Lisp_Object table;
2793 {
2794 register unsigned char *tt; /* Trans table. */
2795 register int nc; /* New character. */
2796 int cnt; /* Number of changes made. */
2797 int size; /* Size of translate table. */
2798 int pos, pos_byte, end_pos;
2799 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2800 int string_multibyte;
2801
2802 validate_region (&start, &end);
2803 if (CHAR_TABLE_P (table))
2804 {
2805 size = MAX_CHAR;
2806 tt = NULL;
2807 }
2808 else
2809 {
2810 CHECK_STRING (table);
2811
2812 if (! multibyte && (SCHARS (table) < SBYTES (table)))
2813 table = string_make_unibyte (table);
2814 string_multibyte = SCHARS (table) < SBYTES (table);
2815 size = SCHARS (table);
2816 tt = SDATA (table);
2817 }
2818
2819 pos = XINT (start);
2820 pos_byte = CHAR_TO_BYTE (pos);
2821 end_pos = XINT (end);
2822 modify_region (current_buffer, pos, XINT (end));
2823
2824 cnt = 0;
2825 for (; pos < end_pos; )
2826 {
2827 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2828 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
2829 int len, str_len;
2830 int oc;
2831
2832 if (multibyte)
2833 oc = STRING_CHAR_AND_LENGTH (p, MAX_MULTIBYTE_LENGTH, len);
2834 else
2835 oc = *p, len = 1;
2836 if (oc < size)
2837 {
2838 if (tt)
2839 {
2840 if (string_multibyte)
2841 {
2842 str = tt + string_char_to_byte (table, oc);
2843 nc = STRING_CHAR_AND_LENGTH (str, MAX_MULTIBYTE_LENGTH,
2844 str_len);
2845 }
2846 else
2847 {
2848 nc = tt[oc];
2849 if (! ASCII_BYTE_P (nc) && multibyte)
2850 {
2851 str_len = CHAR_STRING (nc, buf);
2852 str = buf;
2853 }
2854 else
2855 {
2856 str_len = 1;
2857 str = tt + oc;
2858 }
2859 }
2860 }
2861 else
2862 {
2863 Lisp_Object val;
2864 int c;
2865
2866 nc = oc;
2867 val = CHAR_TABLE_REF (table, oc);
2868 if (INTEGERP (val)
2869 && (c = XINT (val), CHAR_VALID_P (c, 0)))
2870 {
2871 nc = c;
2872 str_len = CHAR_STRING (nc, buf);
2873 str = buf;
2874 }
2875 }
2876
2877 if (nc != oc)
2878 {
2879 if (len != str_len)
2880 {
2881 Lisp_Object string;
2882
2883 /* This is less efficient, because it moves the gap,
2884 but it should multibyte characters correctly. */
2885 string = make_multibyte_string (str, 1, str_len);
2886 replace_range (pos, pos + 1, string, 1, 0, 1);
2887 len = str_len;
2888 }
2889 else
2890 {
2891 record_change (pos, 1);
2892 while (str_len-- > 0)
2893 *p++ = *str++;
2894 signal_after_change (pos, 1, 1);
2895 update_compositions (pos, pos + 1, CHECK_BORDER);
2896 }
2897 ++cnt;
2898 }
2899 }
2900 pos_byte += len;
2901 pos++;
2902 }
2903
2904 return make_number (cnt);
2905 }
2906
2907 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2908 doc: /* Delete the text between point and mark.
2909
2910 When called from a program, expects two arguments,
2911 positions (integers or markers) specifying the stretch to be deleted. */)
2912 (start, end)
2913 Lisp_Object start, end;
2914 {
2915 validate_region (&start, &end);
2916 del_range (XINT (start), XINT (end));
2917 return Qnil;
2918 }
2919
2920 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2921 Sdelete_and_extract_region, 2, 2, 0,
2922 doc: /* Delete the text between START and END and return it. */)
2923 (start, end)
2924 Lisp_Object start, end;
2925 {
2926 validate_region (&start, &end);
2927 if (XINT (start) == XINT (end))
2928 return build_string ("");
2929 return del_range_1 (XINT (start), XINT (end), 1, 1);
2930 }
2931 \f
2932 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2933 doc: /* Remove restrictions (narrowing) from current buffer.
2934 This allows the buffer's full text to be seen and edited. */)
2935 ()
2936 {
2937 if (BEG != BEGV || Z != ZV)
2938 current_buffer->clip_changed = 1;
2939 BEGV = BEG;
2940 BEGV_BYTE = BEG_BYTE;
2941 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2942 /* Changing the buffer bounds invalidates any recorded current column. */
2943 invalidate_current_column ();
2944 return Qnil;
2945 }
2946
2947 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2948 doc: /* Restrict editing in this buffer to the current region.
2949 The rest of the text becomes temporarily invisible and untouchable
2950 but is not deleted; if you save the buffer in a file, the invisible
2951 text is included in the file. \\[widen] makes all visible again.
2952 See also `save-restriction'.
2953
2954 When calling from a program, pass two arguments; positions (integers
2955 or markers) bounding the text that should remain visible. */)
2956 (start, end)
2957 register Lisp_Object start, end;
2958 {
2959 CHECK_NUMBER_COERCE_MARKER (start);
2960 CHECK_NUMBER_COERCE_MARKER (end);
2961
2962 if (XINT (start) > XINT (end))
2963 {
2964 Lisp_Object tem;
2965 tem = start; start = end; end = tem;
2966 }
2967
2968 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2969 args_out_of_range (start, end);
2970
2971 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2972 current_buffer->clip_changed = 1;
2973
2974 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2975 SET_BUF_ZV (current_buffer, XFASTINT (end));
2976 if (PT < XFASTINT (start))
2977 SET_PT (XFASTINT (start));
2978 if (PT > XFASTINT (end))
2979 SET_PT (XFASTINT (end));
2980 /* Changing the buffer bounds invalidates any recorded current column. */
2981 invalidate_current_column ();
2982 return Qnil;
2983 }
2984
2985 Lisp_Object
2986 save_restriction_save ()
2987 {
2988 if (BEGV == BEG && ZV == Z)
2989 /* The common case that the buffer isn't narrowed.
2990 We return just the buffer object, which save_restriction_restore
2991 recognizes as meaning `no restriction'. */
2992 return Fcurrent_buffer ();
2993 else
2994 /* We have to save a restriction, so return a pair of markers, one
2995 for the beginning and one for the end. */
2996 {
2997 Lisp_Object beg, end;
2998
2999 beg = buildmark (BEGV, BEGV_BYTE);
3000 end = buildmark (ZV, ZV_BYTE);
3001
3002 /* END must move forward if text is inserted at its exact location. */
3003 XMARKER(end)->insertion_type = 1;
3004
3005 return Fcons (beg, end);
3006 }
3007 }
3008
3009 Lisp_Object
3010 save_restriction_restore (data)
3011 Lisp_Object data;
3012 {
3013 if (CONSP (data))
3014 /* A pair of marks bounding a saved restriction. */
3015 {
3016 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3017 struct Lisp_Marker *end = XMARKER (XCDR (data));
3018 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
3019
3020 if (buf /* Verify marker still points to a buffer. */
3021 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3022 /* The restriction has changed from the saved one, so restore
3023 the saved restriction. */
3024 {
3025 int pt = BUF_PT (buf);
3026
3027 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3028 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3029
3030 if (pt < beg->charpos || pt > end->charpos)
3031 /* The point is outside the new visible range, move it inside. */
3032 SET_BUF_PT_BOTH (buf,
3033 clip_to_bounds (beg->charpos, pt, end->charpos),
3034 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3035 end->bytepos));
3036
3037 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3038 }
3039 }
3040 else
3041 /* A buffer, which means that there was no old restriction. */
3042 {
3043 struct buffer *buf = XBUFFER (data);
3044
3045 if (buf /* Verify marker still points to a buffer. */
3046 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3047 /* The buffer has been narrowed, get rid of the narrowing. */
3048 {
3049 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3050 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3051
3052 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3053 }
3054 }
3055
3056 return Qnil;
3057 }
3058
3059 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3060 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3061 The buffer's restrictions make parts of the beginning and end invisible.
3062 (They are set up with `narrow-to-region' and eliminated with `widen'.)
3063 This special form, `save-restriction', saves the current buffer's restrictions
3064 when it is entered, and restores them when it is exited.
3065 So any `narrow-to-region' within BODY lasts only until the end of the form.
3066 The old restrictions settings are restored
3067 even in case of abnormal exit (throw or error).
3068
3069 The value returned is the value of the last form in BODY.
3070
3071 Note: if you are using both `save-excursion' and `save-restriction',
3072 use `save-excursion' outermost:
3073 (save-excursion (save-restriction ...))
3074
3075 usage: (save-restriction &rest BODY) */)
3076 (body)
3077 Lisp_Object body;
3078 {
3079 register Lisp_Object val;
3080 int count = SPECPDL_INDEX ();
3081
3082 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3083 val = Fprogn (body);
3084 return unbind_to (count, val);
3085 }
3086 \f
3087 /* Buffer for the most recent text displayed by Fmessage_box. */
3088 static char *message_text;
3089
3090 /* Allocated length of that buffer. */
3091 static int message_length;
3092
3093 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3094 doc: /* Print a one-line message at the bottom of the screen.
3095 The message also goes into the `*Messages*' buffer.
3096 \(In keyboard macros, that's all it does.)
3097
3098 The first argument is a format control string, and the rest are data
3099 to be formatted under control of the string. See `format' for details.
3100
3101 If the first argument is nil, the function clears any existing message;
3102 this lets the minibuffer contents show. See also `current-message'.
3103
3104 usage: (message STRING &rest ARGS) */)
3105 (nargs, args)
3106 int nargs;
3107 Lisp_Object *args;
3108 {
3109 if (NILP (args[0])
3110 || (STRINGP (args[0])
3111 && SBYTES (args[0]) == 0))
3112 {
3113 message (0);
3114 return Qnil;
3115 }
3116 else
3117 {
3118 register Lisp_Object val;
3119 val = Fformat (nargs, args);
3120 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3121 return val;
3122 }
3123 }
3124
3125 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3126 doc: /* Display a message, in a dialog box if possible.
3127 If a dialog box is not available, use the echo area.
3128 The first argument is a format control string, and the rest are data
3129 to be formatted under control of the string. See `format' for details.
3130
3131 If the first argument is nil, clear any existing message; let the
3132 minibuffer contents show.
3133
3134 usage: (message-box STRING &rest ARGS) */)
3135 (nargs, args)
3136 int nargs;
3137 Lisp_Object *args;
3138 {
3139 if (NILP (args[0]))
3140 {
3141 message (0);
3142 return Qnil;
3143 }
3144 else
3145 {
3146 register Lisp_Object val;
3147 val = Fformat (nargs, args);
3148 #ifdef HAVE_MENUS
3149 /* The MS-DOS frames support popup menus even though they are
3150 not FRAME_WINDOW_P. */
3151 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3152 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3153 {
3154 Lisp_Object pane, menu, obj;
3155 struct gcpro gcpro1;
3156 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3157 GCPRO1 (pane);
3158 menu = Fcons (val, pane);
3159 obj = Fx_popup_dialog (Qt, menu);
3160 UNGCPRO;
3161 return val;
3162 }
3163 #endif /* HAVE_MENUS */
3164 /* Copy the data so that it won't move when we GC. */
3165 if (! message_text)
3166 {
3167 message_text = (char *)xmalloc (80);
3168 message_length = 80;
3169 }
3170 if (SBYTES (val) > message_length)
3171 {
3172 message_length = SBYTES (val);
3173 message_text = (char *)xrealloc (message_text, message_length);
3174 }
3175 bcopy (SDATA (val), message_text, SBYTES (val));
3176 message2 (message_text, SBYTES (val),
3177 STRING_MULTIBYTE (val));
3178 return val;
3179 }
3180 }
3181 #ifdef HAVE_MENUS
3182 extern Lisp_Object last_nonmenu_event;
3183 #endif
3184
3185 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3186 doc: /* Display a message in a dialog box or in the echo area.
3187 If this command was invoked with the mouse, use a dialog box if
3188 `use-dialog-box' is non-nil.
3189 Otherwise, use the echo area.
3190 The first argument is a format control string, and the rest are data
3191 to be formatted under control of the string. See `format' for details.
3192
3193 If the first argument is nil, clear any existing message; let the
3194 minibuffer contents show.
3195
3196 usage: (message-or-box STRING &rest ARGS) */)
3197 (nargs, args)
3198 int nargs;
3199 Lisp_Object *args;
3200 {
3201 #ifdef HAVE_MENUS
3202 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3203 && use_dialog_box)
3204 return Fmessage_box (nargs, args);
3205 #endif
3206 return Fmessage (nargs, args);
3207 }
3208
3209 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3210 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3211 ()
3212 {
3213 return current_message ();
3214 }
3215
3216
3217 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3218 doc: /* Return a copy of STRING with text properties added.
3219 First argument is the string to copy.
3220 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3221 properties to add to the result.
3222 usage: (propertize STRING &rest PROPERTIES) */)
3223 (nargs, args)
3224 int nargs;
3225 Lisp_Object *args;
3226 {
3227 Lisp_Object properties, string;
3228 struct gcpro gcpro1, gcpro2;
3229 int i;
3230
3231 /* Number of args must be odd. */
3232 if ((nargs & 1) == 0 || nargs < 1)
3233 error ("Wrong number of arguments");
3234
3235 properties = string = Qnil;
3236 GCPRO2 (properties, string);
3237
3238 /* First argument must be a string. */
3239 CHECK_STRING (args[0]);
3240 string = Fcopy_sequence (args[0]);
3241
3242 for (i = 1; i < nargs; i += 2)
3243 {
3244 CHECK_SYMBOL (args[i]);
3245 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3246 }
3247
3248 Fadd_text_properties (make_number (0),
3249 make_number (SCHARS (string)),
3250 properties, string);
3251 RETURN_UNGCPRO (string);
3252 }
3253
3254
3255 /* Number of bytes that STRING will occupy when put into the result.
3256 MULTIBYTE is nonzero if the result should be multibyte. */
3257
3258 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3259 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3260 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3261 : SBYTES (STRING))
3262
3263 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3264 doc: /* Format a string out of a control-string and arguments.
3265 The first argument is a control string.
3266 The other arguments are substituted into it to make the result, a string.
3267 It may contain %-sequences meaning to substitute the next argument.
3268 %s means print a string argument. Actually, prints any object, with `princ'.
3269 %d means print as number in decimal (%o octal, %x hex).
3270 %X is like %x, but uses upper case.
3271 %e means print a number in exponential notation.
3272 %f means print a number in decimal-point notation.
3273 %g means print a number in exponential notation
3274 or decimal-point notation, whichever uses fewer characters.
3275 %c means print a number as a single character.
3276 %S means print any object as an s-expression (using `prin1').
3277 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3278 Use %% to put a single % into the output.
3279
3280 The basic structure of a %-sequence is
3281 % <flags> <width> <precision> character
3282 where flags is [- #0]+, width is [0-9]+, and precision is .[0-9]+
3283
3284 usage: (format STRING &rest OBJECTS) */)
3285 (nargs, args)
3286 int nargs;
3287 register Lisp_Object *args;
3288 {
3289 register int n; /* The number of the next arg to substitute */
3290 register int total; /* An estimate of the final length */
3291 char *buf, *p;
3292 register unsigned char *format, *end, *format_start;
3293 int nchars;
3294 /* Nonzero if the output should be a multibyte string,
3295 which is true if any of the inputs is one. */
3296 int multibyte = 0;
3297 /* When we make a multibyte string, we must pay attention to the
3298 byte combining problem, i.e., a byte may be combined with a
3299 multibyte charcter of the previous string. This flag tells if we
3300 must consider such a situation or not. */
3301 int maybe_combine_byte;
3302 unsigned char *this_format;
3303 /* Precision for each spec, or -1, a flag value meaning no precision
3304 was given in that spec. Element 0, corresonding to the format
3305 string itself, will not be used. Element NARGS, corresponding to
3306 no argument, *will* be assigned to in the case that a `%' and `.'
3307 occur after the final format specifier. */
3308 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
3309 int longest_format;
3310 Lisp_Object val;
3311 int arg_intervals = 0;
3312 USE_SAFE_ALLOCA;
3313
3314 /* discarded[I] is 1 if byte I of the format
3315 string was not copied into the output.
3316 It is 2 if byte I was not the first byte of its character. */
3317 char *discarded = 0;
3318
3319 /* Each element records, for one argument,
3320 the start and end bytepos in the output string,
3321 and whether the argument is a string with intervals.
3322 info[0] is unused. Unused elements have -1 for start. */
3323 struct info
3324 {
3325 int start, end, intervals;
3326 } *info = 0;
3327
3328 /* It should not be necessary to GCPRO ARGS, because
3329 the caller in the interpreter should take care of that. */
3330
3331 /* Try to determine whether the result should be multibyte.
3332 This is not always right; sometimes the result needs to be multibyte
3333 because of an object that we will pass through prin1,
3334 and in that case, we won't know it here. */
3335 for (n = 0; n < nargs; n++)
3336 {
3337 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3338 multibyte = 1;
3339 /* Piggyback on this loop to initialize precision[N]. */
3340 precision[n] = -1;
3341 }
3342 precision[nargs] = -1;
3343
3344 CHECK_STRING (args[0]);
3345 /* We may have to change "%S" to "%s". */
3346 args[0] = Fcopy_sequence (args[0]);
3347
3348 /* GC should never happen here, so abort if it does. */
3349 abort_on_gc++;
3350
3351 /* If we start out planning a unibyte result,
3352 then discover it has to be multibyte, we jump back to retry.
3353 That can only happen from the first large while loop below. */
3354 retry:
3355
3356 format = SDATA (args[0]);
3357 format_start = format;
3358 end = format + SBYTES (args[0]);
3359 longest_format = 0;
3360
3361 /* Make room in result for all the non-%-codes in the control string. */
3362 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3363
3364 /* Allocate the info and discarded tables. */
3365 {
3366 int nbytes = (nargs+1) * sizeof *info;
3367 int i;
3368 if (!info)
3369 info = (struct info *) alloca (nbytes);
3370 bzero (info, nbytes);
3371 for (i = 0; i <= nargs; i++)
3372 info[i].start = -1;
3373 if (!discarded)
3374 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3375 bzero (discarded, SBYTES (args[0]));
3376 }
3377
3378 /* Add to TOTAL enough space to hold the converted arguments. */
3379
3380 n = 0;
3381 while (format != end)
3382 if (*format++ == '%')
3383 {
3384 int thissize = 0;
3385 int actual_width = 0;
3386 unsigned char *this_format_start = format - 1;
3387 int field_width = 0;
3388
3389 /* General format specifications look like
3390
3391 '%' [flags] [field-width] [precision] format
3392
3393 where
3394
3395 flags ::= [- #0]+
3396 field-width ::= [0-9]+
3397 precision ::= '.' [0-9]*
3398
3399 If a field-width is specified, it specifies to which width
3400 the output should be padded with blanks, iff the output
3401 string is shorter than field-width.
3402
3403 If precision is specified, it specifies the number of
3404 digits to print after the '.' for floats, or the max.
3405 number of chars to print from a string. */
3406
3407 while (index ("-0# ", *format))
3408 ++format;
3409
3410 if (*format >= '0' && *format <= '9')
3411 {
3412 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3413 field_width = 10 * field_width + *format - '0';
3414 }
3415
3416 /* N is not incremented for another few lines below, so refer to
3417 element N+1 (which might be precision[NARGS]). */
3418 if (*format == '.')
3419 {
3420 ++format;
3421 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3422 precision[n+1] = 10 * precision[n+1] + *format - '0';
3423 }
3424
3425 if (format - this_format_start + 1 > longest_format)
3426 longest_format = format - this_format_start + 1;
3427
3428 if (format == end)
3429 error ("Format string ends in middle of format specifier");
3430 if (*format == '%')
3431 format++;
3432 else if (++n >= nargs)
3433 error ("Not enough arguments for format string");
3434 else if (*format == 'S')
3435 {
3436 /* For `S', prin1 the argument and then treat like a string. */
3437 register Lisp_Object tem;
3438 tem = Fprin1_to_string (args[n], Qnil);
3439 if (STRING_MULTIBYTE (tem) && ! multibyte)
3440 {
3441 multibyte = 1;
3442 goto retry;
3443 }
3444 args[n] = tem;
3445 /* If we restart the loop, we should not come here again
3446 because args[n] is now a string and calling
3447 Fprin1_to_string on it produces superflous double
3448 quotes. So, change "%S" to "%s" now. */
3449 *format = 's';
3450 goto string;
3451 }
3452 else if (SYMBOLP (args[n]))
3453 {
3454 args[n] = SYMBOL_NAME (args[n]);
3455 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3456 {
3457 multibyte = 1;
3458 goto retry;
3459 }
3460 goto string;
3461 }
3462 else if (STRINGP (args[n]))
3463 {
3464 string:
3465 if (*format != 's' && *format != 'S')
3466 error ("Format specifier doesn't match argument type");
3467 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3468 to be as large as is calculated here. Easy check for
3469 the case PRECISION = 0. */
3470 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3471 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3472 }
3473 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3474 else if (INTEGERP (args[n]) && *format != 's')
3475 {
3476 /* The following loop assumes the Lisp type indicates
3477 the proper way to pass the argument.
3478 So make sure we have a flonum if the argument should
3479 be a double. */
3480 if (*format == 'e' || *format == 'f' || *format == 'g')
3481 args[n] = Ffloat (args[n]);
3482 else
3483 if (*format != 'd' && *format != 'o' && *format != 'x'
3484 && *format != 'i' && *format != 'X' && *format != 'c')
3485 error ("Invalid format operation %%%c", *format);
3486
3487 thissize = 30;
3488 if (*format == 'c')
3489 {
3490 if (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3491 /* Note: No one can remember why we have to treat
3492 the character 0 as a multibyte character here.
3493 But, until it causes a real problem, let's
3494 don't change it. */
3495 || XINT (args[n]) == 0)
3496 {
3497 if (! multibyte)
3498 {
3499 multibyte = 1;
3500 goto retry;
3501 }
3502 args[n] = Fchar_to_string (args[n]);
3503 thissize = SBYTES (args[n]);
3504 }
3505 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3506 {
3507 args[n]
3508 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3509 thissize = SBYTES (args[n]);
3510 }
3511 }
3512 }
3513 else if (FLOATP (args[n]) && *format != 's')
3514 {
3515 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3516 {
3517 if (*format != 'd' && *format != 'o' && *format != 'x'
3518 && *format != 'i' && *format != 'X' && *format != 'c')
3519 error ("Invalid format operation %%%c", *format);
3520 args[n] = Ftruncate (args[n], Qnil);
3521 }
3522
3523 /* Note that we're using sprintf to print floats,
3524 so we have to take into account what that function
3525 prints. */
3526 /* Filter out flag value of -1. */
3527 thissize = (MAX_10_EXP + 100
3528 + (precision[n] > 0 ? precision[n] : 0));
3529 }
3530 else
3531 {
3532 /* Anything but a string, convert to a string using princ. */
3533 register Lisp_Object tem;
3534 tem = Fprin1_to_string (args[n], Qt);
3535 if (STRING_MULTIBYTE (tem) && ! multibyte)
3536 {
3537 multibyte = 1;
3538 goto retry;
3539 }
3540 args[n] = tem;
3541 goto string;
3542 }
3543
3544 thissize += max (0, field_width - actual_width);
3545 total += thissize + 4;
3546 }
3547
3548 abort_on_gc--;
3549
3550 /* Now we can no longer jump to retry.
3551 TOTAL and LONGEST_FORMAT are known for certain. */
3552
3553 this_format = (unsigned char *) alloca (longest_format + 1);
3554
3555 /* Allocate the space for the result.
3556 Note that TOTAL is an overestimate. */
3557 SAFE_ALLOCA (buf, char *, total);
3558
3559 p = buf;
3560 nchars = 0;
3561 n = 0;
3562
3563 /* Scan the format and store result in BUF. */
3564 format = SDATA (args[0]);
3565 format_start = format;
3566 end = format + SBYTES (args[0]);
3567 maybe_combine_byte = 0;
3568 while (format != end)
3569 {
3570 if (*format == '%')
3571 {
3572 int minlen;
3573 int negative = 0;
3574 unsigned char *this_format_start = format;
3575
3576 discarded[format - format_start] = 1;
3577 format++;
3578
3579 while (index("-0# ", *format))
3580 {
3581 if (*format == '-')
3582 {
3583 negative = 1;
3584 }
3585 discarded[format - format_start] = 1;
3586 ++format;
3587 }
3588
3589 minlen = atoi (format);
3590
3591 while ((*format >= '0' && *format <= '9') || *format == '.')
3592 {
3593 discarded[format - format_start] = 1;
3594 format++;
3595 }
3596
3597 if (*format++ == '%')
3598 {
3599 *p++ = '%';
3600 nchars++;
3601 continue;
3602 }
3603
3604 ++n;
3605
3606 discarded[format - format_start - 1] = 1;
3607 info[n].start = nchars;
3608
3609 if (STRINGP (args[n]))
3610 {
3611 /* handle case (precision[n] >= 0) */
3612
3613 int width, padding;
3614 int nbytes, start, end;
3615 int nchars_string;
3616
3617 /* lisp_string_width ignores a precision of 0, but GNU
3618 libc functions print 0 characters when the precision
3619 is 0. Imitate libc behavior here. Changing
3620 lisp_string_width is the right thing, and will be
3621 done, but meanwhile we work with it. */
3622
3623 if (precision[n] == 0)
3624 width = nchars_string = nbytes = 0;
3625 else if (precision[n] > 0)
3626 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3627 else
3628 { /* no precision spec given for this argument */
3629 width = lisp_string_width (args[n], -1, NULL, NULL);
3630 nbytes = SBYTES (args[n]);
3631 nchars_string = SCHARS (args[n]);
3632 }
3633
3634 /* If spec requires it, pad on right with spaces. */
3635 padding = minlen - width;
3636 if (! negative)
3637 while (padding-- > 0)
3638 {
3639 *p++ = ' ';
3640 ++nchars;
3641 }
3642
3643 start = nchars;
3644 nchars += nchars_string;
3645 end = nchars;
3646
3647 if (p > buf
3648 && multibyte
3649 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3650 && STRING_MULTIBYTE (args[n])
3651 && !CHAR_HEAD_P (SREF (args[n], 0)))
3652 maybe_combine_byte = 1;
3653
3654 p += copy_text (SDATA (args[n]), p,
3655 nbytes,
3656 STRING_MULTIBYTE (args[n]), multibyte);
3657
3658 if (negative)
3659 while (padding-- > 0)
3660 {
3661 *p++ = ' ';
3662 nchars++;
3663 }
3664
3665 /* If this argument has text properties, record where
3666 in the result string it appears. */
3667 if (STRING_INTERVALS (args[n]))
3668 info[n].intervals = arg_intervals = 1;
3669 }
3670 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3671 {
3672 int this_nchars;
3673
3674 bcopy (this_format_start, this_format,
3675 format - this_format_start);
3676 this_format[format - this_format_start] = 0;
3677
3678 if (INTEGERP (args[n]))
3679 sprintf (p, this_format, XINT (args[n]));
3680 else
3681 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3682
3683 if (p > buf
3684 && multibyte
3685 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3686 && !CHAR_HEAD_P (*((unsigned char *) p)))
3687 maybe_combine_byte = 1;
3688 this_nchars = strlen (p);
3689 if (multibyte)
3690 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
3691 else
3692 p += this_nchars;
3693 nchars += this_nchars;
3694 }
3695
3696 info[n].end = nchars;
3697 }
3698 else if (STRING_MULTIBYTE (args[0]))
3699 {
3700 /* Copy a whole multibyte character. */
3701 if (p > buf
3702 && multibyte
3703 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3704 && !CHAR_HEAD_P (*format))
3705 maybe_combine_byte = 1;
3706 *p++ = *format++;
3707 while (! CHAR_HEAD_P (*format))
3708 {
3709 discarded[format - format_start] = 2;
3710 *p++ = *format++;
3711 }
3712 nchars++;
3713 }
3714 else if (multibyte)
3715 {
3716 /* Convert a single-byte character to multibyte. */
3717 int len = copy_text (format, p, 1, 0, 1);
3718
3719 p += len;
3720 format++;
3721 nchars++;
3722 }
3723 else
3724 *p++ = *format++, nchars++;
3725 }
3726
3727 if (p > buf + total)
3728 abort ();
3729
3730 if (maybe_combine_byte)
3731 nchars = multibyte_chars_in_text (buf, p - buf);
3732 val = make_specified_string (buf, nchars, p - buf, multibyte);
3733
3734 /* If we allocated BUF with malloc, free it too. */
3735 SAFE_FREE ();
3736
3737 /* If the format string has text properties, or any of the string
3738 arguments has text properties, set up text properties of the
3739 result string. */
3740
3741 if (STRING_INTERVALS (args[0]) || arg_intervals)
3742 {
3743 Lisp_Object len, new_len, props;
3744 struct gcpro gcpro1;
3745
3746 /* Add text properties from the format string. */
3747 len = make_number (SCHARS (args[0]));
3748 props = text_property_list (args[0], make_number (0), len, Qnil);
3749 GCPRO1 (props);
3750
3751 if (CONSP (props))
3752 {
3753 int bytepos = 0, position = 0, translated = 0, argn = 1;
3754 Lisp_Object list;
3755
3756 /* Adjust the bounds of each text property
3757 to the proper start and end in the output string. */
3758
3759 /* Put the positions in PROPS in increasing order, so that
3760 we can do (effectively) one scan through the position
3761 space of the format string. */
3762 props = Fnreverse (props);
3763
3764 /* BYTEPOS is the byte position in the format string,
3765 POSITION is the untranslated char position in it,
3766 TRANSLATED is the translated char position in BUF,
3767 and ARGN is the number of the next arg we will come to. */
3768 for (list = props; CONSP (list); list = XCDR (list))
3769 {
3770 Lisp_Object item;
3771 int pos;
3772
3773 item = XCAR (list);
3774
3775 /* First adjust the property start position. */
3776 pos = XINT (XCAR (item));
3777
3778 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
3779 up to this position. */
3780 for (; position < pos; bytepos++)
3781 {
3782 if (! discarded[bytepos])
3783 position++, translated++;
3784 else if (discarded[bytepos] == 1)
3785 {
3786 position++;
3787 if (translated == info[argn].start)
3788 {
3789 translated += info[argn].end - info[argn].start;
3790 argn++;
3791 }
3792 }
3793 }
3794
3795 XSETCAR (item, make_number (translated));
3796
3797 /* Likewise adjust the property end position. */
3798 pos = XINT (XCAR (XCDR (item)));
3799
3800 for (; bytepos < pos; bytepos++)
3801 {
3802 if (! discarded[bytepos])
3803 position++, translated++;
3804 else if (discarded[bytepos] == 1)
3805 {
3806 position++;
3807 if (translated == info[argn].start)
3808 {
3809 translated += info[argn].end - info[argn].start;
3810 argn++;
3811 }
3812 }
3813 }
3814
3815 XSETCAR (XCDR (item), make_number (translated));
3816 }
3817
3818 add_text_properties_from_list (val, props, make_number (0));
3819 }
3820
3821 /* Add text properties from arguments. */
3822 if (arg_intervals)
3823 for (n = 1; n < nargs; ++n)
3824 if (info[n].intervals)
3825 {
3826 len = make_number (SCHARS (args[n]));
3827 new_len = make_number (info[n].end - info[n].start);
3828 props = text_property_list (args[n], make_number (0), len, Qnil);
3829 extend_property_ranges (props, len, new_len);
3830 /* If successive arguments have properites, be sure that
3831 the value of `composition' property be the copy. */
3832 if (n > 1 && info[n - 1].end)
3833 make_composition_value_copy (props);
3834 add_text_properties_from_list (val, props,
3835 make_number (info[n].start));
3836 }
3837
3838 UNGCPRO;
3839 }
3840
3841 return val;
3842 }
3843
3844 Lisp_Object
3845 format2 (string1, arg0, arg1)
3846 char *string1;
3847 Lisp_Object arg0, arg1;
3848 {
3849 Lisp_Object args[3];
3850 args[0] = build_string (string1);
3851 args[1] = arg0;
3852 args[2] = arg1;
3853 return Fformat (3, args);
3854 }
3855 \f
3856 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3857 doc: /* Return t if two characters match, optionally ignoring case.
3858 Both arguments must be characters (i.e. integers).
3859 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
3860 (c1, c2)
3861 register Lisp_Object c1, c2;
3862 {
3863 int i1, i2;
3864 CHECK_NUMBER (c1);
3865 CHECK_NUMBER (c2);
3866
3867 if (XINT (c1) == XINT (c2))
3868 return Qt;
3869 if (NILP (current_buffer->case_fold_search))
3870 return Qnil;
3871
3872 /* Do these in separate statements,
3873 then compare the variables.
3874 because of the way DOWNCASE uses temp variables. */
3875 i1 = DOWNCASE (XFASTINT (c1));
3876 i2 = DOWNCASE (XFASTINT (c2));
3877 return (i1 == i2 ? Qt : Qnil);
3878 }
3879 \f
3880 /* Transpose the markers in two regions of the current buffer, and
3881 adjust the ones between them if necessary (i.e.: if the regions
3882 differ in size).
3883
3884 START1, END1 are the character positions of the first region.
3885 START1_BYTE, END1_BYTE are the byte positions.
3886 START2, END2 are the character positions of the second region.
3887 START2_BYTE, END2_BYTE are the byte positions.
3888
3889 Traverses the entire marker list of the buffer to do so, adding an
3890 appropriate amount to some, subtracting from some, and leaving the
3891 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3892
3893 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3894
3895 static void
3896 transpose_markers (start1, end1, start2, end2,
3897 start1_byte, end1_byte, start2_byte, end2_byte)
3898 register int start1, end1, start2, end2;
3899 register int start1_byte, end1_byte, start2_byte, end2_byte;
3900 {
3901 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3902 register struct Lisp_Marker *marker;
3903
3904 /* Update point as if it were a marker. */
3905 if (PT < start1)
3906 ;
3907 else if (PT < end1)
3908 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3909 PT_BYTE + (end2_byte - end1_byte));
3910 else if (PT < start2)
3911 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3912 (PT_BYTE + (end2_byte - start2_byte)
3913 - (end1_byte - start1_byte)));
3914 else if (PT < end2)
3915 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3916 PT_BYTE - (start2_byte - start1_byte));
3917
3918 /* We used to adjust the endpoints here to account for the gap, but that
3919 isn't good enough. Even if we assume the caller has tried to move the
3920 gap out of our way, it might still be at start1 exactly, for example;
3921 and that places it `inside' the interval, for our purposes. The amount
3922 of adjustment is nontrivial if there's a `denormalized' marker whose
3923 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3924 the dirty work to Fmarker_position, below. */
3925
3926 /* The difference between the region's lengths */
3927 diff = (end2 - start2) - (end1 - start1);
3928 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3929
3930 /* For shifting each marker in a region by the length of the other
3931 region plus the distance between the regions. */
3932 amt1 = (end2 - start2) + (start2 - end1);
3933 amt2 = (end1 - start1) + (start2 - end1);
3934 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3935 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3936
3937 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
3938 {
3939 mpos = marker->bytepos;
3940 if (mpos >= start1_byte && mpos < end2_byte)
3941 {
3942 if (mpos < end1_byte)
3943 mpos += amt1_byte;
3944 else if (mpos < start2_byte)
3945 mpos += diff_byte;
3946 else
3947 mpos -= amt2_byte;
3948 marker->bytepos = mpos;
3949 }
3950 mpos = marker->charpos;
3951 if (mpos >= start1 && mpos < end2)
3952 {
3953 if (mpos < end1)
3954 mpos += amt1;
3955 else if (mpos < start2)
3956 mpos += diff;
3957 else
3958 mpos -= amt2;
3959 }
3960 marker->charpos = mpos;
3961 }
3962 }
3963
3964 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3965 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
3966 The regions may not be overlapping, because the size of the buffer is
3967 never changed in a transposition.
3968
3969 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
3970 any markers that happen to be located in the regions.
3971
3972 Transposing beyond buffer boundaries is an error. */)
3973 (startr1, endr1, startr2, endr2, leave_markers)
3974 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3975 {
3976 register int start1, end1, start2, end2;
3977 int start1_byte, start2_byte, len1_byte, len2_byte;
3978 int gap, len1, len_mid, len2;
3979 unsigned char *start1_addr, *start2_addr, *temp;
3980
3981 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3982 cur_intv = BUF_INTERVALS (current_buffer);
3983
3984 validate_region (&startr1, &endr1);
3985 validate_region (&startr2, &endr2);
3986
3987 start1 = XFASTINT (startr1);
3988 end1 = XFASTINT (endr1);
3989 start2 = XFASTINT (startr2);
3990 end2 = XFASTINT (endr2);
3991 gap = GPT;
3992
3993 /* Swap the regions if they're reversed. */
3994 if (start2 < end1)
3995 {
3996 register int glumph = start1;
3997 start1 = start2;
3998 start2 = glumph;
3999 glumph = end1;
4000 end1 = end2;
4001 end2 = glumph;
4002 }
4003
4004 len1 = end1 - start1;
4005 len2 = end2 - start2;
4006
4007 if (start2 < end1)
4008 error ("Transposed regions overlap");
4009 else if (start1 == end1 || start2 == end2)
4010 error ("Transposed region has length 0");
4011
4012 /* The possibilities are:
4013 1. Adjacent (contiguous) regions, or separate but equal regions
4014 (no, really equal, in this case!), or
4015 2. Separate regions of unequal size.
4016
4017 The worst case is usually No. 2. It means that (aside from
4018 potential need for getting the gap out of the way), there also
4019 needs to be a shifting of the text between the two regions. So
4020 if they are spread far apart, we are that much slower... sigh. */
4021
4022 /* It must be pointed out that the really studly thing to do would
4023 be not to move the gap at all, but to leave it in place and work
4024 around it if necessary. This would be extremely efficient,
4025 especially considering that people are likely to do
4026 transpositions near where they are working interactively, which
4027 is exactly where the gap would be found. However, such code
4028 would be much harder to write and to read. So, if you are
4029 reading this comment and are feeling squirrely, by all means have
4030 a go! I just didn't feel like doing it, so I will simply move
4031 the gap the minimum distance to get it out of the way, and then
4032 deal with an unbroken array. */
4033
4034 /* Make sure the gap won't interfere, by moving it out of the text
4035 we will operate on. */
4036 if (start1 < gap && gap < end2)
4037 {
4038 if (gap - start1 < end2 - gap)
4039 move_gap (start1);
4040 else
4041 move_gap (end2);
4042 }
4043
4044 start1_byte = CHAR_TO_BYTE (start1);
4045 start2_byte = CHAR_TO_BYTE (start2);
4046 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4047 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4048
4049 #ifdef BYTE_COMBINING_DEBUG
4050 if (end1 == start2)
4051 {
4052 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4053 len2_byte, start1, start1_byte)
4054 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4055 len1_byte, end2, start2_byte + len2_byte)
4056 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4057 len1_byte, end2, start2_byte + len2_byte))
4058 abort ();
4059 }
4060 else
4061 {
4062 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4063 len2_byte, start1, start1_byte)
4064 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4065 len1_byte, start2, start2_byte)
4066 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4067 len2_byte, end1, start1_byte + len1_byte)
4068 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4069 len1_byte, end2, start2_byte + len2_byte))
4070 abort ();
4071 }
4072 #endif
4073
4074 /* Hmmm... how about checking to see if the gap is large
4075 enough to use as the temporary storage? That would avoid an
4076 allocation... interesting. Later, don't fool with it now. */
4077
4078 /* Working without memmove, for portability (sigh), so must be
4079 careful of overlapping subsections of the array... */
4080
4081 if (end1 == start2) /* adjacent regions */
4082 {
4083 modify_region (current_buffer, start1, end2);
4084 record_change (start1, len1 + len2);
4085
4086 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4087 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4088 Fset_text_properties (make_number (start1), make_number (end2),
4089 Qnil, Qnil);
4090
4091 /* First region smaller than second. */
4092 if (len1_byte < len2_byte)
4093 {
4094 USE_SAFE_ALLOCA;
4095
4096 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4097
4098 /* Don't precompute these addresses. We have to compute them
4099 at the last minute, because the relocating allocator might
4100 have moved the buffer around during the xmalloc. */
4101 start1_addr = BYTE_POS_ADDR (start1_byte);
4102 start2_addr = BYTE_POS_ADDR (start2_byte);
4103
4104 bcopy (start2_addr, temp, len2_byte);
4105 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4106 bcopy (temp, start1_addr, len2_byte);
4107 SAFE_FREE ();
4108 }
4109 else
4110 /* First region not smaller than second. */
4111 {
4112 USE_SAFE_ALLOCA;
4113
4114 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4115 start1_addr = BYTE_POS_ADDR (start1_byte);
4116 start2_addr = BYTE_POS_ADDR (start2_byte);
4117 bcopy (start1_addr, temp, len1_byte);
4118 bcopy (start2_addr, start1_addr, len2_byte);
4119 bcopy (temp, start1_addr + len2_byte, len1_byte);
4120 SAFE_FREE ();
4121 }
4122 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4123 len1, current_buffer, 0);
4124 graft_intervals_into_buffer (tmp_interval2, start1,
4125 len2, current_buffer, 0);
4126 update_compositions (start1, start1 + len2, CHECK_BORDER);
4127 update_compositions (start1 + len2, end2, CHECK_TAIL);
4128 }
4129 /* Non-adjacent regions, because end1 != start2, bleagh... */
4130 else
4131 {
4132 len_mid = start2_byte - (start1_byte + len1_byte);
4133
4134 if (len1_byte == len2_byte)
4135 /* Regions are same size, though, how nice. */
4136 {
4137 USE_SAFE_ALLOCA;
4138
4139 modify_region (current_buffer, start1, end1);
4140 modify_region (current_buffer, start2, end2);
4141 record_change (start1, len1);
4142 record_change (start2, len2);
4143 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4144 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4145 Fset_text_properties (make_number (start1), make_number (end1),
4146 Qnil, Qnil);
4147 Fset_text_properties (make_number (start2), make_number (end2),
4148 Qnil, Qnil);
4149
4150 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4151 start1_addr = BYTE_POS_ADDR (start1_byte);
4152 start2_addr = BYTE_POS_ADDR (start2_byte);
4153 bcopy (start1_addr, temp, len1_byte);
4154 bcopy (start2_addr, start1_addr, len2_byte);
4155 bcopy (temp, start2_addr, len1_byte);
4156 SAFE_FREE ();
4157
4158 graft_intervals_into_buffer (tmp_interval1, start2,
4159 len1, current_buffer, 0);
4160 graft_intervals_into_buffer (tmp_interval2, start1,
4161 len2, current_buffer, 0);
4162 }
4163
4164 else if (len1_byte < len2_byte) /* Second region larger than first */
4165 /* Non-adjacent & unequal size, area between must also be shifted. */
4166 {
4167 USE_SAFE_ALLOCA;
4168
4169 modify_region (current_buffer, start1, end2);
4170 record_change (start1, (end2 - start1));
4171 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4172 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4173 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4174 Fset_text_properties (make_number (start1), make_number (end2),
4175 Qnil, Qnil);
4176
4177 /* holds region 2 */
4178 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4179 start1_addr = BYTE_POS_ADDR (start1_byte);
4180 start2_addr = BYTE_POS_ADDR (start2_byte);
4181 bcopy (start2_addr, temp, len2_byte);
4182 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4183 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4184 bcopy (temp, start1_addr, len2_byte);
4185 SAFE_FREE ();
4186
4187 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4188 len1, current_buffer, 0);
4189 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4190 len_mid, current_buffer, 0);
4191 graft_intervals_into_buffer (tmp_interval2, start1,
4192 len2, current_buffer, 0);
4193 }
4194 else
4195 /* Second region smaller than first. */
4196 {
4197 USE_SAFE_ALLOCA;
4198
4199 record_change (start1, (end2 - start1));
4200 modify_region (current_buffer, start1, end2);
4201
4202 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4203 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4204 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4205 Fset_text_properties (make_number (start1), make_number (end2),
4206 Qnil, Qnil);
4207
4208 /* holds region 1 */
4209 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4210 start1_addr = BYTE_POS_ADDR (start1_byte);
4211 start2_addr = BYTE_POS_ADDR (start2_byte);
4212 bcopy (start1_addr, temp, len1_byte);
4213 bcopy (start2_addr, start1_addr, len2_byte);
4214 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4215 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
4216 SAFE_FREE ();
4217
4218 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4219 len1, current_buffer, 0);
4220 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4221 len_mid, current_buffer, 0);
4222 graft_intervals_into_buffer (tmp_interval2, start1,
4223 len2, current_buffer, 0);
4224 }
4225
4226 update_compositions (start1, start1 + len2, CHECK_BORDER);
4227 update_compositions (end2 - len1, end2, CHECK_BORDER);
4228 }
4229
4230 /* When doing multiple transpositions, it might be nice
4231 to optimize this. Perhaps the markers in any one buffer
4232 should be organized in some sorted data tree. */
4233 if (NILP (leave_markers))
4234 {
4235 transpose_markers (start1, end1, start2, end2,
4236 start1_byte, start1_byte + len1_byte,
4237 start2_byte, start2_byte + len2_byte);
4238 fix_start_end_in_overlays (start1, end2);
4239 }
4240
4241 return Qnil;
4242 }
4243
4244 \f
4245 void
4246 syms_of_editfns ()
4247 {
4248 environbuf = 0;
4249
4250 Qbuffer_access_fontify_functions
4251 = intern ("buffer-access-fontify-functions");
4252 staticpro (&Qbuffer_access_fontify_functions);
4253
4254 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4255 doc: /* Non-nil means text motion commands don't notice fields. */);
4256 Vinhibit_field_text_motion = Qnil;
4257
4258 DEFVAR_LISP ("buffer-access-fontify-functions",
4259 &Vbuffer_access_fontify_functions,
4260 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4261 Each function is called with two arguments which specify the range
4262 of the buffer being accessed. */);
4263 Vbuffer_access_fontify_functions = Qnil;
4264
4265 {
4266 Lisp_Object obuf;
4267 extern Lisp_Object Vprin1_to_string_buffer;
4268 obuf = Fcurrent_buffer ();
4269 /* Do this here, because init_buffer_once is too early--it won't work. */
4270 Fset_buffer (Vprin1_to_string_buffer);
4271 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4272 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
4273 Qnil);
4274 Fset_buffer (obuf);
4275 }
4276
4277 DEFVAR_LISP ("buffer-access-fontified-property",
4278 &Vbuffer_access_fontified_property,
4279 doc: /* Property which (if non-nil) indicates text has been fontified.
4280 `buffer-substring' need not call the `buffer-access-fontify-functions'
4281 functions if all the text being accessed has this property. */);
4282 Vbuffer_access_fontified_property = Qnil;
4283
4284 DEFVAR_LISP ("system-name", &Vsystem_name,
4285 doc: /* The name of the machine Emacs is running on. */);
4286
4287 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4288 doc: /* The full name of the user logged in. */);
4289
4290 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4291 doc: /* The user's name, taken from environment variables if possible. */);
4292
4293 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4294 doc: /* The user's name, based upon the real uid only. */);
4295
4296 defsubr (&Spropertize);
4297 defsubr (&Schar_equal);
4298 defsubr (&Sgoto_char);
4299 defsubr (&Sstring_to_char);
4300 defsubr (&Schar_to_string);
4301 defsubr (&Sbuffer_substring);
4302 defsubr (&Sbuffer_substring_no_properties);
4303 defsubr (&Sbuffer_string);
4304
4305 defsubr (&Spoint_marker);
4306 defsubr (&Smark_marker);
4307 defsubr (&Spoint);
4308 defsubr (&Sregion_beginning);
4309 defsubr (&Sregion_end);
4310
4311 staticpro (&Qfield);
4312 Qfield = intern ("field");
4313 staticpro (&Qboundary);
4314 Qboundary = intern ("boundary");
4315 defsubr (&Sfield_beginning);
4316 defsubr (&Sfield_end);
4317 defsubr (&Sfield_string);
4318 defsubr (&Sfield_string_no_properties);
4319 defsubr (&Sdelete_field);
4320 defsubr (&Sconstrain_to_field);
4321
4322 defsubr (&Sline_beginning_position);
4323 defsubr (&Sline_end_position);
4324
4325 /* defsubr (&Smark); */
4326 /* defsubr (&Sset_mark); */
4327 defsubr (&Ssave_excursion);
4328 defsubr (&Ssave_current_buffer);
4329
4330 defsubr (&Sbufsize);
4331 defsubr (&Spoint_max);
4332 defsubr (&Spoint_min);
4333 defsubr (&Spoint_min_marker);
4334 defsubr (&Spoint_max_marker);
4335 defsubr (&Sgap_position);
4336 defsubr (&Sgap_size);
4337 defsubr (&Sposition_bytes);
4338 defsubr (&Sbyte_to_position);
4339
4340 defsubr (&Sbobp);
4341 defsubr (&Seobp);
4342 defsubr (&Sbolp);
4343 defsubr (&Seolp);
4344 defsubr (&Sfollowing_char);
4345 defsubr (&Sprevious_char);
4346 defsubr (&Schar_after);
4347 defsubr (&Schar_before);
4348 defsubr (&Sinsert);
4349 defsubr (&Sinsert_before_markers);
4350 defsubr (&Sinsert_and_inherit);
4351 defsubr (&Sinsert_and_inherit_before_markers);
4352 defsubr (&Sinsert_char);
4353
4354 defsubr (&Suser_login_name);
4355 defsubr (&Suser_real_login_name);
4356 defsubr (&Suser_uid);
4357 defsubr (&Suser_real_uid);
4358 defsubr (&Suser_full_name);
4359 defsubr (&Semacs_pid);
4360 defsubr (&Scurrent_time);
4361 defsubr (&Sget_internal_run_time);
4362 defsubr (&Sformat_time_string);
4363 defsubr (&Sfloat_time);
4364 defsubr (&Sdecode_time);
4365 defsubr (&Sencode_time);
4366 defsubr (&Scurrent_time_string);
4367 defsubr (&Scurrent_time_zone);
4368 defsubr (&Sset_time_zone_rule);
4369 defsubr (&Ssystem_name);
4370 defsubr (&Smessage);
4371 defsubr (&Smessage_box);
4372 defsubr (&Smessage_or_box);
4373 defsubr (&Scurrent_message);
4374 defsubr (&Sformat);
4375
4376 defsubr (&Sinsert_buffer_substring);
4377 defsubr (&Scompare_buffer_substrings);
4378 defsubr (&Ssubst_char_in_region);
4379 defsubr (&Stranslate_region_internal);
4380 defsubr (&Sdelete_region);
4381 defsubr (&Sdelete_and_extract_region);
4382 defsubr (&Swiden);
4383 defsubr (&Snarrow_to_region);
4384 defsubr (&Ssave_restriction);
4385 defsubr (&Stranspose_regions);
4386 }
4387
4388 /* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4389 (do not change this comment) */