Avoid bidi-related crashes in Cperl Mode.
[emacs.git] / src / editfns.c
blob5328b714b0f9f848db0aeb377b3e690760d8028c
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2011 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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 3 of the License, or
10 (at your option) any later version.
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.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
24 #include <setjmp.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
30 #include <unistd.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
34 #endif
36 #include "lisp.h"
38 /* systime.h includes <sys/time.h> which, on some systems, is required
39 for <sys/resource.h>; thus systime.h must be included before
40 <sys/resource.h> */
41 #include "systime.h"
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
47 #include <ctype.h>
48 #include <float.h>
49 #include <limits.h>
50 #include <intprops.h>
51 #include <strftime.h>
52 #include <verify.h>
54 #include "intervals.h"
55 #include "buffer.h"
56 #include "character.h"
57 #include "coding.h"
58 #include "frame.h"
59 #include "window.h"
60 #include "blockinput.h"
62 #ifndef NULL
63 #define NULL 0
64 #endif
66 #ifndef USER_FULL_NAME
67 #define USER_FULL_NAME pw->pw_gecos
68 #endif
70 #ifndef USE_CRT_DLL
71 extern char **environ;
72 #endif
74 #define TM_YEAR_BASE 1900
76 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
77 asctime to have well-defined behavior. */
78 #ifndef TM_YEAR_IN_ASCTIME_RANGE
79 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
80 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
81 #endif
83 #ifdef WINDOWSNT
84 extern Lisp_Object w32_get_internal_run_time (void);
85 #endif
87 static void time_overflow (void) NO_RETURN;
88 static int tm_diff (struct tm *, struct tm *);
89 static void update_buffer_properties (EMACS_INT, EMACS_INT);
91 static Lisp_Object Qbuffer_access_fontify_functions;
92 static Lisp_Object Fuser_full_name (Lisp_Object);
94 /* Symbol for the text property used to mark fields. */
96 Lisp_Object Qfield;
98 /* A special value for Qfield properties. */
100 static Lisp_Object Qboundary;
103 void
104 init_editfns (void)
106 const char *user_name;
107 register char *p;
108 struct passwd *pw; /* password entry for the current user */
109 Lisp_Object tem;
111 /* Set up system_name even when dumping. */
112 init_system_name ();
114 #ifndef CANNOT_DUMP
115 /* Don't bother with this on initial start when just dumping out */
116 if (!initialized)
117 return;
118 #endif /* not CANNOT_DUMP */
120 pw = getpwuid (getuid ());
121 #ifdef MSDOS
122 /* We let the real user name default to "root" because that's quite
123 accurate on MSDOG and because it lets Emacs find the init file.
124 (The DVX libraries override the Djgpp libraries here.) */
125 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
126 #else
127 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
128 #endif
130 /* Get the effective user name, by consulting environment variables,
131 or the effective uid if those are unset. */
132 user_name = getenv ("LOGNAME");
133 if (!user_name)
134 #ifdef WINDOWSNT
135 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
136 #else /* WINDOWSNT */
137 user_name = getenv ("USER");
138 #endif /* WINDOWSNT */
139 if (!user_name)
141 pw = getpwuid (geteuid ());
142 user_name = pw ? pw->pw_name : "unknown";
144 Vuser_login_name = build_string (user_name);
146 /* If the user name claimed in the environment vars differs from
147 the real uid, use the claimed name to find the full name. */
148 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
149 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
150 : Vuser_login_name);
152 p = getenv ("NAME");
153 if (p)
154 Vuser_full_name = build_string (p);
155 else if (NILP (Vuser_full_name))
156 Vuser_full_name = build_string ("unknown");
158 #ifdef HAVE_SYS_UTSNAME_H
160 struct utsname uts;
161 uname (&uts);
162 Voperating_system_release = build_string (uts.release);
164 #else
165 Voperating_system_release = Qnil;
166 #endif
169 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
170 doc: /* Convert arg CHAR to a string containing that character.
171 usage: (char-to-string CHAR) */)
172 (Lisp_Object character)
174 int c, len;
175 unsigned char str[MAX_MULTIBYTE_LENGTH];
177 CHECK_CHARACTER (character);
178 c = XFASTINT (character);
180 len = CHAR_STRING (c, str);
181 return make_string_from_bytes ((char *) str, 1, len);
184 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
185 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
186 (Lisp_Object byte)
188 unsigned char b;
189 CHECK_NUMBER (byte);
190 if (XINT (byte) < 0 || XINT (byte) > 255)
191 error ("Invalid byte");
192 b = XINT (byte);
193 return make_string_from_bytes ((char *) &b, 1, 1);
196 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
197 doc: /* Convert arg STRING to a character, the first character of that string.
198 A multibyte character is handled correctly. */)
199 (register Lisp_Object string)
201 register Lisp_Object val;
202 CHECK_STRING (string);
203 if (SCHARS (string))
205 if (STRING_MULTIBYTE (string))
206 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
207 else
208 XSETFASTINT (val, SREF (string, 0));
210 else
211 XSETFASTINT (val, 0);
212 return val;
215 static Lisp_Object
216 buildmark (EMACS_INT charpos, EMACS_INT bytepos)
218 register Lisp_Object mark;
219 mark = Fmake_marker ();
220 set_marker_both (mark, Qnil, charpos, bytepos);
221 return mark;
224 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
225 doc: /* Return value of point, as an integer.
226 Beginning of buffer is position (point-min). */)
227 (void)
229 Lisp_Object temp;
230 XSETFASTINT (temp, PT);
231 return temp;
234 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
235 doc: /* Return value of point, as a marker object. */)
236 (void)
238 return buildmark (PT, PT_BYTE);
241 EMACS_INT
242 clip_to_bounds (EMACS_INT lower, EMACS_INT num, EMACS_INT upper)
244 if (num < lower)
245 return lower;
246 else if (num > upper)
247 return upper;
248 else
249 return num;
252 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
253 doc: /* Set point to POSITION, a number or marker.
254 Beginning of buffer is position (point-min), end is (point-max).
256 The return value is POSITION. */)
257 (register Lisp_Object position)
259 EMACS_INT pos;
261 if (MARKERP (position)
262 && current_buffer == XMARKER (position)->buffer)
264 pos = marker_position (position);
265 if (pos < BEGV)
266 SET_PT_BOTH (BEGV, BEGV_BYTE);
267 else if (pos > ZV)
268 SET_PT_BOTH (ZV, ZV_BYTE);
269 else
270 SET_PT_BOTH (pos, marker_byte_position (position));
272 return position;
275 CHECK_NUMBER_COERCE_MARKER (position);
277 pos = clip_to_bounds (BEGV, XINT (position), ZV);
278 SET_PT (pos);
279 return position;
283 /* Return the start or end position of the region.
284 BEGINNINGP non-zero means return the start.
285 If there is no region active, signal an error. */
287 static Lisp_Object
288 region_limit (int beginningp)
290 Lisp_Object m;
292 if (!NILP (Vtransient_mark_mode)
293 && NILP (Vmark_even_if_inactive)
294 && NILP (BVAR (current_buffer, mark_active)))
295 xsignal0 (Qmark_inactive);
297 m = Fmarker_position (BVAR (current_buffer, mark));
298 if (NILP (m))
299 error ("The mark is not set now, so there is no region");
301 if ((PT < XFASTINT (m)) == (beginningp != 0))
302 m = make_number (PT);
303 return m;
306 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
307 doc: /* Return the integer value of point or mark, whichever is smaller. */)
308 (void)
310 return region_limit (1);
313 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
314 doc: /* Return the integer value of point or mark, whichever is larger. */)
315 (void)
317 return region_limit (0);
320 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
321 doc: /* Return this buffer's mark, as a marker object.
322 Watch out! Moving this marker changes the mark position.
323 If you set the marker not to point anywhere, the buffer will have no mark. */)
324 (void)
326 return BVAR (current_buffer, mark);
330 /* Find all the overlays in the current buffer that touch position POS.
331 Return the number found, and store them in a vector in VEC
332 of length LEN. */
334 static ptrdiff_t
335 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
337 Lisp_Object overlay, start, end;
338 struct Lisp_Overlay *tail;
339 EMACS_INT startpos, endpos;
340 ptrdiff_t idx = 0;
342 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
344 XSETMISC (overlay, tail);
346 end = OVERLAY_END (overlay);
347 endpos = OVERLAY_POSITION (end);
348 if (endpos < pos)
349 break;
350 start = OVERLAY_START (overlay);
351 startpos = OVERLAY_POSITION (start);
352 if (startpos <= pos)
354 if (idx < len)
355 vec[idx] = overlay;
356 /* Keep counting overlays even if we can't return them all. */
357 idx++;
361 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
363 XSETMISC (overlay, tail);
365 start = OVERLAY_START (overlay);
366 startpos = OVERLAY_POSITION (start);
367 if (pos < startpos)
368 break;
369 end = OVERLAY_END (overlay);
370 endpos = OVERLAY_POSITION (end);
371 if (pos <= endpos)
373 if (idx < len)
374 vec[idx] = overlay;
375 idx++;
379 return idx;
382 /* Return the value of property PROP, in OBJECT at POSITION.
383 It's the value of PROP that a char inserted at POSITION would get.
384 OBJECT is optional and defaults to the current buffer.
385 If OBJECT is a buffer, then overlay properties are considered as well as
386 text properties.
387 If OBJECT is a window, then that window's buffer is used, but
388 window-specific overlays are considered only if they are associated
389 with OBJECT. */
390 Lisp_Object
391 get_pos_property (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
393 CHECK_NUMBER_COERCE_MARKER (position);
395 if (NILP (object))
396 XSETBUFFER (object, current_buffer);
397 else if (WINDOWP (object))
398 object = XWINDOW (object)->buffer;
400 if (!BUFFERP (object))
401 /* pos-property only makes sense in buffers right now, since strings
402 have no overlays and no notion of insertion for which stickiness
403 could be obeyed. */
404 return Fget_text_property (position, prop, object);
405 else
407 EMACS_INT posn = XINT (position);
408 ptrdiff_t noverlays;
409 Lisp_Object *overlay_vec, tem;
410 struct buffer *obuf = current_buffer;
412 set_buffer_temp (XBUFFER (object));
414 /* First try with room for 40 overlays. */
415 noverlays = 40;
416 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
417 noverlays = overlays_around (posn, overlay_vec, noverlays);
419 /* If there are more than 40,
420 make enough space for all, and try again. */
421 if (noverlays > 40)
423 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
424 noverlays = overlays_around (posn, overlay_vec, noverlays);
426 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
428 set_buffer_temp (obuf);
430 /* Now check the overlays in order of decreasing priority. */
431 while (--noverlays >= 0)
433 Lisp_Object ol = overlay_vec[noverlays];
434 tem = Foverlay_get (ol, prop);
435 if (!NILP (tem))
437 /* Check the overlay is indeed active at point. */
438 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
439 if ((OVERLAY_POSITION (start) == posn
440 && XMARKER (start)->insertion_type == 1)
441 || (OVERLAY_POSITION (finish) == posn
442 && XMARKER (finish)->insertion_type == 0))
443 ; /* The overlay will not cover a char inserted at point. */
444 else
446 return tem;
451 { /* Now check the text properties. */
452 int stickiness = text_property_stickiness (prop, position, object);
453 if (stickiness > 0)
454 return Fget_text_property (position, prop, object);
455 else if (stickiness < 0
456 && XINT (position) > BUF_BEGV (XBUFFER (object)))
457 return Fget_text_property (make_number (XINT (position) - 1),
458 prop, object);
459 else
460 return Qnil;
465 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
466 the value of point is used instead. If BEG or END is null,
467 means don't store the beginning or end of the field.
469 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
470 results; they do not effect boundary behavior.
472 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
473 position of a field, then the beginning of the previous field is
474 returned instead of the beginning of POS's field (since the end of a
475 field is actually also the beginning of the next input field, this
476 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
477 true case, if two fields are separated by a field with the special
478 value `boundary', and POS lies within it, then the two separated
479 fields are considered to be adjacent, and POS between them, when
480 finding the beginning and ending of the "merged" field.
482 Either BEG or END may be 0, in which case the corresponding value
483 is not stored. */
485 static void
486 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
487 Lisp_Object beg_limit,
488 EMACS_INT *beg, Lisp_Object end_limit, EMACS_INT *end)
490 /* Fields right before and after the point. */
491 Lisp_Object before_field, after_field;
492 /* 1 if POS counts as the start of a field. */
493 int at_field_start = 0;
494 /* 1 if POS counts as the end of a field. */
495 int at_field_end = 0;
497 if (NILP (pos))
498 XSETFASTINT (pos, PT);
499 else
500 CHECK_NUMBER_COERCE_MARKER (pos);
502 after_field
503 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
504 before_field
505 = (XFASTINT (pos) > BEGV
506 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
507 Qfield, Qnil, NULL)
508 /* Using nil here would be a more obvious choice, but it would
509 fail when the buffer starts with a non-sticky field. */
510 : after_field);
512 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
513 and POS is at beginning of a field, which can also be interpreted
514 as the end of the previous field. Note that the case where if
515 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
516 more natural one; then we avoid treating the beginning of a field
517 specially. */
518 if (NILP (merge_at_boundary))
520 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
521 if (!EQ (field, after_field))
522 at_field_end = 1;
523 if (!EQ (field, before_field))
524 at_field_start = 1;
525 if (NILP (field) && at_field_start && at_field_end)
526 /* If an inserted char would have a nil field while the surrounding
527 text is non-nil, we're probably not looking at a
528 zero-length field, but instead at a non-nil field that's
529 not intended for editing (such as comint's prompts). */
530 at_field_end = at_field_start = 0;
533 /* Note about special `boundary' fields:
535 Consider the case where the point (`.') is between the fields `x' and `y':
537 xxxx.yyyy
539 In this situation, if merge_at_boundary is true, we consider the
540 `x' and `y' fields as forming one big merged field, and so the end
541 of the field is the end of `y'.
543 However, if `x' and `y' are separated by a special `boundary' field
544 (a field with a `field' char-property of 'boundary), then we ignore
545 this special field when merging adjacent fields. Here's the same
546 situation, but with a `boundary' field between the `x' and `y' fields:
548 xxx.BBBByyyy
550 Here, if point is at the end of `x', the beginning of `y', or
551 anywhere in-between (within the `boundary' field), we merge all
552 three fields and consider the beginning as being the beginning of
553 the `x' field, and the end as being the end of the `y' field. */
555 if (beg)
557 if (at_field_start)
558 /* POS is at the edge of a field, and we should consider it as
559 the beginning of the following field. */
560 *beg = XFASTINT (pos);
561 else
562 /* Find the previous field boundary. */
564 Lisp_Object p = pos;
565 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
566 /* Skip a `boundary' field. */
567 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
568 beg_limit);
570 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
571 beg_limit);
572 *beg = NILP (p) ? BEGV : XFASTINT (p);
576 if (end)
578 if (at_field_end)
579 /* POS is at the edge of a field, and we should consider it as
580 the end of the previous field. */
581 *end = XFASTINT (pos);
582 else
583 /* Find the next field boundary. */
585 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
586 /* Skip a `boundary' field. */
587 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
588 end_limit);
590 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
591 end_limit);
592 *end = NILP (pos) ? ZV : XFASTINT (pos);
598 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
599 doc: /* Delete the field surrounding POS.
600 A field is a region of text with the same `field' property.
601 If POS is nil, the value of point is used for POS. */)
602 (Lisp_Object pos)
604 EMACS_INT beg, end;
605 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
606 if (beg != end)
607 del_range (beg, end);
608 return Qnil;
611 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
612 doc: /* Return the contents of the field surrounding POS as a string.
613 A field is a region of text with the same `field' property.
614 If POS is nil, the value of point is used for POS. */)
615 (Lisp_Object pos)
617 EMACS_INT beg, end;
618 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
619 return make_buffer_string (beg, end, 1);
622 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
623 doc: /* Return the contents of the field around POS, without text properties.
624 A field is a region of text with the same `field' property.
625 If POS is nil, the value of point is used for POS. */)
626 (Lisp_Object pos)
628 EMACS_INT beg, end;
629 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
630 return make_buffer_string (beg, end, 0);
633 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
634 doc: /* Return the beginning of the field surrounding POS.
635 A field is a region of text with the same `field' property.
636 If POS is nil, the value of point is used for POS.
637 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
638 field, then the beginning of the *previous* field is returned.
639 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
640 is before LIMIT, then LIMIT will be returned instead. */)
641 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
643 EMACS_INT beg;
644 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
645 return make_number (beg);
648 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
649 doc: /* Return the end of the field surrounding POS.
650 A field is a region of text with the same `field' property.
651 If POS is nil, the value of point is used for POS.
652 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
653 then the end of the *following* field is returned.
654 If LIMIT is non-nil, it is a buffer position; if the end of the field
655 is after LIMIT, then LIMIT will be returned instead. */)
656 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
658 EMACS_INT end;
659 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
660 return make_number (end);
663 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
664 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
666 A field is a region of text with the same `field' property.
667 If NEW-POS is nil, then the current point is used instead, and set to the
668 constrained position if that is different.
670 If OLD-POS is at the boundary of two fields, then the allowable
671 positions for NEW-POS depends on the value of the optional argument
672 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
673 constrained to the field that has the same `field' char-property
674 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
675 is non-nil, NEW-POS is constrained to the union of the two adjacent
676 fields. Additionally, if two fields are separated by another field with
677 the special value `boundary', then any point within this special field is
678 also considered to be `on the boundary'.
680 If the optional argument ONLY-IN-LINE is non-nil and constraining
681 NEW-POS would move it to a different line, NEW-POS is returned
682 unconstrained. This useful for commands that move by line, like
683 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
684 only in the case where they can still move to the right line.
686 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
687 a non-nil property of that name, then any field boundaries are ignored.
689 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
690 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
692 /* If non-zero, then the original point, before re-positioning. */
693 EMACS_INT orig_point = 0;
694 int fwd;
695 Lisp_Object prev_old, prev_new;
697 if (NILP (new_pos))
698 /* Use the current point, and afterwards, set it. */
700 orig_point = PT;
701 XSETFASTINT (new_pos, PT);
704 CHECK_NUMBER_COERCE_MARKER (new_pos);
705 CHECK_NUMBER_COERCE_MARKER (old_pos);
707 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
709 prev_old = make_number (XFASTINT (old_pos) - 1);
710 prev_new = make_number (XFASTINT (new_pos) - 1);
712 if (NILP (Vinhibit_field_text_motion)
713 && !EQ (new_pos, old_pos)
714 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
715 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
716 /* To recognize field boundaries, we must also look at the
717 previous positions; we could use `get_pos_property'
718 instead, but in itself that would fail inside non-sticky
719 fields (like comint prompts). */
720 || (XFASTINT (new_pos) > BEGV
721 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
722 || (XFASTINT (old_pos) > BEGV
723 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
724 && (NILP (inhibit_capture_property)
725 /* Field boundaries are again a problem; but now we must
726 decide the case exactly, so we need to call
727 `get_pos_property' as well. */
728 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
729 && (XFASTINT (old_pos) <= BEGV
730 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
731 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
732 /* It is possible that NEW_POS is not within the same field as
733 OLD_POS; try to move NEW_POS so that it is. */
735 EMACS_INT shortage;
736 Lisp_Object field_bound;
738 if (fwd)
739 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
740 else
741 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
743 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
744 other side of NEW_POS, which would mean that NEW_POS is
745 already acceptable, and it's not necessary to constrain it
746 to FIELD_BOUND. */
747 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
748 /* NEW_POS should be constrained, but only if either
749 ONLY_IN_LINE is nil (in which case any constraint is OK),
750 or NEW_POS and FIELD_BOUND are on the same line (in which
751 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
752 && (NILP (only_in_line)
753 /* This is the ONLY_IN_LINE case, check that NEW_POS and
754 FIELD_BOUND are on the same line by seeing whether
755 there's an intervening newline or not. */
756 || (scan_buffer ('\n',
757 XFASTINT (new_pos), XFASTINT (field_bound),
758 fwd ? -1 : 1, &shortage, 1),
759 shortage != 0)))
760 /* Constrain NEW_POS to FIELD_BOUND. */
761 new_pos = field_bound;
763 if (orig_point && XFASTINT (new_pos) != orig_point)
764 /* The NEW_POS argument was originally nil, so automatically set PT. */
765 SET_PT (XFASTINT (new_pos));
768 return new_pos;
772 DEFUN ("line-beginning-position",
773 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
774 doc: /* Return the character position of the first character on the current line.
775 With argument N not nil or 1, move forward N - 1 lines first.
776 If scan reaches end of buffer, return that position.
778 The returned position is of the first character in the logical order,
779 i.e. the one that has the smallest character position.
781 This function constrains the returned position to the current field
782 unless that would be on a different line than the original,
783 unconstrained result. If N is nil or 1, and a front-sticky field
784 starts at point, the scan stops as soon as it starts. To ignore field
785 boundaries bind `inhibit-field-text-motion' to t.
787 This function does not move point. */)
788 (Lisp_Object n)
790 EMACS_INT orig, orig_byte, end;
791 int count = SPECPDL_INDEX ();
792 specbind (Qinhibit_point_motion_hooks, Qt);
794 if (NILP (n))
795 XSETFASTINT (n, 1);
796 else
797 CHECK_NUMBER (n);
799 orig = PT;
800 orig_byte = PT_BYTE;
801 Fforward_line (make_number (XINT (n) - 1));
802 end = PT;
804 SET_PT_BOTH (orig, orig_byte);
806 unbind_to (count, Qnil);
808 /* Return END constrained to the current input field. */
809 return Fconstrain_to_field (make_number (end), make_number (orig),
810 XINT (n) != 1 ? Qt : Qnil,
811 Qt, Qnil);
814 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
815 doc: /* Return the character position of the last character on the current line.
816 With argument N not nil or 1, move forward N - 1 lines first.
817 If scan reaches end of buffer, return that position.
819 The returned position is of the last character in the logical order,
820 i.e. the character whose buffer position is the largest one.
822 This function constrains the returned position to the current field
823 unless that would be on a different line than the original,
824 unconstrained result. If N is nil or 1, and a rear-sticky field ends
825 at point, the scan stops as soon as it starts. To ignore field
826 boundaries bind `inhibit-field-text-motion' to t.
828 This function does not move point. */)
829 (Lisp_Object n)
831 EMACS_INT end_pos;
832 EMACS_INT orig = PT;
834 if (NILP (n))
835 XSETFASTINT (n, 1);
836 else
837 CHECK_NUMBER (n);
839 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
841 /* Return END_POS constrained to the current input field. */
842 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
843 Qnil, Qt, Qnil);
847 Lisp_Object
848 save_excursion_save (void)
850 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
851 == current_buffer);
853 return Fcons (Fpoint_marker (),
854 Fcons (Fcopy_marker (BVAR (current_buffer, mark), Qnil),
855 Fcons (visible ? Qt : Qnil,
856 Fcons (BVAR (current_buffer, mark_active),
857 selected_window))));
860 Lisp_Object
861 save_excursion_restore (Lisp_Object info)
863 Lisp_Object tem, tem1, omark, nmark;
864 struct gcpro gcpro1, gcpro2, gcpro3;
865 int visible_p;
867 tem = Fmarker_buffer (XCAR (info));
868 /* If buffer being returned to is now deleted, avoid error */
869 /* Otherwise could get error here while unwinding to top level
870 and crash */
871 /* In that case, Fmarker_buffer returns nil now. */
872 if (NILP (tem))
873 return Qnil;
875 omark = nmark = Qnil;
876 GCPRO3 (info, omark, nmark);
878 Fset_buffer (tem);
880 /* Point marker. */
881 tem = XCAR (info);
882 Fgoto_char (tem);
883 unchain_marker (XMARKER (tem));
885 /* Mark marker. */
886 info = XCDR (info);
887 tem = XCAR (info);
888 omark = Fmarker_position (BVAR (current_buffer, mark));
889 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
890 nmark = Fmarker_position (tem);
891 unchain_marker (XMARKER (tem));
893 /* visible */
894 info = XCDR (info);
895 visible_p = !NILP (XCAR (info));
897 #if 0 /* We used to make the current buffer visible in the selected window
898 if that was true previously. That avoids some anomalies.
899 But it creates others, and it wasn't documented, and it is simpler
900 and cleaner never to alter the window/buffer connections. */
901 tem1 = Fcar (tem);
902 if (!NILP (tem1)
903 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
904 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
905 #endif /* 0 */
907 /* Mark active */
908 info = XCDR (info);
909 tem = XCAR (info);
910 tem1 = BVAR (current_buffer, mark_active);
911 BVAR (current_buffer, mark_active) = tem;
913 /* If mark is active now, and either was not active
914 or was at a different place, run the activate hook. */
915 if (! NILP (tem))
917 if (! EQ (omark, nmark))
919 tem = intern ("activate-mark-hook");
920 Frun_hooks (1, &tem);
923 /* If mark has ceased to be active, run deactivate hook. */
924 else if (! NILP (tem1))
926 tem = intern ("deactivate-mark-hook");
927 Frun_hooks (1, &tem);
930 /* If buffer was visible in a window, and a different window was
931 selected, and the old selected window is still showing this
932 buffer, restore point in that window. */
933 tem = XCDR (info);
934 if (visible_p
935 && !EQ (tem, selected_window)
936 && (tem1 = XWINDOW (tem)->buffer,
937 (/* Window is live... */
938 BUFFERP (tem1)
939 /* ...and it shows the current buffer. */
940 && XBUFFER (tem1) == current_buffer)))
941 Fset_window_point (tem, make_number (PT));
943 UNGCPRO;
944 return Qnil;
947 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
948 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
949 Executes BODY just like `progn'.
950 The values of point, mark and the current buffer are restored
951 even in case of abnormal exit (throw or error).
952 The state of activation of the mark is also restored.
954 This construct does not save `deactivate-mark', and therefore
955 functions that change the buffer will still cause deactivation
956 of the mark at the end of the command. To prevent that, bind
957 `deactivate-mark' with `let'.
959 If you only want to save the current buffer but not point nor mark,
960 then just use `save-current-buffer', or even `with-current-buffer'.
962 usage: (save-excursion &rest BODY) */)
963 (Lisp_Object args)
965 register Lisp_Object val;
966 int count = SPECPDL_INDEX ();
968 record_unwind_protect (save_excursion_restore, save_excursion_save ());
970 val = Fprogn (args);
971 return unbind_to (count, val);
974 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
975 doc: /* Save the current buffer; execute BODY; restore the current buffer.
976 Executes BODY just like `progn'.
977 usage: (save-current-buffer &rest BODY) */)
978 (Lisp_Object args)
980 Lisp_Object val;
981 int count = SPECPDL_INDEX ();
983 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
985 val = Fprogn (args);
986 return unbind_to (count, val);
989 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
990 doc: /* Return the number of characters in the current buffer.
991 If BUFFER, return the number of characters in that buffer instead. */)
992 (Lisp_Object buffer)
994 if (NILP (buffer))
995 return make_number (Z - BEG);
996 else
998 CHECK_BUFFER (buffer);
999 return make_number (BUF_Z (XBUFFER (buffer))
1000 - BUF_BEG (XBUFFER (buffer)));
1004 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1005 doc: /* Return the minimum permissible value of point in the current buffer.
1006 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1007 (void)
1009 Lisp_Object temp;
1010 XSETFASTINT (temp, BEGV);
1011 return temp;
1014 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1015 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1016 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1017 (void)
1019 return buildmark (BEGV, BEGV_BYTE);
1022 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1023 doc: /* Return the maximum permissible value of point in the current buffer.
1024 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1025 is in effect, in which case it is less. */)
1026 (void)
1028 Lisp_Object temp;
1029 XSETFASTINT (temp, ZV);
1030 return temp;
1033 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1034 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1035 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1036 is in effect, in which case it is less. */)
1037 (void)
1039 return buildmark (ZV, ZV_BYTE);
1042 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1043 doc: /* Return the position of the gap, in the current buffer.
1044 See also `gap-size'. */)
1045 (void)
1047 Lisp_Object temp;
1048 XSETFASTINT (temp, GPT);
1049 return temp;
1052 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1053 doc: /* Return the size of the current buffer's gap.
1054 See also `gap-position'. */)
1055 (void)
1057 Lisp_Object temp;
1058 XSETFASTINT (temp, GAP_SIZE);
1059 return temp;
1062 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1063 doc: /* Return the byte position for character position POSITION.
1064 If POSITION is out of range, the value is nil. */)
1065 (Lisp_Object position)
1067 CHECK_NUMBER_COERCE_MARKER (position);
1068 if (XINT (position) < BEG || XINT (position) > Z)
1069 return Qnil;
1070 return make_number (CHAR_TO_BYTE (XINT (position)));
1073 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1074 doc: /* Return the character position for byte position BYTEPOS.
1075 If BYTEPOS is out of range, the value is nil. */)
1076 (Lisp_Object bytepos)
1078 CHECK_NUMBER (bytepos);
1079 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1080 return Qnil;
1081 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1084 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1085 doc: /* Return the character following point, as a number.
1086 At the end of the buffer or accessible region, return 0. */)
1087 (void)
1089 Lisp_Object temp;
1090 if (PT >= ZV)
1091 XSETFASTINT (temp, 0);
1092 else
1093 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1094 return temp;
1097 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1098 doc: /* Return the character preceding point, as a number.
1099 At the beginning of the buffer or accessible region, return 0. */)
1100 (void)
1102 Lisp_Object temp;
1103 if (PT <= BEGV)
1104 XSETFASTINT (temp, 0);
1105 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1107 EMACS_INT pos = PT_BYTE;
1108 DEC_POS (pos);
1109 XSETFASTINT (temp, FETCH_CHAR (pos));
1111 else
1112 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1113 return temp;
1116 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1117 doc: /* Return t if point is at the beginning of the buffer.
1118 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1119 (void)
1121 if (PT == BEGV)
1122 return Qt;
1123 return Qnil;
1126 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1127 doc: /* Return t if point is at the end of the buffer.
1128 If the buffer is narrowed, this means the end of the narrowed part. */)
1129 (void)
1131 if (PT == ZV)
1132 return Qt;
1133 return Qnil;
1136 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1137 doc: /* Return t if point is at the beginning of a line. */)
1138 (void)
1140 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1141 return Qt;
1142 return Qnil;
1145 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1146 doc: /* Return t if point is at the end of a line.
1147 `End of a line' includes point being at the end of the buffer. */)
1148 (void)
1150 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1151 return Qt;
1152 return Qnil;
1155 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1156 doc: /* Return character in current buffer at position POS.
1157 POS is an integer or a marker and defaults to point.
1158 If POS is out of range, the value is nil. */)
1159 (Lisp_Object pos)
1161 register EMACS_INT pos_byte;
1163 if (NILP (pos))
1165 pos_byte = PT_BYTE;
1166 XSETFASTINT (pos, PT);
1169 if (MARKERP (pos))
1171 pos_byte = marker_byte_position (pos);
1172 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1173 return Qnil;
1175 else
1177 CHECK_NUMBER_COERCE_MARKER (pos);
1178 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1179 return Qnil;
1181 pos_byte = CHAR_TO_BYTE (XINT (pos));
1184 return make_number (FETCH_CHAR (pos_byte));
1187 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1188 doc: /* Return character in current buffer preceding position POS.
1189 POS is an integer or a marker and defaults to point.
1190 If POS is out of range, the value is nil. */)
1191 (Lisp_Object pos)
1193 register Lisp_Object val;
1194 register EMACS_INT pos_byte;
1196 if (NILP (pos))
1198 pos_byte = PT_BYTE;
1199 XSETFASTINT (pos, PT);
1202 if (MARKERP (pos))
1204 pos_byte = marker_byte_position (pos);
1206 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1207 return Qnil;
1209 else
1211 CHECK_NUMBER_COERCE_MARKER (pos);
1213 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1214 return Qnil;
1216 pos_byte = CHAR_TO_BYTE (XINT (pos));
1219 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1221 DEC_POS (pos_byte);
1222 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1224 else
1226 pos_byte--;
1227 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1229 return val;
1232 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1233 doc: /* Return the name under which the user logged in, as a string.
1234 This is based on the effective uid, not the real uid.
1235 Also, if the environment variables LOGNAME or USER are set,
1236 that determines the value of this function.
1238 If optional argument UID is an integer or a float, return the login name
1239 of the user with that uid, or nil if there is no such user. */)
1240 (Lisp_Object uid)
1242 struct passwd *pw;
1243 uid_t id;
1245 /* Set up the user name info if we didn't do it before.
1246 (That can happen if Emacs is dumpable
1247 but you decide to run `temacs -l loadup' and not dump. */
1248 if (INTEGERP (Vuser_login_name))
1249 init_editfns ();
1251 if (NILP (uid))
1252 return Vuser_login_name;
1254 id = XFLOATINT (uid);
1255 BLOCK_INPUT;
1256 pw = getpwuid (id);
1257 UNBLOCK_INPUT;
1258 return (pw ? build_string (pw->pw_name) : Qnil);
1261 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1262 0, 0, 0,
1263 doc: /* Return the name of the user's real uid, as a string.
1264 This ignores the environment variables LOGNAME and USER, so it differs from
1265 `user-login-name' when running under `su'. */)
1266 (void)
1268 /* Set up the user name info if we didn't do it before.
1269 (That can happen if Emacs is dumpable
1270 but you decide to run `temacs -l loadup' and not dump. */
1271 if (INTEGERP (Vuser_login_name))
1272 init_editfns ();
1273 return Vuser_real_login_name;
1276 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1277 doc: /* Return the effective uid of Emacs.
1278 Value is an integer or a float, depending on the value. */)
1279 (void)
1281 /* Assignment to EMACS_INT stops GCC whining about limited range of
1282 data type. */
1283 EMACS_INT euid = geteuid ();
1285 /* Make sure we don't produce a negative UID due to signed integer
1286 overflow. */
1287 if (euid < 0)
1288 return make_float (geteuid ());
1289 return make_fixnum_or_float (euid);
1292 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1293 doc: /* Return the real uid of Emacs.
1294 Value is an integer or a float, depending on the value. */)
1295 (void)
1297 /* Assignment to EMACS_INT stops GCC whining about limited range of
1298 data type. */
1299 EMACS_INT uid = getuid ();
1301 /* Make sure we don't produce a negative UID due to signed integer
1302 overflow. */
1303 if (uid < 0)
1304 return make_float (getuid ());
1305 return make_fixnum_or_float (uid);
1308 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1309 doc: /* Return the full name of the user logged in, as a string.
1310 If the full name corresponding to Emacs's userid is not known,
1311 return "unknown".
1313 If optional argument UID is an integer or float, return the full name
1314 of the user with that uid, or nil if there is no such user.
1315 If UID is a string, return the full name of the user with that login
1316 name, or nil if there is no such user. */)
1317 (Lisp_Object uid)
1319 struct passwd *pw;
1320 register char *p, *q;
1321 Lisp_Object full;
1323 if (NILP (uid))
1324 return Vuser_full_name;
1325 else if (NUMBERP (uid))
1327 uid_t u = XFLOATINT (uid);
1328 BLOCK_INPUT;
1329 pw = getpwuid (u);
1330 UNBLOCK_INPUT;
1332 else if (STRINGP (uid))
1334 BLOCK_INPUT;
1335 pw = getpwnam (SSDATA (uid));
1336 UNBLOCK_INPUT;
1338 else
1339 error ("Invalid UID specification");
1341 if (!pw)
1342 return Qnil;
1344 p = USER_FULL_NAME;
1345 /* Chop off everything after the first comma. */
1346 q = strchr (p, ',');
1347 full = make_string (p, q ? q - p : strlen (p));
1349 #ifdef AMPERSAND_FULL_NAME
1350 p = SSDATA (full);
1351 q = strchr (p, '&');
1352 /* Substitute the login name for the &, upcasing the first character. */
1353 if (q)
1355 register char *r;
1356 Lisp_Object login;
1358 login = Fuser_login_name (make_number (pw->pw_uid));
1359 r = (char *) alloca (strlen (p) + SCHARS (login) + 1);
1360 memcpy (r, p, q - p);
1361 r[q - p] = 0;
1362 strcat (r, SSDATA (login));
1363 r[q - p] = upcase ((unsigned char) r[q - p]);
1364 strcat (r, q + 1);
1365 full = build_string (r);
1367 #endif /* AMPERSAND_FULL_NAME */
1369 return full;
1372 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1373 doc: /* Return the host name of the machine you are running on, as a string. */)
1374 (void)
1376 return Vsystem_name;
1379 const char *
1380 get_system_name (void)
1382 if (STRINGP (Vsystem_name))
1383 return SSDATA (Vsystem_name);
1384 else
1385 return "";
1388 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1389 doc: /* Return the process ID of Emacs, as an integer. */)
1390 (void)
1392 return make_number (getpid ());
1397 #ifndef TIME_T_MIN
1398 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1399 #endif
1400 #ifndef TIME_T_MAX
1401 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1402 #endif
1404 /* Report that a time value is out of range for Emacs. */
1405 static void
1406 time_overflow (void)
1408 error ("Specified time is not representable");
1411 /* Return the upper part of the time T (everything but the bottom 16 bits),
1412 making sure that it is representable. */
1413 static EMACS_INT
1414 hi_time (time_t t)
1416 time_t hi = t >> 16;
1418 /* Check for overflow, helping the compiler for common cases where
1419 no runtime check is needed, and taking care not to convert
1420 negative numbers to unsigned before comparing them. */
1421 if (! ((! TYPE_SIGNED (time_t)
1422 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1423 || MOST_NEGATIVE_FIXNUM <= hi)
1424 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1425 || hi <= MOST_POSITIVE_FIXNUM)))
1426 time_overflow ();
1428 return hi;
1431 /* Return the bottom 16 bits of the time T. */
1432 static EMACS_INT
1433 lo_time (time_t t)
1435 return t & ((1 << 16) - 1);
1438 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1439 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1440 The time is returned as a list of three integers. The first has the
1441 most significant 16 bits of the seconds, while the second has the
1442 least significant 16 bits. The third integer gives the microsecond
1443 count.
1445 The microsecond count is zero on systems that do not provide
1446 resolution finer than a second. */)
1447 (void)
1449 EMACS_TIME t;
1451 EMACS_GET_TIME (t);
1452 return list3 (make_number (hi_time (EMACS_SECS (t))),
1453 make_number (lo_time (EMACS_SECS (t))),
1454 make_number (EMACS_USECS (t)));
1457 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1458 0, 0, 0,
1459 doc: /* Return the current run time used by Emacs.
1460 The time is returned as a list of three integers. The first has the
1461 most significant 16 bits of the seconds, while the second has the
1462 least significant 16 bits. The third integer gives the microsecond
1463 count.
1465 On systems that can't determine the run time, `get-internal-run-time'
1466 does the same thing as `current-time'. The microsecond count is zero
1467 on systems that do not provide resolution finer than a second. */)
1468 (void)
1470 #ifdef HAVE_GETRUSAGE
1471 struct rusage usage;
1472 time_t secs;
1473 int usecs;
1475 if (getrusage (RUSAGE_SELF, &usage) < 0)
1476 /* This shouldn't happen. What action is appropriate? */
1477 xsignal0 (Qerror);
1479 /* Sum up user time and system time. */
1480 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1481 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1482 if (usecs >= 1000000)
1484 usecs -= 1000000;
1485 secs++;
1488 return list3 (make_number (hi_time (secs)),
1489 make_number (lo_time (secs)),
1490 make_number (usecs));
1491 #else /* ! HAVE_GETRUSAGE */
1492 #ifdef WINDOWSNT
1493 return w32_get_internal_run_time ();
1494 #else /* ! WINDOWSNT */
1495 return Fcurrent_time ();
1496 #endif /* WINDOWSNT */
1497 #endif /* HAVE_GETRUSAGE */
1501 /* Make a Lisp list that represents the time T. */
1502 Lisp_Object
1503 make_time (time_t t)
1505 return list2 (make_number (hi_time (t)),
1506 make_number (lo_time (t)));
1509 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1510 If SPECIFIED_TIME is nil, use the current time.
1511 Set *RESULT to seconds since the Epoch.
1512 If USEC is not null, set *USEC to the microseconds component.
1513 Return nonzero if successful. */
1515 lisp_time_argument (Lisp_Object specified_time, time_t *result, int *usec)
1517 if (NILP (specified_time))
1519 if (usec)
1521 EMACS_TIME t;
1523 EMACS_GET_TIME (t);
1524 *usec = EMACS_USECS (t);
1525 *result = EMACS_SECS (t);
1526 return 1;
1528 else
1529 return time (result) != -1;
1531 else
1533 Lisp_Object high, low;
1534 EMACS_INT hi;
1535 high = Fcar (specified_time);
1536 CHECK_NUMBER (high);
1537 low = Fcdr (specified_time);
1538 if (CONSP (low))
1540 if (usec)
1542 Lisp_Object usec_l = Fcdr (low);
1543 if (CONSP (usec_l))
1544 usec_l = Fcar (usec_l);
1545 if (NILP (usec_l))
1546 *usec = 0;
1547 else
1549 CHECK_NUMBER (usec_l);
1550 *usec = XINT (usec_l);
1553 low = Fcar (low);
1555 else if (usec)
1556 *usec = 0;
1557 CHECK_NUMBER (low);
1558 hi = XINT (high);
1560 /* Check for overflow, helping the compiler for common cases
1561 where no runtime check is needed, and taking care not to
1562 convert negative numbers to unsigned before comparing them. */
1563 if (! ((TYPE_SIGNED (time_t)
1564 ? (TIME_T_MIN >> 16 <= MOST_NEGATIVE_FIXNUM
1565 || TIME_T_MIN >> 16 <= hi)
1566 : 0 <= hi)
1567 && (MOST_POSITIVE_FIXNUM <= TIME_T_MAX >> 16
1568 || hi <= TIME_T_MAX >> 16)))
1569 return 0;
1571 *result = (hi << 16) + (XINT (low) & 0xffff);
1572 return 1;
1576 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1577 doc: /* Return the current time, as a float number of seconds since the epoch.
1578 If SPECIFIED-TIME is given, it is the time to convert to float
1579 instead of the current time. The argument should have the form
1580 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1581 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1582 have the form (HIGH . LOW), but this is considered obsolete.
1584 WARNING: Since the result is floating point, it may not be exact.
1585 If precise time stamps are required, use either `current-time',
1586 or (if you need time as a string) `format-time-string'. */)
1587 (Lisp_Object specified_time)
1589 time_t sec;
1590 int usec;
1592 if (! lisp_time_argument (specified_time, &sec, &usec))
1593 error ("Invalid time specification");
1595 return make_float ((sec * 1e6 + usec) / 1e6);
1598 /* Write information into buffer S of size MAXSIZE, according to the
1599 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1600 Default to Universal Time if UT is nonzero, local time otherwise.
1601 Use NS as the number of nanoseconds in the %N directive.
1602 Return the number of bytes written, not including the terminating
1603 '\0'. If S is NULL, nothing will be written anywhere; so to
1604 determine how many bytes would be written, use NULL for S and
1605 ((size_t) -1) for MAXSIZE.
1607 This function behaves like nstrftime, except it allows null
1608 bytes in FORMAT and it does not support nanoseconds. */
1609 static size_t
1610 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1611 size_t format_len, const struct tm *tp, int ut, int ns)
1613 size_t total = 0;
1615 /* Loop through all the null-terminated strings in the format
1616 argument. Normally there's just one null-terminated string, but
1617 there can be arbitrarily many, concatenated together, if the
1618 format contains '\0' bytes. nstrftime stops at the first
1619 '\0' byte so we must invoke it separately for each such string. */
1620 for (;;)
1622 size_t len;
1623 size_t result;
1625 if (s)
1626 s[0] = '\1';
1628 result = nstrftime (s, maxsize, format, tp, ut, ns);
1630 if (s)
1632 if (result == 0 && s[0] != '\0')
1633 return 0;
1634 s += result + 1;
1637 maxsize -= result + 1;
1638 total += result;
1639 len = strlen (format);
1640 if (len == format_len)
1641 return total;
1642 total++;
1643 format += len + 1;
1644 format_len -= len + 1;
1648 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1649 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1650 TIME is specified as (HIGH LOW . IGNORED), as returned by
1651 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1652 is also still accepted.
1653 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1654 as Universal Time; nil means describe TIME in the local time zone.
1655 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1656 by text that describes the specified date and time in TIME:
1658 %Y is the year, %y within the century, %C the century.
1659 %G is the year corresponding to the ISO week, %g within the century.
1660 %m is the numeric month.
1661 %b and %h are the locale's abbreviated month name, %B the full name.
1662 %d is the day of the month, zero-padded, %e is blank-padded.
1663 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1664 %a is the locale's abbreviated name of the day of week, %A the full name.
1665 %U is the week number starting on Sunday, %W starting on Monday,
1666 %V according to ISO 8601.
1667 %j is the day of the year.
1669 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1670 only blank-padded, %l is like %I blank-padded.
1671 %p is the locale's equivalent of either AM or PM.
1672 %M is the minute.
1673 %S is the second.
1674 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1675 %Z is the time zone name, %z is the numeric form.
1676 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1678 %c is the locale's date and time format.
1679 %x is the locale's "preferred" date format.
1680 %D is like "%m/%d/%y".
1682 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1683 %X is the locale's "preferred" time format.
1685 Finally, %n is a newline, %t is a tab, %% is a literal %.
1687 Certain flags and modifiers are available with some format controls.
1688 The flags are `_', `-', `^' and `#'. For certain characters X,
1689 %_X is like %X, but padded with blanks; %-X is like %X,
1690 but without padding. %^X is like %X, but with all textual
1691 characters up-cased; %#X is like %X, but with letter-case of
1692 all textual characters reversed.
1693 %NX (where N stands for an integer) is like %X,
1694 but takes up at least N (a number) positions.
1695 The modifiers are `E' and `O'. For certain characters X,
1696 %EX is a locale's alternative version of %X;
1697 %OX is like %X, but uses the locale's number symbols.
1699 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1700 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1702 time_t value;
1703 int size;
1704 int usec;
1705 int ns;
1706 struct tm *tm;
1707 int ut = ! NILP (universal);
1709 CHECK_STRING (format_string);
1711 if (! (lisp_time_argument (timeval, &value, &usec)
1712 && 0 <= usec && usec < 1000000))
1713 error ("Invalid time specification");
1714 ns = usec * 1000;
1716 format_string = code_convert_string_norecord (format_string,
1717 Vlocale_coding_system, 1);
1719 /* This is probably enough. */
1720 size = SBYTES (format_string) * 6 + 50;
1722 BLOCK_INPUT;
1723 tm = ut ? gmtime (&value) : localtime (&value);
1724 UNBLOCK_INPUT;
1725 if (! tm)
1726 time_overflow ();
1728 synchronize_system_time_locale ();
1730 while (1)
1732 char *buf = (char *) alloca (size + 1);
1733 int result;
1735 buf[0] = '\1';
1736 BLOCK_INPUT;
1737 result = emacs_nmemftime (buf, size, SSDATA (format_string),
1738 SBYTES (format_string),
1739 tm, ut, ns);
1740 UNBLOCK_INPUT;
1741 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1742 return code_convert_string_norecord (make_unibyte_string (buf, result),
1743 Vlocale_coding_system, 0);
1745 /* If buffer was too small, make it bigger and try again. */
1746 BLOCK_INPUT;
1747 result = emacs_nmemftime (NULL, (size_t) -1,
1748 SSDATA (format_string),
1749 SBYTES (format_string),
1750 tm, ut, ns);
1751 UNBLOCK_INPUT;
1752 size = result + 1;
1756 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1757 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1758 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1759 as from `current-time' and `file-attributes', or nil to use the
1760 current time. The obsolete form (HIGH . LOW) is also still accepted.
1761 The list has the following nine members: SEC is an integer between 0
1762 and 60; SEC is 60 for a leap second, which only some operating systems
1763 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1764 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1765 integer between 1 and 12. YEAR is an integer indicating the
1766 four-digit year. DOW is the day of week, an integer between 0 and 6,
1767 where 0 is Sunday. DST is t if daylight saving time is in effect,
1768 otherwise nil. ZONE is an integer indicating the number of seconds
1769 east of Greenwich. (Note that Common Lisp has different meanings for
1770 DOW and ZONE.) */)
1771 (Lisp_Object specified_time)
1773 time_t time_spec;
1774 struct tm save_tm;
1775 struct tm *decoded_time;
1776 Lisp_Object list_args[9];
1778 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1779 error ("Invalid time specification");
1781 BLOCK_INPUT;
1782 decoded_time = localtime (&time_spec);
1783 UNBLOCK_INPUT;
1784 if (! (decoded_time
1785 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= decoded_time->tm_year
1786 && decoded_time->tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1787 time_overflow ();
1788 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1789 XSETFASTINT (list_args[1], decoded_time->tm_min);
1790 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1791 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1792 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1793 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1794 cast below avoids overflow in int arithmetics. */
1795 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1796 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1797 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1799 /* Make a copy, in case gmtime modifies the struct. */
1800 save_tm = *decoded_time;
1801 BLOCK_INPUT;
1802 decoded_time = gmtime (&time_spec);
1803 UNBLOCK_INPUT;
1804 if (decoded_time == 0)
1805 list_args[8] = Qnil;
1806 else
1807 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1808 return Flist (9, list_args);
1811 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1812 the result is representable as an int. Assume OFFSET is small and
1813 nonnegative. */
1814 static int
1815 check_tm_member (Lisp_Object obj, int offset)
1817 EMACS_INT n;
1818 CHECK_NUMBER (obj);
1819 n = XINT (obj);
1820 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1821 time_overflow ();
1822 return n - offset;
1825 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1826 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1827 This is the reverse operation of `decode-time', which see.
1828 ZONE defaults to the current time zone rule. This can
1829 be a string or t (as from `set-time-zone-rule'), or it can be a list
1830 \(as from `current-time-zone') or an integer (as from `decode-time')
1831 applied without consideration for daylight saving time.
1833 You can pass more than 7 arguments; then the first six arguments
1834 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1835 The intervening arguments are ignored.
1836 This feature lets (apply 'encode-time (decode-time ...)) work.
1838 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1839 for example, a DAY of 0 means the day preceding the given month.
1840 Year numbers less than 100 are treated just like other year numbers.
1841 If you want them to stand for years in this century, you must do that yourself.
1843 Years before 1970 are not guaranteed to work. On some systems,
1844 year values as low as 1901 do work.
1846 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1847 (ptrdiff_t nargs, Lisp_Object *args)
1849 time_t value;
1850 struct tm tm;
1851 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1853 tm.tm_sec = check_tm_member (args[0], 0);
1854 tm.tm_min = check_tm_member (args[1], 0);
1855 tm.tm_hour = check_tm_member (args[2], 0);
1856 tm.tm_mday = check_tm_member (args[3], 0);
1857 tm.tm_mon = check_tm_member (args[4], 1);
1858 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1859 tm.tm_isdst = -1;
1861 if (CONSP (zone))
1862 zone = Fcar (zone);
1863 if (NILP (zone))
1865 BLOCK_INPUT;
1866 value = mktime (&tm);
1867 UNBLOCK_INPUT;
1869 else
1871 char tzbuf[100];
1872 const char *tzstring;
1873 char **oldenv = environ, **newenv;
1875 if (EQ (zone, Qt))
1876 tzstring = "UTC0";
1877 else if (STRINGP (zone))
1878 tzstring = SSDATA (zone);
1879 else if (INTEGERP (zone))
1881 int abszone = eabs (XINT (zone));
1882 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1883 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1884 tzstring = tzbuf;
1886 else
1887 error ("Invalid time zone specification");
1889 /* Set TZ before calling mktime; merely adjusting mktime's returned
1890 value doesn't suffice, since that would mishandle leap seconds. */
1891 set_time_zone_rule (tzstring);
1893 BLOCK_INPUT;
1894 value = mktime (&tm);
1895 UNBLOCK_INPUT;
1897 /* Restore TZ to previous value. */
1898 newenv = environ;
1899 environ = oldenv;
1900 xfree (newenv);
1901 #ifdef LOCALTIME_CACHE
1902 tzset ();
1903 #endif
1906 if (value == (time_t) -1)
1907 time_overflow ();
1909 return make_time (value);
1912 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1913 doc: /* Return the current local time, as a human-readable string.
1914 Programs can use this function to decode a time,
1915 since the number of columns in each field is fixed
1916 if the year is in the range 1000-9999.
1917 The format is `Sun Sep 16 01:03:52 1973'.
1918 However, see also the functions `decode-time' and `format-time-string'
1919 which provide a much more powerful and general facility.
1921 If SPECIFIED-TIME is given, it is a time to format instead of the
1922 current time. The argument should have the form (HIGH LOW . IGNORED).
1923 Thus, you can use times obtained from `current-time' and from
1924 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1925 but this is considered obsolete. */)
1926 (Lisp_Object specified_time)
1928 time_t value;
1929 struct tm *tm;
1930 register char *tem;
1932 if (! lisp_time_argument (specified_time, &value, NULL))
1933 error ("Invalid time specification");
1935 /* Convert to a string, checking for out-of-range time stamps.
1936 Don't use 'ctime', as that might dump core if VALUE is out of
1937 range. */
1938 BLOCK_INPUT;
1939 tm = localtime (&value);
1940 UNBLOCK_INPUT;
1941 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1942 time_overflow ();
1944 /* Remove the trailing newline. */
1945 tem[strlen (tem) - 1] = '\0';
1947 return build_string (tem);
1950 /* Yield A - B, measured in seconds.
1951 This function is copied from the GNU C Library. */
1952 static int
1953 tm_diff (struct tm *a, struct tm *b)
1955 /* Compute intervening leap days correctly even if year is negative.
1956 Take care to avoid int overflow in leap day calculations,
1957 but it's OK to assume that A and B are close to each other. */
1958 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1959 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1960 int a100 = a4 / 25 - (a4 % 25 < 0);
1961 int b100 = b4 / 25 - (b4 % 25 < 0);
1962 int a400 = a100 >> 2;
1963 int b400 = b100 >> 2;
1964 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1965 int years = a->tm_year - b->tm_year;
1966 int days = (365 * years + intervening_leap_days
1967 + (a->tm_yday - b->tm_yday));
1968 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1969 + (a->tm_min - b->tm_min))
1970 + (a->tm_sec - b->tm_sec));
1973 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1974 doc: /* Return the offset and name for the local time zone.
1975 This returns a list of the form (OFFSET NAME).
1976 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1977 A negative value means west of Greenwich.
1978 NAME is a string giving the name of the time zone.
1979 If SPECIFIED-TIME is given, the time zone offset is determined from it
1980 instead of using the current time. The argument should have the form
1981 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1982 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1983 have the form (HIGH . LOW), but this is considered obsolete.
1985 Some operating systems cannot provide all this information to Emacs;
1986 in this case, `current-time-zone' returns a list containing nil for
1987 the data it can't find. */)
1988 (Lisp_Object specified_time)
1990 time_t value;
1991 struct tm *t;
1992 struct tm gmt;
1994 if (!lisp_time_argument (specified_time, &value, NULL))
1995 t = NULL;
1996 else
1998 BLOCK_INPUT;
1999 t = gmtime (&value);
2000 if (t)
2002 gmt = *t;
2003 t = localtime (&value);
2005 UNBLOCK_INPUT;
2008 if (t)
2010 int offset = tm_diff (t, &gmt);
2011 char *s = 0;
2012 char buf[6];
2014 #ifdef HAVE_TM_ZONE
2015 if (t->tm_zone)
2016 s = (char *)t->tm_zone;
2017 #else /* not HAVE_TM_ZONE */
2018 #ifdef HAVE_TZNAME
2019 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2020 s = tzname[t->tm_isdst];
2021 #endif
2022 #endif /* not HAVE_TM_ZONE */
2024 if (!s)
2026 /* No local time zone name is available; use "+-NNNN" instead. */
2027 int am = (offset < 0 ? -offset : offset) / 60;
2028 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2029 s = buf;
2032 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2034 else
2035 return Fmake_list (make_number (2), Qnil);
2038 /* This holds the value of `environ' produced by the previous
2039 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2040 has never been called. */
2041 static char **environbuf;
2043 /* This holds the startup value of the TZ environment variable so it
2044 can be restored if the user calls set-time-zone-rule with a nil
2045 argument. */
2046 static char *initial_tz;
2048 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2049 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2050 If TZ is nil, use implementation-defined default time zone information.
2051 If TZ is t, use Universal Time. */)
2052 (Lisp_Object tz)
2054 const char *tzstring;
2056 /* When called for the first time, save the original TZ. */
2057 if (!environbuf)
2058 initial_tz = (char *) getenv ("TZ");
2060 if (NILP (tz))
2061 tzstring = initial_tz;
2062 else if (EQ (tz, Qt))
2063 tzstring = "UTC0";
2064 else
2066 CHECK_STRING (tz);
2067 tzstring = SSDATA (tz);
2070 set_time_zone_rule (tzstring);
2071 free (environbuf);
2072 environbuf = environ;
2074 return Qnil;
2077 #ifdef LOCALTIME_CACHE
2079 /* These two values are known to load tz files in buggy implementations,
2080 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2081 Their values shouldn't matter in non-buggy implementations.
2082 We don't use string literals for these strings,
2083 since if a string in the environment is in readonly
2084 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2085 See Sun bugs 1113095 and 1114114, ``Timezone routines
2086 improperly modify environment''. */
2088 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2089 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2091 #endif
2093 /* Set the local time zone rule to TZSTRING.
2094 This allocates memory into `environ', which it is the caller's
2095 responsibility to free. */
2097 void
2098 set_time_zone_rule (const char *tzstring)
2100 int envptrs;
2101 char **from, **to, **newenv;
2103 /* Make the ENVIRON vector longer with room for TZSTRING. */
2104 for (from = environ; *from; from++)
2105 continue;
2106 envptrs = from - environ + 2;
2107 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2108 + (tzstring ? strlen (tzstring) + 4 : 0));
2110 /* Add TZSTRING to the end of environ, as a value for TZ. */
2111 if (tzstring)
2113 char *t = (char *) (to + envptrs);
2114 strcpy (t, "TZ=");
2115 strcat (t, tzstring);
2116 *to++ = t;
2119 /* Copy the old environ vector elements into NEWENV,
2120 but don't copy the TZ variable.
2121 So we have only one definition of TZ, which came from TZSTRING. */
2122 for (from = environ; *from; from++)
2123 if (strncmp (*from, "TZ=", 3) != 0)
2124 *to++ = *from;
2125 *to = 0;
2127 environ = newenv;
2129 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2130 the TZ variable is stored. If we do not have a TZSTRING,
2131 TO points to the vector slot which has the terminating null. */
2133 #ifdef LOCALTIME_CACHE
2135 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2136 "US/Pacific" that loads a tz file, then changes to a value like
2137 "XXX0" that does not load a tz file, and then changes back to
2138 its original value, the last change is (incorrectly) ignored.
2139 Also, if TZ changes twice in succession to values that do
2140 not load a tz file, tzset can dump core (see Sun bug#1225179).
2141 The following code works around these bugs. */
2143 if (tzstring)
2145 /* Temporarily set TZ to a value that loads a tz file
2146 and that differs from tzstring. */
2147 char *tz = *newenv;
2148 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2149 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2150 tzset ();
2151 *newenv = tz;
2153 else
2155 /* The implied tzstring is unknown, so temporarily set TZ to
2156 two different values that each load a tz file. */
2157 *to = set_time_zone_rule_tz1;
2158 to[1] = 0;
2159 tzset ();
2160 *to = set_time_zone_rule_tz2;
2161 tzset ();
2162 *to = 0;
2165 /* Now TZ has the desired value, and tzset can be invoked safely. */
2168 tzset ();
2169 #endif
2172 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2173 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2174 type of object is Lisp_String). INHERIT is passed to
2175 INSERT_FROM_STRING_FUNC as the last argument. */
2177 static void
2178 general_insert_function (void (*insert_func)
2179 (const char *, EMACS_INT),
2180 void (*insert_from_string_func)
2181 (Lisp_Object, EMACS_INT, EMACS_INT,
2182 EMACS_INT, EMACS_INT, int),
2183 int inherit, ptrdiff_t nargs, Lisp_Object *args)
2185 ptrdiff_t argnum;
2186 register Lisp_Object val;
2188 for (argnum = 0; argnum < nargs; argnum++)
2190 val = args[argnum];
2191 if (CHARACTERP (val))
2193 int c = XFASTINT (val);
2194 unsigned char str[MAX_MULTIBYTE_LENGTH];
2195 int len;
2197 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2198 len = CHAR_STRING (c, str);
2199 else
2201 str[0] = ASCII_CHAR_P (c) ? c : multibyte_char_to_unibyte (c);
2202 len = 1;
2204 (*insert_func) ((char *) str, len);
2206 else if (STRINGP (val))
2208 (*insert_from_string_func) (val, 0, 0,
2209 SCHARS (val),
2210 SBYTES (val),
2211 inherit);
2213 else
2214 wrong_type_argument (Qchar_or_string_p, val);
2218 void
2219 insert1 (Lisp_Object arg)
2221 Finsert (1, &arg);
2225 /* Callers passing one argument to Finsert need not gcpro the
2226 argument "array", since the only element of the array will
2227 not be used after calling insert or insert_from_string, so
2228 we don't care if it gets trashed. */
2230 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2231 doc: /* Insert the arguments, either strings or characters, at point.
2232 Point and before-insertion markers move forward to end up
2233 after the inserted text.
2234 Any other markers at the point of insertion remain before the text.
2236 If the current buffer is multibyte, unibyte strings are converted
2237 to multibyte for insertion (see `string-make-multibyte').
2238 If the current buffer is unibyte, multibyte strings are converted
2239 to unibyte for insertion (see `string-make-unibyte').
2241 When operating on binary data, it may be necessary to preserve the
2242 original bytes of a unibyte string when inserting it into a multibyte
2243 buffer; to accomplish this, apply `string-as-multibyte' to the string
2244 and insert the result.
2246 usage: (insert &rest ARGS) */)
2247 (ptrdiff_t nargs, Lisp_Object *args)
2249 general_insert_function (insert, insert_from_string, 0, nargs, args);
2250 return Qnil;
2253 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2254 0, MANY, 0,
2255 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2256 Point and before-insertion markers move forward to end up
2257 after the inserted text.
2258 Any other markers at the point of insertion remain before the text.
2260 If the current buffer is multibyte, unibyte strings are converted
2261 to multibyte for insertion (see `unibyte-char-to-multibyte').
2262 If the current buffer is unibyte, multibyte strings are converted
2263 to unibyte for insertion.
2265 usage: (insert-and-inherit &rest ARGS) */)
2266 (ptrdiff_t nargs, Lisp_Object *args)
2268 general_insert_function (insert_and_inherit, insert_from_string, 1,
2269 nargs, args);
2270 return Qnil;
2273 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2274 doc: /* Insert strings or characters at point, relocating markers after the text.
2275 Point and markers move forward to end up after the inserted text.
2277 If the current buffer is multibyte, unibyte strings are converted
2278 to multibyte for insertion (see `unibyte-char-to-multibyte').
2279 If the current buffer is unibyte, multibyte strings are converted
2280 to unibyte for insertion.
2282 usage: (insert-before-markers &rest ARGS) */)
2283 (ptrdiff_t nargs, Lisp_Object *args)
2285 general_insert_function (insert_before_markers,
2286 insert_from_string_before_markers, 0,
2287 nargs, args);
2288 return Qnil;
2291 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2292 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2293 doc: /* Insert text at point, relocating markers and inheriting properties.
2294 Point and markers move forward to end up after the inserted text.
2296 If the current buffer is multibyte, unibyte strings are converted
2297 to multibyte for insertion (see `unibyte-char-to-multibyte').
2298 If the current buffer is unibyte, multibyte strings are converted
2299 to unibyte for insertion.
2301 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2302 (ptrdiff_t nargs, Lisp_Object *args)
2304 general_insert_function (insert_before_markers_and_inherit,
2305 insert_from_string_before_markers, 1,
2306 nargs, args);
2307 return Qnil;
2310 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2311 doc: /* Insert COUNT copies of CHARACTER.
2312 Point, and before-insertion markers, are relocated as in the function `insert'.
2313 The optional third arg INHERIT, if non-nil, says to inherit text properties
2314 from adjoining text, if those properties are sticky. */)
2315 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2317 int i, stringlen;
2318 register EMACS_INT n;
2319 int c, len;
2320 unsigned char str[MAX_MULTIBYTE_LENGTH];
2321 char string[4000];
2323 CHECK_CHARACTER (character);
2324 CHECK_NUMBER (count);
2325 c = XFASTINT (character);
2327 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2328 len = CHAR_STRING (c, str);
2329 else
2330 str[0] = c, len = 1;
2331 if (XINT (count) <= 0)
2332 return Qnil;
2333 if (BUF_BYTES_MAX / len < XINT (count))
2334 buffer_overflow ();
2335 n = XINT (count) * len;
2336 stringlen = min (n, sizeof string - sizeof string % len);
2337 for (i = 0; i < stringlen; i++)
2338 string[i] = str[i % len];
2339 while (n > stringlen)
2341 QUIT;
2342 if (!NILP (inherit))
2343 insert_and_inherit (string, stringlen);
2344 else
2345 insert (string, stringlen);
2346 n -= stringlen;
2348 if (!NILP (inherit))
2349 insert_and_inherit (string, n);
2350 else
2351 insert (string, n);
2352 return Qnil;
2355 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2356 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2357 Both arguments are required.
2358 BYTE is a number of the range 0..255.
2360 If BYTE is 128..255 and the current buffer is multibyte, the
2361 corresponding eight-bit character is inserted.
2363 Point, and before-insertion markers, are relocated as in the function `insert'.
2364 The optional third arg INHERIT, if non-nil, says to inherit text properties
2365 from adjoining text, if those properties are sticky. */)
2366 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2368 CHECK_NUMBER (byte);
2369 if (XINT (byte) < 0 || XINT (byte) > 255)
2370 args_out_of_range_3 (byte, make_number (0), make_number (255));
2371 if (XINT (byte) >= 128
2372 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2373 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2374 return Finsert_char (byte, count, inherit);
2378 /* Making strings from buffer contents. */
2380 /* Return a Lisp_String containing the text of the current buffer from
2381 START to END. If text properties are in use and the current buffer
2382 has properties in the range specified, the resulting string will also
2383 have them, if PROPS is nonzero.
2385 We don't want to use plain old make_string here, because it calls
2386 make_uninit_string, which can cause the buffer arena to be
2387 compacted. make_string has no way of knowing that the data has
2388 been moved, and thus copies the wrong data into the string. This
2389 doesn't effect most of the other users of make_string, so it should
2390 be left as is. But we should use this function when conjuring
2391 buffer substrings. */
2393 Lisp_Object
2394 make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
2396 EMACS_INT start_byte = CHAR_TO_BYTE (start);
2397 EMACS_INT end_byte = CHAR_TO_BYTE (end);
2399 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2402 /* Return a Lisp_String containing the text of the current buffer from
2403 START / START_BYTE to END / END_BYTE.
2405 If text properties are in use and the current buffer
2406 has properties in the range specified, the resulting string will also
2407 have them, if PROPS is nonzero.
2409 We don't want to use plain old make_string here, because it calls
2410 make_uninit_string, which can cause the buffer arena to be
2411 compacted. make_string has no way of knowing that the data has
2412 been moved, and thus copies the wrong data into the string. This
2413 doesn't effect most of the other users of make_string, so it should
2414 be left as is. But we should use this function when conjuring
2415 buffer substrings. */
2417 Lisp_Object
2418 make_buffer_string_both (EMACS_INT start, EMACS_INT start_byte,
2419 EMACS_INT end, EMACS_INT end_byte, int props)
2421 Lisp_Object result, tem, tem1;
2423 if (start < GPT && GPT < end)
2424 move_gap (start);
2426 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2427 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2428 else
2429 result = make_uninit_string (end - start);
2430 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2432 /* If desired, update and copy the text properties. */
2433 if (props)
2435 update_buffer_properties (start, end);
2437 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2438 tem1 = Ftext_properties_at (make_number (start), Qnil);
2440 if (XINT (tem) != end || !NILP (tem1))
2441 copy_intervals_to_string (result, current_buffer, start,
2442 end - start);
2445 return result;
2448 /* Call Vbuffer_access_fontify_functions for the range START ... END
2449 in the current buffer, if necessary. */
2451 static void
2452 update_buffer_properties (EMACS_INT start, EMACS_INT end)
2454 /* If this buffer has some access functions,
2455 call them, specifying the range of the buffer being accessed. */
2456 if (!NILP (Vbuffer_access_fontify_functions))
2458 Lisp_Object args[3];
2459 Lisp_Object tem;
2461 args[0] = Qbuffer_access_fontify_functions;
2462 XSETINT (args[1], start);
2463 XSETINT (args[2], end);
2465 /* But don't call them if we can tell that the work
2466 has already been done. */
2467 if (!NILP (Vbuffer_access_fontified_property))
2469 tem = Ftext_property_any (args[1], args[2],
2470 Vbuffer_access_fontified_property,
2471 Qnil, Qnil);
2472 if (! NILP (tem))
2473 Frun_hook_with_args (3, args);
2475 else
2476 Frun_hook_with_args (3, args);
2480 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2481 doc: /* Return the contents of part of the current buffer as a string.
2482 The two arguments START and END are character positions;
2483 they can be in either order.
2484 The string returned is multibyte if the buffer is multibyte.
2486 This function copies the text properties of that part of the buffer
2487 into the result string; if you don't want the text properties,
2488 use `buffer-substring-no-properties' instead. */)
2489 (Lisp_Object start, Lisp_Object end)
2491 register EMACS_INT b, e;
2493 validate_region (&start, &end);
2494 b = XINT (start);
2495 e = XINT (end);
2497 return make_buffer_string (b, e, 1);
2500 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2501 Sbuffer_substring_no_properties, 2, 2, 0,
2502 doc: /* Return the characters of part of the buffer, without the text properties.
2503 The two arguments START and END are character positions;
2504 they can be in either order. */)
2505 (Lisp_Object start, Lisp_Object end)
2507 register EMACS_INT b, e;
2509 validate_region (&start, &end);
2510 b = XINT (start);
2511 e = XINT (end);
2513 return make_buffer_string (b, e, 0);
2516 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2517 doc: /* Return the contents of the current buffer as a string.
2518 If narrowing is in effect, this function returns only the visible part
2519 of the buffer. */)
2520 (void)
2522 return make_buffer_string (BEGV, ZV, 1);
2525 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2526 1, 3, 0,
2527 doc: /* Insert before point a substring of the contents of BUFFER.
2528 BUFFER may be a buffer or a buffer name.
2529 Arguments START and END are character positions specifying the substring.
2530 They default to the values of (point-min) and (point-max) in BUFFER. */)
2531 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2533 register EMACS_INT b, e, temp;
2534 register struct buffer *bp, *obuf;
2535 Lisp_Object buf;
2537 buf = Fget_buffer (buffer);
2538 if (NILP (buf))
2539 nsberror (buffer);
2540 bp = XBUFFER (buf);
2541 if (NILP (BVAR (bp, name)))
2542 error ("Selecting deleted buffer");
2544 if (NILP (start))
2545 b = BUF_BEGV (bp);
2546 else
2548 CHECK_NUMBER_COERCE_MARKER (start);
2549 b = XINT (start);
2551 if (NILP (end))
2552 e = BUF_ZV (bp);
2553 else
2555 CHECK_NUMBER_COERCE_MARKER (end);
2556 e = XINT (end);
2559 if (b > e)
2560 temp = b, b = e, e = temp;
2562 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2563 args_out_of_range (start, end);
2565 obuf = current_buffer;
2566 set_buffer_internal_1 (bp);
2567 update_buffer_properties (b, e);
2568 set_buffer_internal_1 (obuf);
2570 insert_from_buffer (bp, b, e - b, 0);
2571 return Qnil;
2574 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2575 6, 6, 0,
2576 doc: /* Compare two substrings of two buffers; return result as number.
2577 the value is -N if first string is less after N-1 chars,
2578 +N if first string is greater after N-1 chars, or 0 if strings match.
2579 Each substring is represented as three arguments: BUFFER, START and END.
2580 That makes six args in all, three for each substring.
2582 The value of `case-fold-search' in the current buffer
2583 determines whether case is significant or ignored. */)
2584 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2586 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2587 register struct buffer *bp1, *bp2;
2588 register Lisp_Object trt
2589 = (!NILP (BVAR (current_buffer, case_fold_search))
2590 ? BVAR (current_buffer, case_canon_table) : Qnil);
2591 EMACS_INT chars = 0;
2592 EMACS_INT i1, i2, i1_byte, i2_byte;
2594 /* Find the first buffer and its substring. */
2596 if (NILP (buffer1))
2597 bp1 = current_buffer;
2598 else
2600 Lisp_Object buf1;
2601 buf1 = Fget_buffer (buffer1);
2602 if (NILP (buf1))
2603 nsberror (buffer1);
2604 bp1 = XBUFFER (buf1);
2605 if (NILP (BVAR (bp1, name)))
2606 error ("Selecting deleted buffer");
2609 if (NILP (start1))
2610 begp1 = BUF_BEGV (bp1);
2611 else
2613 CHECK_NUMBER_COERCE_MARKER (start1);
2614 begp1 = XINT (start1);
2616 if (NILP (end1))
2617 endp1 = BUF_ZV (bp1);
2618 else
2620 CHECK_NUMBER_COERCE_MARKER (end1);
2621 endp1 = XINT (end1);
2624 if (begp1 > endp1)
2625 temp = begp1, begp1 = endp1, endp1 = temp;
2627 if (!(BUF_BEGV (bp1) <= begp1
2628 && begp1 <= endp1
2629 && endp1 <= BUF_ZV (bp1)))
2630 args_out_of_range (start1, end1);
2632 /* Likewise for second substring. */
2634 if (NILP (buffer2))
2635 bp2 = current_buffer;
2636 else
2638 Lisp_Object buf2;
2639 buf2 = Fget_buffer (buffer2);
2640 if (NILP (buf2))
2641 nsberror (buffer2);
2642 bp2 = XBUFFER (buf2);
2643 if (NILP (BVAR (bp2, name)))
2644 error ("Selecting deleted buffer");
2647 if (NILP (start2))
2648 begp2 = BUF_BEGV (bp2);
2649 else
2651 CHECK_NUMBER_COERCE_MARKER (start2);
2652 begp2 = XINT (start2);
2654 if (NILP (end2))
2655 endp2 = BUF_ZV (bp2);
2656 else
2658 CHECK_NUMBER_COERCE_MARKER (end2);
2659 endp2 = XINT (end2);
2662 if (begp2 > endp2)
2663 temp = begp2, begp2 = endp2, endp2 = temp;
2665 if (!(BUF_BEGV (bp2) <= begp2
2666 && begp2 <= endp2
2667 && endp2 <= BUF_ZV (bp2)))
2668 args_out_of_range (start2, end2);
2670 i1 = begp1;
2671 i2 = begp2;
2672 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2673 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2675 while (i1 < endp1 && i2 < endp2)
2677 /* When we find a mismatch, we must compare the
2678 characters, not just the bytes. */
2679 int c1, c2;
2681 QUIT;
2683 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2685 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2686 BUF_INC_POS (bp1, i1_byte);
2687 i1++;
2689 else
2691 c1 = BUF_FETCH_BYTE (bp1, i1);
2692 MAKE_CHAR_MULTIBYTE (c1);
2693 i1++;
2696 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2698 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2699 BUF_INC_POS (bp2, i2_byte);
2700 i2++;
2702 else
2704 c2 = BUF_FETCH_BYTE (bp2, i2);
2705 MAKE_CHAR_MULTIBYTE (c2);
2706 i2++;
2709 if (!NILP (trt))
2711 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2712 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2714 if (c1 < c2)
2715 return make_number (- 1 - chars);
2716 if (c1 > c2)
2717 return make_number (chars + 1);
2719 chars++;
2722 /* The strings match as far as they go.
2723 If one is shorter, that one is less. */
2724 if (chars < endp1 - begp1)
2725 return make_number (chars + 1);
2726 else if (chars < endp2 - begp2)
2727 return make_number (- chars - 1);
2729 /* Same length too => they are equal. */
2730 return make_number (0);
2733 static Lisp_Object
2734 subst_char_in_region_unwind (Lisp_Object arg)
2736 return BVAR (current_buffer, undo_list) = arg;
2739 static Lisp_Object
2740 subst_char_in_region_unwind_1 (Lisp_Object arg)
2742 return BVAR (current_buffer, filename) = arg;
2745 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2746 Ssubst_char_in_region, 4, 5, 0,
2747 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2748 If optional arg NOUNDO is non-nil, don't record this change for undo
2749 and don't mark the buffer as really changed.
2750 Both characters must have the same length of multi-byte form. */)
2751 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2753 register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
2754 /* Keep track of the first change in the buffer:
2755 if 0 we haven't found it yet.
2756 if < 0 we've found it and we've run the before-change-function.
2757 if > 0 we've actually performed it and the value is its position. */
2758 EMACS_INT changed = 0;
2759 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2760 unsigned char *p;
2761 int count = SPECPDL_INDEX ();
2762 #define COMBINING_NO 0
2763 #define COMBINING_BEFORE 1
2764 #define COMBINING_AFTER 2
2765 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2766 int maybe_byte_combining = COMBINING_NO;
2767 EMACS_INT last_changed = 0;
2768 int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2769 int fromc, toc;
2771 restart:
2773 validate_region (&start, &end);
2774 CHECK_CHARACTER (fromchar);
2775 CHECK_CHARACTER (tochar);
2776 fromc = XFASTINT (fromchar);
2777 toc = XFASTINT (tochar);
2779 if (multibyte_p)
2781 len = CHAR_STRING (fromc, fromstr);
2782 if (CHAR_STRING (toc, tostr) != len)
2783 error ("Characters in `subst-char-in-region' have different byte-lengths");
2784 if (!ASCII_BYTE_P (*tostr))
2786 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2787 complete multibyte character, it may be combined with the
2788 after bytes. If it is in the range 0xA0..0xFF, it may be
2789 combined with the before and after bytes. */
2790 if (!CHAR_HEAD_P (*tostr))
2791 maybe_byte_combining = COMBINING_BOTH;
2792 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2793 maybe_byte_combining = COMBINING_AFTER;
2796 else
2798 len = 1;
2799 fromstr[0] = fromc;
2800 tostr[0] = toc;
2803 pos = XINT (start);
2804 pos_byte = CHAR_TO_BYTE (pos);
2805 stop = CHAR_TO_BYTE (XINT (end));
2806 end_byte = stop;
2808 /* If we don't want undo, turn off putting stuff on the list.
2809 That's faster than getting rid of things,
2810 and it prevents even the entry for a first change.
2811 Also inhibit locking the file. */
2812 if (!changed && !NILP (noundo))
2814 record_unwind_protect (subst_char_in_region_unwind,
2815 BVAR (current_buffer, undo_list));
2816 BVAR (current_buffer, undo_list) = Qt;
2817 /* Don't do file-locking. */
2818 record_unwind_protect (subst_char_in_region_unwind_1,
2819 BVAR (current_buffer, filename));
2820 BVAR (current_buffer, filename) = Qnil;
2823 if (pos_byte < GPT_BYTE)
2824 stop = min (stop, GPT_BYTE);
2825 while (1)
2827 EMACS_INT pos_byte_next = pos_byte;
2829 if (pos_byte >= stop)
2831 if (pos_byte >= end_byte) break;
2832 stop = end_byte;
2834 p = BYTE_POS_ADDR (pos_byte);
2835 if (multibyte_p)
2836 INC_POS (pos_byte_next);
2837 else
2838 ++pos_byte_next;
2839 if (pos_byte_next - pos_byte == len
2840 && p[0] == fromstr[0]
2841 && (len == 1
2842 || (p[1] == fromstr[1]
2843 && (len == 2 || (p[2] == fromstr[2]
2844 && (len == 3 || p[3] == fromstr[3]))))))
2846 if (changed < 0)
2847 /* We've already seen this and run the before-change-function;
2848 this time we only need to record the actual position. */
2849 changed = pos;
2850 else if (!changed)
2852 changed = -1;
2853 modify_region (current_buffer, pos, XINT (end), 0);
2855 if (! NILP (noundo))
2857 if (MODIFF - 1 == SAVE_MODIFF)
2858 SAVE_MODIFF++;
2859 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2860 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2863 /* The before-change-function may have moved the gap
2864 or even modified the buffer so we should start over. */
2865 goto restart;
2868 /* Take care of the case where the new character
2869 combines with neighboring bytes. */
2870 if (maybe_byte_combining
2871 && (maybe_byte_combining == COMBINING_AFTER
2872 ? (pos_byte_next < Z_BYTE
2873 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2874 : ((pos_byte_next < Z_BYTE
2875 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2876 || (pos_byte > BEG_BYTE
2877 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2879 Lisp_Object tem, string;
2881 struct gcpro gcpro1;
2883 tem = BVAR (current_buffer, undo_list);
2884 GCPRO1 (tem);
2886 /* Make a multibyte string containing this single character. */
2887 string = make_multibyte_string ((char *) tostr, 1, len);
2888 /* replace_range is less efficient, because it moves the gap,
2889 but it handles combining correctly. */
2890 replace_range (pos, pos + 1, string,
2891 0, 0, 1);
2892 pos_byte_next = CHAR_TO_BYTE (pos);
2893 if (pos_byte_next > pos_byte)
2894 /* Before combining happened. We should not increment
2895 POS. So, to cancel the later increment of POS,
2896 decrease it now. */
2897 pos--;
2898 else
2899 INC_POS (pos_byte_next);
2901 if (! NILP (noundo))
2902 BVAR (current_buffer, undo_list) = tem;
2904 UNGCPRO;
2906 else
2908 if (NILP (noundo))
2909 record_change (pos, 1);
2910 for (i = 0; i < len; i++) *p++ = tostr[i];
2912 last_changed = pos + 1;
2914 pos_byte = pos_byte_next;
2915 pos++;
2918 if (changed > 0)
2920 signal_after_change (changed,
2921 last_changed - changed, last_changed - changed);
2922 update_compositions (changed, last_changed, CHECK_ALL);
2925 unbind_to (count, Qnil);
2926 return Qnil;
2930 static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
2931 Lisp_Object);
2933 /* Helper function for Ftranslate_region_internal.
2935 Check if a character sequence at POS (POS_BYTE) matches an element
2936 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2937 element is found, return it. Otherwise return Qnil. */
2939 static Lisp_Object
2940 check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
2941 Lisp_Object val)
2943 int buf_size = 16, buf_used = 0;
2944 int *buf = alloca (sizeof (int) * buf_size);
2946 for (; CONSP (val); val = XCDR (val))
2948 Lisp_Object elt;
2949 EMACS_INT len, i;
2951 elt = XCAR (val);
2952 if (! CONSP (elt))
2953 continue;
2954 elt = XCAR (elt);
2955 if (! VECTORP (elt))
2956 continue;
2957 len = ASIZE (elt);
2958 if (len <= end - pos)
2960 for (i = 0; i < len; i++)
2962 if (buf_used <= i)
2964 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2965 int len1;
2967 if (buf_used == buf_size)
2969 int *newbuf;
2971 buf_size += 16;
2972 newbuf = alloca (sizeof (int) * buf_size);
2973 memcpy (newbuf, buf, sizeof (int) * buf_used);
2974 buf = newbuf;
2976 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
2977 pos_byte += len1;
2979 if (XINT (AREF (elt, i)) != buf[i])
2980 break;
2982 if (i == len)
2983 return XCAR (val);
2986 return Qnil;
2990 DEFUN ("translate-region-internal", Ftranslate_region_internal,
2991 Stranslate_region_internal, 3, 3, 0,
2992 doc: /* Internal use only.
2993 From START to END, translate characters according to TABLE.
2994 TABLE is a string or a char-table; the Nth character in it is the
2995 mapping for the character with code N.
2996 It returns the number of characters changed. */)
2997 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
2999 register unsigned char *tt; /* Trans table. */
3000 register int nc; /* New character. */
3001 int cnt; /* Number of changes made. */
3002 EMACS_INT size; /* Size of translate table. */
3003 EMACS_INT pos, pos_byte, end_pos;
3004 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3005 int string_multibyte IF_LINT (= 0);
3007 validate_region (&start, &end);
3008 if (CHAR_TABLE_P (table))
3010 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3011 error ("Not a translation table");
3012 size = MAX_CHAR;
3013 tt = NULL;
3015 else
3017 CHECK_STRING (table);
3019 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3020 table = string_make_unibyte (table);
3021 string_multibyte = SCHARS (table) < SBYTES (table);
3022 size = SBYTES (table);
3023 tt = SDATA (table);
3026 pos = XINT (start);
3027 pos_byte = CHAR_TO_BYTE (pos);
3028 end_pos = XINT (end);
3029 modify_region (current_buffer, pos, end_pos, 0);
3031 cnt = 0;
3032 for (; pos < end_pos; )
3034 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3035 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3036 int len, str_len;
3037 int oc;
3038 Lisp_Object val;
3040 if (multibyte)
3041 oc = STRING_CHAR_AND_LENGTH (p, len);
3042 else
3043 oc = *p, len = 1;
3044 if (oc < size)
3046 if (tt)
3048 /* Reload as signal_after_change in last iteration may GC. */
3049 tt = SDATA (table);
3050 if (string_multibyte)
3052 str = tt + string_char_to_byte (table, oc);
3053 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3055 else
3057 nc = tt[oc];
3058 if (! ASCII_BYTE_P (nc) && multibyte)
3060 str_len = BYTE8_STRING (nc, buf);
3061 str = buf;
3063 else
3065 str_len = 1;
3066 str = tt + oc;
3070 else
3072 nc = oc;
3073 val = CHAR_TABLE_REF (table, oc);
3074 if (CHARACTERP (val))
3076 nc = XFASTINT (val);
3077 str_len = CHAR_STRING (nc, buf);
3078 str = buf;
3080 else if (VECTORP (val) || (CONSP (val)))
3082 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3083 where TO is TO-CHAR or [TO-CHAR ...]. */
3084 nc = -1;
3088 if (nc != oc && nc >= 0)
3090 /* Simple one char to one char translation. */
3091 if (len != str_len)
3093 Lisp_Object string;
3095 /* This is less efficient, because it moves the gap,
3096 but it should handle multibyte characters correctly. */
3097 string = make_multibyte_string ((char *) str, 1, str_len);
3098 replace_range (pos, pos + 1, string, 1, 0, 1);
3099 len = str_len;
3101 else
3103 record_change (pos, 1);
3104 while (str_len-- > 0)
3105 *p++ = *str++;
3106 signal_after_change (pos, 1, 1);
3107 update_compositions (pos, pos + 1, CHECK_BORDER);
3109 ++cnt;
3111 else if (nc < 0)
3113 Lisp_Object string;
3115 if (CONSP (val))
3117 val = check_translation (pos, pos_byte, end_pos, val);
3118 if (NILP (val))
3120 pos_byte += len;
3121 pos++;
3122 continue;
3124 /* VAL is ([FROM-CHAR ...] . TO). */
3125 len = ASIZE (XCAR (val));
3126 val = XCDR (val);
3128 else
3129 len = 1;
3131 if (VECTORP (val))
3133 string = Fconcat (1, &val);
3135 else
3137 string = Fmake_string (make_number (1), val);
3139 replace_range (pos, pos + len, string, 1, 0, 1);
3140 pos_byte += SBYTES (string);
3141 pos += SCHARS (string);
3142 cnt += SCHARS (string);
3143 end_pos += SCHARS (string) - len;
3144 continue;
3147 pos_byte += len;
3148 pos++;
3151 return make_number (cnt);
3154 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3155 doc: /* Delete the text between point and mark.
3157 When called from a program, expects two arguments,
3158 positions (integers or markers) specifying the stretch to be deleted. */)
3159 (Lisp_Object start, Lisp_Object end)
3161 validate_region (&start, &end);
3162 del_range (XINT (start), XINT (end));
3163 return Qnil;
3166 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3167 Sdelete_and_extract_region, 2, 2, 0,
3168 doc: /* Delete the text between START and END and return it. */)
3169 (Lisp_Object start, Lisp_Object end)
3171 validate_region (&start, &end);
3172 if (XINT (start) == XINT (end))
3173 return empty_unibyte_string;
3174 return del_range_1 (XINT (start), XINT (end), 1, 1);
3177 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3178 doc: /* Remove restrictions (narrowing) from current buffer.
3179 This allows the buffer's full text to be seen and edited. */)
3180 (void)
3182 if (BEG != BEGV || Z != ZV)
3183 current_buffer->clip_changed = 1;
3184 BEGV = BEG;
3185 BEGV_BYTE = BEG_BYTE;
3186 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3187 /* Changing the buffer bounds invalidates any recorded current column. */
3188 invalidate_current_column ();
3189 return Qnil;
3192 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3193 doc: /* Restrict editing in this buffer to the current region.
3194 The rest of the text becomes temporarily invisible and untouchable
3195 but is not deleted; if you save the buffer in a file, the invisible
3196 text is included in the file. \\[widen] makes all visible again.
3197 See also `save-restriction'.
3199 When calling from a program, pass two arguments; positions (integers
3200 or markers) bounding the text that should remain visible. */)
3201 (register Lisp_Object start, Lisp_Object end)
3203 CHECK_NUMBER_COERCE_MARKER (start);
3204 CHECK_NUMBER_COERCE_MARKER (end);
3206 if (XINT (start) > XINT (end))
3208 Lisp_Object tem;
3209 tem = start; start = end; end = tem;
3212 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3213 args_out_of_range (start, end);
3215 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3216 current_buffer->clip_changed = 1;
3218 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3219 SET_BUF_ZV (current_buffer, XFASTINT (end));
3220 if (PT < XFASTINT (start))
3221 SET_PT (XFASTINT (start));
3222 if (PT > XFASTINT (end))
3223 SET_PT (XFASTINT (end));
3224 /* Changing the buffer bounds invalidates any recorded current column. */
3225 invalidate_current_column ();
3226 return Qnil;
3229 Lisp_Object
3230 save_restriction_save (void)
3232 if (BEGV == BEG && ZV == Z)
3233 /* The common case that the buffer isn't narrowed.
3234 We return just the buffer object, which save_restriction_restore
3235 recognizes as meaning `no restriction'. */
3236 return Fcurrent_buffer ();
3237 else
3238 /* We have to save a restriction, so return a pair of markers, one
3239 for the beginning and one for the end. */
3241 Lisp_Object beg, end;
3243 beg = buildmark (BEGV, BEGV_BYTE);
3244 end = buildmark (ZV, ZV_BYTE);
3246 /* END must move forward if text is inserted at its exact location. */
3247 XMARKER(end)->insertion_type = 1;
3249 return Fcons (beg, end);
3253 Lisp_Object
3254 save_restriction_restore (Lisp_Object data)
3256 struct buffer *cur = NULL;
3257 struct buffer *buf = (CONSP (data)
3258 ? XMARKER (XCAR (data))->buffer
3259 : XBUFFER (data));
3261 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3262 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3263 is the case if it is or has an indirect buffer), then make
3264 sure it is current before we update BEGV, so
3265 set_buffer_internal takes care of managing those markers. */
3266 cur = current_buffer;
3267 set_buffer_internal (buf);
3270 if (CONSP (data))
3271 /* A pair of marks bounding a saved restriction. */
3273 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3274 struct Lisp_Marker *end = XMARKER (XCDR (data));
3275 eassert (buf == end->buffer);
3277 if (buf /* Verify marker still points to a buffer. */
3278 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3279 /* The restriction has changed from the saved one, so restore
3280 the saved restriction. */
3282 EMACS_INT pt = BUF_PT (buf);
3284 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3285 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3287 if (pt < beg->charpos || pt > end->charpos)
3288 /* The point is outside the new visible range, move it inside. */
3289 SET_BUF_PT_BOTH (buf,
3290 clip_to_bounds (beg->charpos, pt, end->charpos),
3291 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3292 end->bytepos));
3294 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3297 else
3298 /* A buffer, which means that there was no old restriction. */
3300 if (buf /* Verify marker still points to a buffer. */
3301 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3302 /* The buffer has been narrowed, get rid of the narrowing. */
3304 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3305 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3307 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3311 /* Changing the buffer bounds invalidates any recorded current column. */
3312 invalidate_current_column ();
3314 if (cur)
3315 set_buffer_internal (cur);
3317 return Qnil;
3320 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3321 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3322 The buffer's restrictions make parts of the beginning and end invisible.
3323 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3324 This special form, `save-restriction', saves the current buffer's restrictions
3325 when it is entered, and restores them when it is exited.
3326 So any `narrow-to-region' within BODY lasts only until the end of the form.
3327 The old restrictions settings are restored
3328 even in case of abnormal exit (throw or error).
3330 The value returned is the value of the last form in BODY.
3332 Note: if you are using both `save-excursion' and `save-restriction',
3333 use `save-excursion' outermost:
3334 (save-excursion (save-restriction ...))
3336 usage: (save-restriction &rest BODY) */)
3337 (Lisp_Object body)
3339 register Lisp_Object val;
3340 int count = SPECPDL_INDEX ();
3342 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3343 val = Fprogn (body);
3344 return unbind_to (count, val);
3347 /* Buffer for the most recent text displayed by Fmessage_box. */
3348 static char *message_text;
3350 /* Allocated length of that buffer. */
3351 static int message_length;
3353 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3354 doc: /* Display a message at the bottom of the screen.
3355 The message also goes into the `*Messages*' buffer.
3356 \(In keyboard macros, that's all it does.)
3357 Return the message.
3359 The first argument is a format control string, and the rest are data
3360 to be formatted under control of the string. See `format' for details.
3362 Note: Use (message "%s" VALUE) to print the value of expressions and
3363 variables to avoid accidentally interpreting `%' as format specifiers.
3365 If the first argument is nil or the empty string, the function clears
3366 any existing message; this lets the minibuffer contents show. See
3367 also `current-message'.
3369 usage: (message FORMAT-STRING &rest ARGS) */)
3370 (ptrdiff_t nargs, Lisp_Object *args)
3372 if (NILP (args[0])
3373 || (STRINGP (args[0])
3374 && SBYTES (args[0]) == 0))
3376 message (0);
3377 return args[0];
3379 else
3381 register Lisp_Object val;
3382 val = Fformat (nargs, args);
3383 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3384 return val;
3388 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3389 doc: /* Display a message, in a dialog box if possible.
3390 If a dialog box is not available, use the echo area.
3391 The first argument is a format control string, and the rest are data
3392 to be formatted under control of the string. See `format' for details.
3394 If the first argument is nil or the empty string, clear any existing
3395 message; let the minibuffer contents show.
3397 usage: (message-box FORMAT-STRING &rest ARGS) */)
3398 (ptrdiff_t nargs, Lisp_Object *args)
3400 if (NILP (args[0]))
3402 message (0);
3403 return Qnil;
3405 else
3407 register Lisp_Object val;
3408 val = Fformat (nargs, args);
3409 #ifdef HAVE_MENUS
3410 /* The MS-DOS frames support popup menus even though they are
3411 not FRAME_WINDOW_P. */
3412 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3413 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3415 Lisp_Object pane, menu;
3416 struct gcpro gcpro1;
3417 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3418 GCPRO1 (pane);
3419 menu = Fcons (val, pane);
3420 Fx_popup_dialog (Qt, menu, Qt);
3421 UNGCPRO;
3422 return val;
3424 #endif /* HAVE_MENUS */
3425 /* Copy the data so that it won't move when we GC. */
3426 if (! message_text)
3428 message_text = (char *)xmalloc (80);
3429 message_length = 80;
3431 if (SBYTES (val) > message_length)
3433 message_length = SBYTES (val);
3434 message_text = (char *)xrealloc (message_text, message_length);
3436 memcpy (message_text, SDATA (val), SBYTES (val));
3437 message2 (message_text, SBYTES (val),
3438 STRING_MULTIBYTE (val));
3439 return val;
3443 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3444 doc: /* Display a message in a dialog box or in the echo area.
3445 If this command was invoked with the mouse, use a dialog box if
3446 `use-dialog-box' is non-nil.
3447 Otherwise, use the echo area.
3448 The first argument is a format control string, and the rest are data
3449 to be formatted under control of the string. See `format' for details.
3451 If the first argument is nil or the empty string, clear any existing
3452 message; let the minibuffer contents show.
3454 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3455 (ptrdiff_t nargs, Lisp_Object *args)
3457 #ifdef HAVE_MENUS
3458 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3459 && use_dialog_box)
3460 return Fmessage_box (nargs, args);
3461 #endif
3462 return Fmessage (nargs, args);
3465 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3466 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3467 (void)
3469 return current_message ();
3473 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3474 doc: /* Return a copy of STRING with text properties added.
3475 First argument is the string to copy.
3476 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3477 properties to add to the result.
3478 usage: (propertize STRING &rest PROPERTIES) */)
3479 (ptrdiff_t nargs, Lisp_Object *args)
3481 Lisp_Object properties, string;
3482 struct gcpro gcpro1, gcpro2;
3483 ptrdiff_t i;
3485 /* Number of args must be odd. */
3486 if ((nargs & 1) == 0)
3487 error ("Wrong number of arguments");
3489 properties = string = Qnil;
3490 GCPRO2 (properties, string);
3492 /* First argument must be a string. */
3493 CHECK_STRING (args[0]);
3494 string = Fcopy_sequence (args[0]);
3496 for (i = 1; i < nargs; i += 2)
3497 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3499 Fadd_text_properties (make_number (0),
3500 make_number (SCHARS (string)),
3501 properties, string);
3502 RETURN_UNGCPRO (string);
3505 /* pWIDE is a conversion for printing large decimal integers (possibly with a
3506 trailing "d" that is ignored). pWIDElen is its length. signed_wide and
3507 unsigned_wide are signed and unsigned types for printing them. Use widest
3508 integers if available so that more floating point values can be converted. */
3509 #ifdef PRIdMAX
3510 # define pWIDE PRIdMAX
3511 enum { pWIDElen = sizeof PRIdMAX - 2 }; /* Don't count trailing "d". */
3512 typedef intmax_t signed_wide;
3513 typedef uintmax_t unsigned_wide;
3514 #else
3515 # define pWIDE pI
3516 enum { pWIDElen = sizeof pI - 1 };
3517 typedef EMACS_INT signed_wide;
3518 typedef EMACS_UINT unsigned_wide;
3519 #endif
3521 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3522 doc: /* Format a string out of a format-string and arguments.
3523 The first argument is a format control string.
3524 The other arguments are substituted into it to make the result, a string.
3526 The format control string may contain %-sequences meaning to substitute
3527 the next available argument:
3529 %s means print a string argument. Actually, prints any object, with `princ'.
3530 %d means print as number in decimal (%o octal, %x hex).
3531 %X is like %x, but uses upper case.
3532 %e means print a number in exponential notation.
3533 %f means print a number in decimal-point notation.
3534 %g means print a number in exponential notation
3535 or decimal-point notation, whichever uses fewer characters.
3536 %c means print a number as a single character.
3537 %S means print any object as an s-expression (using `prin1').
3539 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3540 Use %% to put a single % into the output.
3542 A %-sequence may contain optional flag, width, and precision
3543 specifiers, as follows:
3545 %<flags><width><precision>character
3547 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3549 The + flag character inserts a + before any positive number, while a
3550 space inserts a space before any positive number; these flags only
3551 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3552 The # flag means to use an alternate display form for %o, %x, %X, %e,
3553 %f, and %g sequences. The - and 0 flags affect the width specifier,
3554 as described below.
3556 The width specifier supplies a lower limit for the length of the
3557 printed representation. The padding, if any, normally goes on the
3558 left, but it goes on the right if the - flag is present. The padding
3559 character is normally a space, but it is 0 if the 0 flag is present.
3560 The - flag takes precedence over the 0 flag.
3562 For %e, %f, and %g sequences, the number after the "." in the
3563 precision specifier says how many decimal places to show; if zero, the
3564 decimal point itself is omitted. For %s and %S, the precision
3565 specifier truncates the string to the given width.
3567 usage: (format STRING &rest OBJECTS) */)
3568 (ptrdiff_t nargs, Lisp_Object *args)
3570 ptrdiff_t n; /* The number of the next arg to substitute */
3571 char initial_buffer[4000];
3572 char *buf = initial_buffer;
3573 EMACS_INT bufsize = sizeof initial_buffer;
3574 EMACS_INT max_bufsize = STRING_BYTES_BOUND + 1;
3575 char *p;
3576 Lisp_Object buf_save_value IF_LINT (= {0});
3577 register char *format, *end, *format_start;
3578 EMACS_INT formatlen, nchars;
3579 /* Nonzero if the format is multibyte. */
3580 int multibyte_format = 0;
3581 /* Nonzero if the output should be a multibyte string,
3582 which is true if any of the inputs is one. */
3583 int multibyte = 0;
3584 /* When we make a multibyte string, we must pay attention to the
3585 byte combining problem, i.e., a byte may be combined with a
3586 multibyte character of the previous string. This flag tells if we
3587 must consider such a situation or not. */
3588 int maybe_combine_byte;
3589 Lisp_Object val;
3590 int arg_intervals = 0;
3591 USE_SAFE_ALLOCA;
3593 /* discarded[I] is 1 if byte I of the format
3594 string was not copied into the output.
3595 It is 2 if byte I was not the first byte of its character. */
3596 char *discarded;
3598 /* Each element records, for one argument,
3599 the start and end bytepos in the output string,
3600 whether the argument has been converted to string (e.g., due to "%S"),
3601 and whether the argument is a string with intervals.
3602 info[0] is unused. Unused elements have -1 for start. */
3603 struct info
3605 EMACS_INT start, end;
3606 int converted_to_string;
3607 int intervals;
3608 } *info = 0;
3610 /* It should not be necessary to GCPRO ARGS, because
3611 the caller in the interpreter should take care of that. */
3613 CHECK_STRING (args[0]);
3614 format_start = SSDATA (args[0]);
3615 formatlen = SBYTES (args[0]);
3617 /* Allocate the info and discarded tables. */
3619 ptrdiff_t i;
3620 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3621 memory_full (SIZE_MAX);
3622 SAFE_ALLOCA (info, struct info *, (nargs + 1) * sizeof *info + formatlen);
3623 discarded = (char *) &info[nargs + 1];
3624 for (i = 0; i < nargs + 1; i++)
3626 info[i].start = -1;
3627 info[i].intervals = info[i].converted_to_string = 0;
3629 memset (discarded, 0, formatlen);
3632 /* Try to determine whether the result should be multibyte.
3633 This is not always right; sometimes the result needs to be multibyte
3634 because of an object that we will pass through prin1,
3635 and in that case, we won't know it here. */
3636 multibyte_format = STRING_MULTIBYTE (args[0]);
3637 multibyte = multibyte_format;
3638 for (n = 1; !multibyte && n < nargs; n++)
3639 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3640 multibyte = 1;
3642 /* If we start out planning a unibyte result,
3643 then discover it has to be multibyte, we jump back to retry. */
3644 retry:
3646 p = buf;
3647 nchars = 0;
3648 n = 0;
3650 /* Scan the format and store result in BUF. */
3651 format = format_start;
3652 end = format + formatlen;
3653 maybe_combine_byte = 0;
3655 while (format != end)
3657 /* The values of N and FORMAT when the loop body is entered. */
3658 ptrdiff_t n0 = n;
3659 char *format0 = format;
3661 /* Bytes needed to represent the output of this conversion. */
3662 EMACS_INT convbytes;
3664 if (*format == '%')
3666 /* General format specifications look like
3668 '%' [flags] [field-width] [precision] format
3670 where
3672 flags ::= [-+0# ]+
3673 field-width ::= [0-9]+
3674 precision ::= '.' [0-9]*
3676 If a field-width is specified, it specifies to which width
3677 the output should be padded with blanks, if the output
3678 string is shorter than field-width.
3680 If precision is specified, it specifies the number of
3681 digits to print after the '.' for floats, or the max.
3682 number of chars to print from a string. */
3684 int minus_flag = 0;
3685 int plus_flag = 0;
3686 int space_flag = 0;
3687 int sharp_flag = 0;
3688 int zero_flag = 0;
3689 EMACS_INT field_width;
3690 int precision_given;
3691 uintmax_t precision = UINTMAX_MAX;
3692 char *num_end;
3693 char conversion;
3695 while (1)
3697 switch (*++format)
3699 case '-': minus_flag = 1; continue;
3700 case '+': plus_flag = 1; continue;
3701 case ' ': space_flag = 1; continue;
3702 case '#': sharp_flag = 1; continue;
3703 case '0': zero_flag = 1; continue;
3705 break;
3708 /* Ignore flags when sprintf ignores them. */
3709 space_flag &= ~ plus_flag;
3710 zero_flag &= ~ minus_flag;
3713 uintmax_t w = strtoumax (format, &num_end, 10);
3714 if (max_bufsize <= w)
3715 string_overflow ();
3716 field_width = w;
3718 precision_given = *num_end == '.';
3719 if (precision_given)
3720 precision = strtoumax (num_end + 1, &num_end, 10);
3721 format = num_end;
3723 if (format == end)
3724 error ("Format string ends in middle of format specifier");
3726 memset (&discarded[format0 - format_start], 1, format - format0);
3727 conversion = *format;
3728 if (conversion == '%')
3729 goto copy_char;
3730 discarded[format - format_start] = 1;
3731 format++;
3733 ++n;
3734 if (! (n < nargs))
3735 error ("Not enough arguments for format string");
3737 /* For 'S', prin1 the argument, and then treat like 's'.
3738 For 's', princ any argument that is not a string or
3739 symbol. But don't do this conversion twice, which might
3740 happen after retrying. */
3741 if ((conversion == 'S'
3742 || (conversion == 's'
3743 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3745 if (! info[n].converted_to_string)
3747 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3748 args[n] = Fprin1_to_string (args[n], noescape);
3749 info[n].converted_to_string = 1;
3750 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3752 multibyte = 1;
3753 goto retry;
3756 conversion = 's';
3758 else if (conversion == 'c')
3760 if (FLOATP (args[n]))
3762 double d = XFLOAT_DATA (args[n]);
3763 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3766 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3768 if (!multibyte)
3770 multibyte = 1;
3771 goto retry;
3773 args[n] = Fchar_to_string (args[n]);
3774 info[n].converted_to_string = 1;
3777 if (info[n].converted_to_string)
3778 conversion = 's';
3779 zero_flag = 0;
3782 if (SYMBOLP (args[n]))
3784 args[n] = SYMBOL_NAME (args[n]);
3785 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3787 multibyte = 1;
3788 goto retry;
3792 if (conversion == 's')
3794 /* handle case (precision[n] >= 0) */
3796 EMACS_INT width, padding, nbytes;
3797 EMACS_INT nchars_string;
3799 EMACS_INT prec = -1;
3800 if (precision_given && precision <= TYPE_MAXIMUM (EMACS_INT))
3801 prec = precision;
3803 /* lisp_string_width ignores a precision of 0, but GNU
3804 libc functions print 0 characters when the precision
3805 is 0. Imitate libc behavior here. Changing
3806 lisp_string_width is the right thing, and will be
3807 done, but meanwhile we work with it. */
3809 if (prec == 0)
3810 width = nchars_string = nbytes = 0;
3811 else
3813 EMACS_INT nch, nby;
3814 width = lisp_string_width (args[n], prec, &nch, &nby);
3815 if (prec < 0)
3817 nchars_string = SCHARS (args[n]);
3818 nbytes = SBYTES (args[n]);
3820 else
3822 nchars_string = nch;
3823 nbytes = nby;
3827 convbytes = nbytes;
3828 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
3829 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
3831 padding = width < field_width ? field_width - width : 0;
3833 if (max_bufsize - padding <= convbytes)
3834 string_overflow ();
3835 convbytes += padding;
3836 if (convbytes <= buf + bufsize - p)
3838 if (! minus_flag)
3840 memset (p, ' ', padding);
3841 p += padding;
3842 nchars += padding;
3845 if (p > buf
3846 && multibyte
3847 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3848 && STRING_MULTIBYTE (args[n])
3849 && !CHAR_HEAD_P (SREF (args[n], 0)))
3850 maybe_combine_byte = 1;
3852 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3853 nbytes,
3854 STRING_MULTIBYTE (args[n]), multibyte);
3856 info[n].start = nchars;
3857 nchars += nchars_string;
3858 info[n].end = nchars;
3860 if (minus_flag)
3862 memset (p, ' ', padding);
3863 p += padding;
3864 nchars += padding;
3867 /* If this argument has text properties, record where
3868 in the result string it appears. */
3869 if (STRING_INTERVALS (args[n]))
3870 info[n].intervals = arg_intervals = 1;
3872 continue;
3875 else if (! (conversion == 'c' || conversion == 'd'
3876 || conversion == 'e' || conversion == 'f'
3877 || conversion == 'g' || conversion == 'i'
3878 || conversion == 'o' || conversion == 'x'
3879 || conversion == 'X'))
3880 error ("Invalid format operation %%%c",
3881 STRING_CHAR ((unsigned char *) format - 1));
3882 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
3883 error ("Format specifier doesn't match argument type");
3884 else
3886 enum
3888 /* Maximum precision for a %f conversion such that the
3889 trailing output digit might be nonzero. Any precisions
3890 larger than this will not yield useful information. */
3891 USEFUL_PRECISION_MAX =
3892 ((1 - DBL_MIN_EXP)
3893 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
3894 : FLT_RADIX == 16 ? 4
3895 : -1)),
3897 /* Maximum number of bytes generated by any format, if
3898 precision is no more than DBL_USEFUL_PRECISION_MAX.
3899 On all practical hosts, %f is the worst case. */
3900 SPRINTF_BUFSIZE =
3901 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX
3903 verify (0 < USEFUL_PRECISION_MAX);
3905 int prec;
3906 EMACS_INT padding, sprintf_bytes;
3907 uintmax_t excess_precision, numwidth;
3908 uintmax_t leading_zeros = 0, trailing_zeros = 0;
3910 char sprintf_buf[SPRINTF_BUFSIZE];
3912 /* Copy of conversion specification, modified somewhat.
3913 At most three flags F can be specified at once. */
3914 char convspec[sizeof "%FFF.*d" + pWIDElen];
3916 /* Avoid undefined behavior in underlying sprintf. */
3917 if (conversion == 'd' || conversion == 'i')
3918 sharp_flag = 0;
3920 /* Create the copy of the conversion specification, with
3921 any width and precision removed, with ".*" inserted,
3922 and with pWIDE inserted for integer formats. */
3924 char *f = convspec;
3925 *f++ = '%';
3926 *f = '-'; f += minus_flag;
3927 *f = '+'; f += plus_flag;
3928 *f = ' '; f += space_flag;
3929 *f = '#'; f += sharp_flag;
3930 *f = '0'; f += zero_flag;
3931 *f++ = '.';
3932 *f++ = '*';
3933 if (conversion == 'd' || conversion == 'i'
3934 || conversion == 'o' || conversion == 'x'
3935 || conversion == 'X')
3937 memcpy (f, pWIDE, pWIDElen);
3938 f += pWIDElen;
3939 zero_flag &= ~ precision_given;
3941 *f++ = conversion;
3942 *f = '\0';
3945 prec = -1;
3946 if (precision_given)
3947 prec = min (precision, USEFUL_PRECISION_MAX);
3949 /* Use sprintf to format this number into sprintf_buf. Omit
3950 padding and excess precision, though, because sprintf limits
3951 output length to INT_MAX.
3953 There are four types of conversion: double, unsigned
3954 char (passed as int), wide signed int, and wide
3955 unsigned int. Treat them separately because the
3956 sprintf ABI is sensitive to which type is passed. Be
3957 careful about integer overflow, NaNs, infinities, and
3958 conversions; for example, the min and max macros are
3959 not suitable here. */
3960 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
3962 double x = (INTEGERP (args[n])
3963 ? XINT (args[n])
3964 : XFLOAT_DATA (args[n]));
3965 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
3967 else if (conversion == 'c')
3969 /* Don't use sprintf here, as it might mishandle prec. */
3970 sprintf_buf[0] = XINT (args[n]);
3971 sprintf_bytes = prec != 0;
3973 else if (conversion == 'd')
3975 /* For float, maybe we should use "%1.0f"
3976 instead so it also works for values outside
3977 the integer range. */
3978 signed_wide x;
3979 if (INTEGERP (args[n]))
3980 x = XINT (args[n]);
3981 else
3983 double d = XFLOAT_DATA (args[n]);
3984 if (d < 0)
3986 x = TYPE_MINIMUM (signed_wide);
3987 if (x < d)
3988 x = d;
3990 else
3992 x = TYPE_MAXIMUM (signed_wide);
3993 if (d < x)
3994 x = d;
3997 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
3999 else
4001 /* Don't sign-extend for octal or hex printing. */
4002 unsigned_wide x;
4003 if (INTEGERP (args[n]))
4004 x = XUINT (args[n]);
4005 else
4007 double d = XFLOAT_DATA (args[n]);
4008 if (d < 0)
4009 x = 0;
4010 else
4012 x = TYPE_MAXIMUM (unsigned_wide);
4013 if (d < x)
4014 x = d;
4017 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4020 /* Now the length of the formatted item is known, except it omits
4021 padding and excess precision. Deal with excess precision
4022 first. This happens only when the format specifies
4023 ridiculously large precision. */
4024 excess_precision = precision - prec;
4025 if (excess_precision)
4027 if (conversion == 'e' || conversion == 'f'
4028 || conversion == 'g')
4030 if ((conversion == 'g' && ! sharp_flag)
4031 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4032 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4033 excess_precision = 0;
4034 else
4036 if (conversion == 'g')
4038 char *dot = strchr (sprintf_buf, '.');
4039 if (!dot)
4040 excess_precision = 0;
4043 trailing_zeros = excess_precision;
4045 else
4046 leading_zeros = excess_precision;
4049 /* Compute the total bytes needed for this item, including
4050 excess precision and padding. */
4051 numwidth = sprintf_bytes + excess_precision;
4052 padding = numwidth < field_width ? field_width - numwidth : 0;
4053 if (max_bufsize - sprintf_bytes <= excess_precision
4054 || max_bufsize - padding <= numwidth)
4055 string_overflow ();
4056 convbytes = numwidth + padding;
4058 if (convbytes <= buf + bufsize - p)
4060 /* Copy the formatted item from sprintf_buf into buf,
4061 inserting padding and excess-precision zeros. */
4063 char *src = sprintf_buf;
4064 char src0 = src[0];
4065 int exponent_bytes = 0;
4066 int signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4067 int significand_bytes;
4068 if (zero_flag
4069 && ((src[signedp] >= '0' && src[signedp] <= '9')
4070 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4071 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4073 leading_zeros += padding;
4074 padding = 0;
4077 if (excess_precision
4078 && (conversion == 'e' || conversion == 'g'))
4080 char *e = strchr (src, 'e');
4081 if (e)
4082 exponent_bytes = src + sprintf_bytes - e;
4085 if (! minus_flag)
4087 memset (p, ' ', padding);
4088 p += padding;
4089 nchars += padding;
4092 *p = src0;
4093 src += signedp;
4094 p += signedp;
4095 memset (p, '0', leading_zeros);
4096 p += leading_zeros;
4097 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4098 memcpy (p, src, significand_bytes);
4099 p += significand_bytes;
4100 src += significand_bytes;
4101 memset (p, '0', trailing_zeros);
4102 p += trailing_zeros;
4103 memcpy (p, src, exponent_bytes);
4104 p += exponent_bytes;
4106 info[n].start = nchars;
4107 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4108 info[n].end = nchars;
4110 if (minus_flag)
4112 memset (p, ' ', padding);
4113 p += padding;
4114 nchars += padding;
4117 continue;
4121 else
4122 copy_char:
4124 /* Copy a single character from format to buf. */
4126 char *src = format;
4127 unsigned char str[MAX_MULTIBYTE_LENGTH];
4129 if (multibyte_format)
4131 /* Copy a whole multibyte character. */
4132 if (p > buf
4133 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4134 && !CHAR_HEAD_P (*format))
4135 maybe_combine_byte = 1;
4138 format++;
4139 while (! CHAR_HEAD_P (*format));
4141 convbytes = format - format0;
4142 memset (&discarded[format0 + 1 - format_start], 2, convbytes - 1);
4144 else
4146 unsigned char uc = *format++;
4147 if (! multibyte || ASCII_BYTE_P (uc))
4148 convbytes = 1;
4149 else
4151 int c = BYTE8_TO_CHAR (uc);
4152 convbytes = CHAR_STRING (c, str);
4153 src = (char *) str;
4157 if (convbytes <= buf + bufsize - p)
4159 memcpy (p, src, convbytes);
4160 p += convbytes;
4161 nchars++;
4162 continue;
4166 /* There wasn't enough room to store this conversion or single
4167 character. CONVBYTES says how much room is needed. Allocate
4168 enough room (and then some) and do it again. */
4170 EMACS_INT used = p - buf;
4172 if (max_bufsize - used < convbytes)
4173 string_overflow ();
4174 bufsize = used + convbytes;
4175 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4177 if (buf == initial_buffer)
4179 buf = xmalloc (bufsize);
4180 sa_must_free = 1;
4181 buf_save_value = make_save_value (buf, 0);
4182 record_unwind_protect (safe_alloca_unwind, buf_save_value);
4183 memcpy (buf, initial_buffer, used);
4185 else
4186 XSAVE_VALUE (buf_save_value)->pointer = buf = xrealloc (buf, bufsize);
4188 p = buf + used;
4191 format = format0;
4192 n = n0;
4195 if (bufsize < p - buf)
4196 abort ();
4198 if (maybe_combine_byte)
4199 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4200 val = make_specified_string (buf, nchars, p - buf, multibyte);
4202 /* If we allocated BUF with malloc, free it too. */
4203 SAFE_FREE ();
4205 /* If the format string has text properties, or any of the string
4206 arguments has text properties, set up text properties of the
4207 result string. */
4209 if (STRING_INTERVALS (args[0]) || arg_intervals)
4211 Lisp_Object len, new_len, props;
4212 struct gcpro gcpro1;
4214 /* Add text properties from the format string. */
4215 len = make_number (SCHARS (args[0]));
4216 props = text_property_list (args[0], make_number (0), len, Qnil);
4217 GCPRO1 (props);
4219 if (CONSP (props))
4221 EMACS_INT bytepos = 0, position = 0, translated = 0;
4222 EMACS_INT argn = 1;
4223 Lisp_Object list;
4225 /* Adjust the bounds of each text property
4226 to the proper start and end in the output string. */
4228 /* Put the positions in PROPS in increasing order, so that
4229 we can do (effectively) one scan through the position
4230 space of the format string. */
4231 props = Fnreverse (props);
4233 /* BYTEPOS is the byte position in the format string,
4234 POSITION is the untranslated char position in it,
4235 TRANSLATED is the translated char position in BUF,
4236 and ARGN is the number of the next arg we will come to. */
4237 for (list = props; CONSP (list); list = XCDR (list))
4239 Lisp_Object item;
4240 EMACS_INT pos;
4242 item = XCAR (list);
4244 /* First adjust the property start position. */
4245 pos = XINT (XCAR (item));
4247 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4248 up to this position. */
4249 for (; position < pos; bytepos++)
4251 if (! discarded[bytepos])
4252 position++, translated++;
4253 else if (discarded[bytepos] == 1)
4255 position++;
4256 if (translated == info[argn].start)
4258 translated += info[argn].end - info[argn].start;
4259 argn++;
4264 XSETCAR (item, make_number (translated));
4266 /* Likewise adjust the property end position. */
4267 pos = XINT (XCAR (XCDR (item)));
4269 for (; position < pos; bytepos++)
4271 if (! discarded[bytepos])
4272 position++, translated++;
4273 else if (discarded[bytepos] == 1)
4275 position++;
4276 if (translated == info[argn].start)
4278 translated += info[argn].end - info[argn].start;
4279 argn++;
4284 XSETCAR (XCDR (item), make_number (translated));
4287 add_text_properties_from_list (val, props, make_number (0));
4290 /* Add text properties from arguments. */
4291 if (arg_intervals)
4292 for (n = 1; n < nargs; ++n)
4293 if (info[n].intervals)
4295 len = make_number (SCHARS (args[n]));
4296 new_len = make_number (info[n].end - info[n].start);
4297 props = text_property_list (args[n], make_number (0), len, Qnil);
4298 props = extend_property_ranges (props, new_len);
4299 /* If successive arguments have properties, be sure that
4300 the value of `composition' property be the copy. */
4301 if (n > 1 && info[n - 1].end)
4302 make_composition_value_copy (props);
4303 add_text_properties_from_list (val, props,
4304 make_number (info[n].start));
4307 UNGCPRO;
4310 return val;
4313 Lisp_Object
4314 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4316 Lisp_Object args[3];
4317 args[0] = build_string (string1);
4318 args[1] = arg0;
4319 args[2] = arg1;
4320 return Fformat (3, args);
4323 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4324 doc: /* Return t if two characters match, optionally ignoring case.
4325 Both arguments must be characters (i.e. integers).
4326 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4327 (register Lisp_Object c1, Lisp_Object c2)
4329 int i1, i2;
4330 /* Check they're chars, not just integers, otherwise we could get array
4331 bounds violations in downcase. */
4332 CHECK_CHARACTER (c1);
4333 CHECK_CHARACTER (c2);
4335 if (XINT (c1) == XINT (c2))
4336 return Qt;
4337 if (NILP (BVAR (current_buffer, case_fold_search)))
4338 return Qnil;
4340 i1 = XFASTINT (c1);
4341 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4342 && ! ASCII_CHAR_P (i1))
4344 MAKE_CHAR_MULTIBYTE (i1);
4346 i2 = XFASTINT (c2);
4347 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4348 && ! ASCII_CHAR_P (i2))
4350 MAKE_CHAR_MULTIBYTE (i2);
4352 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4355 /* Transpose the markers in two regions of the current buffer, and
4356 adjust the ones between them if necessary (i.e.: if the regions
4357 differ in size).
4359 START1, END1 are the character positions of the first region.
4360 START1_BYTE, END1_BYTE are the byte positions.
4361 START2, END2 are the character positions of the second region.
4362 START2_BYTE, END2_BYTE are the byte positions.
4364 Traverses the entire marker list of the buffer to do so, adding an
4365 appropriate amount to some, subtracting from some, and leaving the
4366 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4368 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4370 static void
4371 transpose_markers (EMACS_INT start1, EMACS_INT end1,
4372 EMACS_INT start2, EMACS_INT end2,
4373 EMACS_INT start1_byte, EMACS_INT end1_byte,
4374 EMACS_INT start2_byte, EMACS_INT end2_byte)
4376 register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4377 register struct Lisp_Marker *marker;
4379 /* Update point as if it were a marker. */
4380 if (PT < start1)
4382 else if (PT < end1)
4383 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4384 PT_BYTE + (end2_byte - end1_byte));
4385 else if (PT < start2)
4386 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4387 (PT_BYTE + (end2_byte - start2_byte)
4388 - (end1_byte - start1_byte)));
4389 else if (PT < end2)
4390 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4391 PT_BYTE - (start2_byte - start1_byte));
4393 /* We used to adjust the endpoints here to account for the gap, but that
4394 isn't good enough. Even if we assume the caller has tried to move the
4395 gap out of our way, it might still be at start1 exactly, for example;
4396 and that places it `inside' the interval, for our purposes. The amount
4397 of adjustment is nontrivial if there's a `denormalized' marker whose
4398 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4399 the dirty work to Fmarker_position, below. */
4401 /* The difference between the region's lengths */
4402 diff = (end2 - start2) - (end1 - start1);
4403 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4405 /* For shifting each marker in a region by the length of the other
4406 region plus the distance between the regions. */
4407 amt1 = (end2 - start2) + (start2 - end1);
4408 amt2 = (end1 - start1) + (start2 - end1);
4409 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4410 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4412 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4414 mpos = marker->bytepos;
4415 if (mpos >= start1_byte && mpos < end2_byte)
4417 if (mpos < end1_byte)
4418 mpos += amt1_byte;
4419 else if (mpos < start2_byte)
4420 mpos += diff_byte;
4421 else
4422 mpos -= amt2_byte;
4423 marker->bytepos = mpos;
4425 mpos = marker->charpos;
4426 if (mpos >= start1 && mpos < end2)
4428 if (mpos < end1)
4429 mpos += amt1;
4430 else if (mpos < start2)
4431 mpos += diff;
4432 else
4433 mpos -= amt2;
4435 marker->charpos = mpos;
4439 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4440 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4441 The regions should not be overlapping, because the size of the buffer is
4442 never changed in a transposition.
4444 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4445 any markers that happen to be located in the regions.
4447 Transposing beyond buffer boundaries is an error. */)
4448 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4450 register EMACS_INT start1, end1, start2, end2;
4451 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4452 EMACS_INT gap, len1, len_mid, len2;
4453 unsigned char *start1_addr, *start2_addr, *temp;
4455 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4456 Lisp_Object buf;
4458 XSETBUFFER (buf, current_buffer);
4459 cur_intv = BUF_INTERVALS (current_buffer);
4461 validate_region (&startr1, &endr1);
4462 validate_region (&startr2, &endr2);
4464 start1 = XFASTINT (startr1);
4465 end1 = XFASTINT (endr1);
4466 start2 = XFASTINT (startr2);
4467 end2 = XFASTINT (endr2);
4468 gap = GPT;
4470 /* Swap the regions if they're reversed. */
4471 if (start2 < end1)
4473 register EMACS_INT glumph = start1;
4474 start1 = start2;
4475 start2 = glumph;
4476 glumph = end1;
4477 end1 = end2;
4478 end2 = glumph;
4481 len1 = end1 - start1;
4482 len2 = end2 - start2;
4484 if (start2 < end1)
4485 error ("Transposed regions overlap");
4486 /* Nothing to change for adjacent regions with one being empty */
4487 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4488 return Qnil;
4490 /* The possibilities are:
4491 1. Adjacent (contiguous) regions, or separate but equal regions
4492 (no, really equal, in this case!), or
4493 2. Separate regions of unequal size.
4495 The worst case is usually No. 2. It means that (aside from
4496 potential need for getting the gap out of the way), there also
4497 needs to be a shifting of the text between the two regions. So
4498 if they are spread far apart, we are that much slower... sigh. */
4500 /* It must be pointed out that the really studly thing to do would
4501 be not to move the gap at all, but to leave it in place and work
4502 around it if necessary. This would be extremely efficient,
4503 especially considering that people are likely to do
4504 transpositions near where they are working interactively, which
4505 is exactly where the gap would be found. However, such code
4506 would be much harder to write and to read. So, if you are
4507 reading this comment and are feeling squirrely, by all means have
4508 a go! I just didn't feel like doing it, so I will simply move
4509 the gap the minimum distance to get it out of the way, and then
4510 deal with an unbroken array. */
4512 /* Make sure the gap won't interfere, by moving it out of the text
4513 we will operate on. */
4514 if (start1 < gap && gap < end2)
4516 if (gap - start1 < end2 - gap)
4517 move_gap (start1);
4518 else
4519 move_gap (end2);
4522 start1_byte = CHAR_TO_BYTE (start1);
4523 start2_byte = CHAR_TO_BYTE (start2);
4524 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4525 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4527 #ifdef BYTE_COMBINING_DEBUG
4528 if (end1 == start2)
4530 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4531 len2_byte, start1, start1_byte)
4532 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4533 len1_byte, end2, start2_byte + len2_byte)
4534 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4535 len1_byte, end2, start2_byte + len2_byte))
4536 abort ();
4538 else
4540 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4541 len2_byte, start1, start1_byte)
4542 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4543 len1_byte, start2, start2_byte)
4544 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4545 len2_byte, end1, start1_byte + len1_byte)
4546 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4547 len1_byte, end2, start2_byte + len2_byte))
4548 abort ();
4550 #endif
4552 /* Hmmm... how about checking to see if the gap is large
4553 enough to use as the temporary storage? That would avoid an
4554 allocation... interesting. Later, don't fool with it now. */
4556 /* Working without memmove, for portability (sigh), so must be
4557 careful of overlapping subsections of the array... */
4559 if (end1 == start2) /* adjacent regions */
4561 modify_region (current_buffer, start1, end2, 0);
4562 record_change (start1, len1 + len2);
4564 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4565 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4566 /* Don't use Fset_text_properties: that can cause GC, which can
4567 clobber objects stored in the tmp_intervals. */
4568 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4569 if (!NULL_INTERVAL_P (tmp_interval3))
4570 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4572 /* First region smaller than second. */
4573 if (len1_byte < len2_byte)
4575 USE_SAFE_ALLOCA;
4577 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4579 /* Don't precompute these addresses. We have to compute them
4580 at the last minute, because the relocating allocator might
4581 have moved the buffer around during the xmalloc. */
4582 start1_addr = BYTE_POS_ADDR (start1_byte);
4583 start2_addr = BYTE_POS_ADDR (start2_byte);
4585 memcpy (temp, start2_addr, len2_byte);
4586 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4587 memcpy (start1_addr, temp, len2_byte);
4588 SAFE_FREE ();
4590 else
4591 /* First region not smaller than second. */
4593 USE_SAFE_ALLOCA;
4595 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4596 start1_addr = BYTE_POS_ADDR (start1_byte);
4597 start2_addr = BYTE_POS_ADDR (start2_byte);
4598 memcpy (temp, start1_addr, len1_byte);
4599 memcpy (start1_addr, start2_addr, len2_byte);
4600 memcpy (start1_addr + len2_byte, temp, len1_byte);
4601 SAFE_FREE ();
4603 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4604 len1, current_buffer, 0);
4605 graft_intervals_into_buffer (tmp_interval2, start1,
4606 len2, current_buffer, 0);
4607 update_compositions (start1, start1 + len2, CHECK_BORDER);
4608 update_compositions (start1 + len2, end2, CHECK_TAIL);
4610 /* Non-adjacent regions, because end1 != start2, bleagh... */
4611 else
4613 len_mid = start2_byte - (start1_byte + len1_byte);
4615 if (len1_byte == len2_byte)
4616 /* Regions are same size, though, how nice. */
4618 USE_SAFE_ALLOCA;
4620 modify_region (current_buffer, start1, end1, 0);
4621 modify_region (current_buffer, start2, end2, 0);
4622 record_change (start1, len1);
4623 record_change (start2, len2);
4624 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4625 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4627 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4628 if (!NULL_INTERVAL_P (tmp_interval3))
4629 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4631 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4632 if (!NULL_INTERVAL_P (tmp_interval3))
4633 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4635 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4636 start1_addr = BYTE_POS_ADDR (start1_byte);
4637 start2_addr = BYTE_POS_ADDR (start2_byte);
4638 memcpy (temp, start1_addr, len1_byte);
4639 memcpy (start1_addr, start2_addr, len2_byte);
4640 memcpy (start2_addr, temp, len1_byte);
4641 SAFE_FREE ();
4643 graft_intervals_into_buffer (tmp_interval1, start2,
4644 len1, current_buffer, 0);
4645 graft_intervals_into_buffer (tmp_interval2, start1,
4646 len2, current_buffer, 0);
4649 else if (len1_byte < len2_byte) /* Second region larger than first */
4650 /* Non-adjacent & unequal size, area between must also be shifted. */
4652 USE_SAFE_ALLOCA;
4654 modify_region (current_buffer, start1, end2, 0);
4655 record_change (start1, (end2 - start1));
4656 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4657 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4658 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4660 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4661 if (!NULL_INTERVAL_P (tmp_interval3))
4662 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4664 /* holds region 2 */
4665 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4666 start1_addr = BYTE_POS_ADDR (start1_byte);
4667 start2_addr = BYTE_POS_ADDR (start2_byte);
4668 memcpy (temp, start2_addr, len2_byte);
4669 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4670 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4671 memcpy (start1_addr, temp, len2_byte);
4672 SAFE_FREE ();
4674 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4675 len1, current_buffer, 0);
4676 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4677 len_mid, current_buffer, 0);
4678 graft_intervals_into_buffer (tmp_interval2, start1,
4679 len2, current_buffer, 0);
4681 else
4682 /* Second region smaller than first. */
4684 USE_SAFE_ALLOCA;
4686 record_change (start1, (end2 - start1));
4687 modify_region (current_buffer, start1, end2, 0);
4689 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4690 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4691 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4693 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4694 if (!NULL_INTERVAL_P (tmp_interval3))
4695 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4697 /* holds region 1 */
4698 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4699 start1_addr = BYTE_POS_ADDR (start1_byte);
4700 start2_addr = BYTE_POS_ADDR (start2_byte);
4701 memcpy (temp, start1_addr, len1_byte);
4702 memcpy (start1_addr, start2_addr, len2_byte);
4703 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4704 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4705 SAFE_FREE ();
4707 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4708 len1, current_buffer, 0);
4709 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4710 len_mid, current_buffer, 0);
4711 graft_intervals_into_buffer (tmp_interval2, start1,
4712 len2, current_buffer, 0);
4715 update_compositions (start1, start1 + len2, CHECK_BORDER);
4716 update_compositions (end2 - len1, end2, CHECK_BORDER);
4719 /* When doing multiple transpositions, it might be nice
4720 to optimize this. Perhaps the markers in any one buffer
4721 should be organized in some sorted data tree. */
4722 if (NILP (leave_markers))
4724 transpose_markers (start1, end1, start2, end2,
4725 start1_byte, start1_byte + len1_byte,
4726 start2_byte, start2_byte + len2_byte);
4727 fix_start_end_in_overlays (start1, end2);
4730 signal_after_change (start1, end2 - start1, end2 - start1);
4731 return Qnil;
4735 void
4736 syms_of_editfns (void)
4738 environbuf = 0;
4739 initial_tz = 0;
4741 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4743 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4744 doc: /* Non-nil means text motion commands don't notice fields. */);
4745 Vinhibit_field_text_motion = Qnil;
4747 DEFVAR_LISP ("buffer-access-fontify-functions",
4748 Vbuffer_access_fontify_functions,
4749 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4750 Each function is called with two arguments which specify the range
4751 of the buffer being accessed. */);
4752 Vbuffer_access_fontify_functions = Qnil;
4755 Lisp_Object obuf;
4756 obuf = Fcurrent_buffer ();
4757 /* Do this here, because init_buffer_once is too early--it won't work. */
4758 Fset_buffer (Vprin1_to_string_buffer);
4759 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4760 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4761 Qnil);
4762 Fset_buffer (obuf);
4765 DEFVAR_LISP ("buffer-access-fontified-property",
4766 Vbuffer_access_fontified_property,
4767 doc: /* Property which (if non-nil) indicates text has been fontified.
4768 `buffer-substring' need not call the `buffer-access-fontify-functions'
4769 functions if all the text being accessed has this property. */);
4770 Vbuffer_access_fontified_property = Qnil;
4772 DEFVAR_LISP ("system-name", Vsystem_name,
4773 doc: /* The host name of the machine Emacs is running on. */);
4775 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4776 doc: /* The full name of the user logged in. */);
4778 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4779 doc: /* The user's name, taken from environment variables if possible. */);
4781 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4782 doc: /* The user's name, based upon the real uid only. */);
4784 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4785 doc: /* The release of the operating system Emacs is running on. */);
4787 defsubr (&Spropertize);
4788 defsubr (&Schar_equal);
4789 defsubr (&Sgoto_char);
4790 defsubr (&Sstring_to_char);
4791 defsubr (&Schar_to_string);
4792 defsubr (&Sbyte_to_string);
4793 defsubr (&Sbuffer_substring);
4794 defsubr (&Sbuffer_substring_no_properties);
4795 defsubr (&Sbuffer_string);
4797 defsubr (&Spoint_marker);
4798 defsubr (&Smark_marker);
4799 defsubr (&Spoint);
4800 defsubr (&Sregion_beginning);
4801 defsubr (&Sregion_end);
4803 DEFSYM (Qfield, "field");
4804 DEFSYM (Qboundary, "boundary");
4805 defsubr (&Sfield_beginning);
4806 defsubr (&Sfield_end);
4807 defsubr (&Sfield_string);
4808 defsubr (&Sfield_string_no_properties);
4809 defsubr (&Sdelete_field);
4810 defsubr (&Sconstrain_to_field);
4812 defsubr (&Sline_beginning_position);
4813 defsubr (&Sline_end_position);
4815 /* defsubr (&Smark); */
4816 /* defsubr (&Sset_mark); */
4817 defsubr (&Ssave_excursion);
4818 defsubr (&Ssave_current_buffer);
4820 defsubr (&Sbufsize);
4821 defsubr (&Spoint_max);
4822 defsubr (&Spoint_min);
4823 defsubr (&Spoint_min_marker);
4824 defsubr (&Spoint_max_marker);
4825 defsubr (&Sgap_position);
4826 defsubr (&Sgap_size);
4827 defsubr (&Sposition_bytes);
4828 defsubr (&Sbyte_to_position);
4830 defsubr (&Sbobp);
4831 defsubr (&Seobp);
4832 defsubr (&Sbolp);
4833 defsubr (&Seolp);
4834 defsubr (&Sfollowing_char);
4835 defsubr (&Sprevious_char);
4836 defsubr (&Schar_after);
4837 defsubr (&Schar_before);
4838 defsubr (&Sinsert);
4839 defsubr (&Sinsert_before_markers);
4840 defsubr (&Sinsert_and_inherit);
4841 defsubr (&Sinsert_and_inherit_before_markers);
4842 defsubr (&Sinsert_char);
4843 defsubr (&Sinsert_byte);
4845 defsubr (&Suser_login_name);
4846 defsubr (&Suser_real_login_name);
4847 defsubr (&Suser_uid);
4848 defsubr (&Suser_real_uid);
4849 defsubr (&Suser_full_name);
4850 defsubr (&Semacs_pid);
4851 defsubr (&Scurrent_time);
4852 defsubr (&Sget_internal_run_time);
4853 defsubr (&Sformat_time_string);
4854 defsubr (&Sfloat_time);
4855 defsubr (&Sdecode_time);
4856 defsubr (&Sencode_time);
4857 defsubr (&Scurrent_time_string);
4858 defsubr (&Scurrent_time_zone);
4859 defsubr (&Sset_time_zone_rule);
4860 defsubr (&Ssystem_name);
4861 defsubr (&Smessage);
4862 defsubr (&Smessage_box);
4863 defsubr (&Smessage_or_box);
4864 defsubr (&Scurrent_message);
4865 defsubr (&Sformat);
4867 defsubr (&Sinsert_buffer_substring);
4868 defsubr (&Scompare_buffer_substrings);
4869 defsubr (&Ssubst_char_in_region);
4870 defsubr (&Stranslate_region_internal);
4871 defsubr (&Sdelete_region);
4872 defsubr (&Sdelete_and_extract_region);
4873 defsubr (&Swiden);
4874 defsubr (&Snarrow_to_region);
4875 defsubr (&Ssave_restriction);
4876 defsubr (&Stranspose_regions);