Fix TTY colors breakage by 'clear-face-cache'
[emacs.git] / src / editfns.c
blobd1a6bfbbb1bd25c28257e510f6a0b8663c484566
1 /* Lisp functions pertaining to editing. -*- coding: utf-8 -*-
3 Copyright (C) 1985-1987, 1989, 1993-2018 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 (at
10 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 <https://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
25 #ifdef HAVE_PWD_H
26 #include <pwd.h>
27 #include <grp.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 <errno.h>
48 #include <float.h>
49 #include <limits.h>
51 #include <c-ctype.h>
52 #include <intprops.h>
53 #include <stdlib.h>
54 #include <strftime.h>
55 #include <verify.h>
57 #include "composite.h"
58 #include "intervals.h"
59 #include "character.h"
60 #include "buffer.h"
61 #include "coding.h"
62 #include "window.h"
63 #include "blockinput.h"
65 #define TM_YEAR_BASE 1900
67 #ifdef WINDOWSNT
68 extern Lisp_Object w32_get_internal_run_time (void);
69 #endif
71 static struct lisp_time lisp_time_struct (Lisp_Object, int *);
72 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
73 Lisp_Object, struct tm *);
74 static long int tm_gmtoff (struct tm *);
75 static int tm_diff (struct tm *, struct tm *);
76 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
77 static Lisp_Object styled_format (ptrdiff_t, Lisp_Object *, bool);
79 #ifndef HAVE_TM_GMTOFF
80 # define HAVE_TM_GMTOFF false
81 #endif
83 enum { tzeqlen = sizeof "TZ=" - 1 };
85 /* Time zones equivalent to current local time and to UTC, respectively. */
86 static timezone_t local_tz;
87 static timezone_t const utc_tz = 0;
89 /* The cached value of Vsystem_name. This is used only to compare it
90 to Vsystem_name, so it need not be visible to the GC. */
91 static Lisp_Object cached_system_name;
93 static void
94 init_and_cache_system_name (void)
96 init_system_name ();
97 cached_system_name = Vsystem_name;
100 static struct tm *
101 emacs_localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
103 tm = localtime_rz (tz, t, tm);
104 if (!tm && errno == ENOMEM)
105 memory_full (SIZE_MAX);
106 return tm;
109 static time_t
110 emacs_mktime_z (timezone_t tz, struct tm *tm)
112 errno = 0;
113 time_t t = mktime_z (tz, tm);
114 if (t == (time_t) -1 && errno == ENOMEM)
115 memory_full (SIZE_MAX);
116 return t;
119 /* Allocate a timezone, signaling on failure. */
120 static timezone_t
121 xtzalloc (char const *name)
123 timezone_t tz = tzalloc (name);
124 if (!tz)
125 memory_full (SIZE_MAX);
126 return tz;
129 /* Free a timezone, except do not free the time zone for local time.
130 Freeing utc_tz is also a no-op. */
131 static void
132 xtzfree (timezone_t tz)
134 if (tz != local_tz)
135 tzfree (tz);
138 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
139 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
140 If SETTZ, set Emacs local time to the time zone rule; otherwise,
141 the caller should eventually pass the returned value to xtzfree. */
142 static timezone_t
143 tzlookup (Lisp_Object zone, bool settz)
145 static char const tzbuf_format[] = "<%+.*"pI"d>%s%"pI"d:%02d:%02d";
146 char const *trailing_tzbuf_format = tzbuf_format + sizeof "<%+.*"pI"d" - 1;
147 char tzbuf[sizeof tzbuf_format + 2 * INT_STRLEN_BOUND (EMACS_INT)];
148 char const *zone_string;
149 timezone_t new_tz;
151 if (NILP (zone))
152 return local_tz;
153 else if (EQ (zone, Qt))
155 zone_string = "UTC0";
156 new_tz = utc_tz;
158 else
160 bool plain_integer = INTEGERP (zone);
162 if (EQ (zone, Qwall))
163 zone_string = 0;
164 else if (STRINGP (zone))
165 zone_string = SSDATA (ENCODE_SYSTEM (zone));
166 else if (plain_integer || (CONSP (zone) && INTEGERP (XCAR (zone))
167 && CONSP (XCDR (zone))))
169 Lisp_Object abbr;
170 if (!plain_integer)
172 abbr = XCAR (XCDR (zone));
173 zone = XCAR (zone);
176 EMACS_INT abszone = eabs (XINT (zone)), hour = abszone / (60 * 60);
177 int hour_remainder = abszone % (60 * 60);
178 int min = hour_remainder / 60, sec = hour_remainder % 60;
180 if (plain_integer)
182 int prec = 2;
183 EMACS_INT numzone = hour;
184 if (hour_remainder != 0)
186 prec += 2, numzone = 100 * numzone + min;
187 if (sec != 0)
188 prec += 2, numzone = 100 * numzone + sec;
190 sprintf (tzbuf, tzbuf_format, prec,
191 XINT (zone) < 0 ? -numzone : numzone,
192 &"-"[XINT (zone) < 0], hour, min, sec);
193 zone_string = tzbuf;
195 else
197 AUTO_STRING (leading, "<");
198 AUTO_STRING_WITH_LEN (trailing, tzbuf,
199 sprintf (tzbuf, trailing_tzbuf_format,
200 &"-"[XINT (zone) < 0],
201 hour, min, sec));
202 zone_string = SSDATA (concat3 (leading, ENCODE_SYSTEM (abbr),
203 trailing));
206 else
207 xsignal2 (Qerror, build_string ("Invalid time zone specification"),
208 zone);
209 new_tz = xtzalloc (zone_string);
212 if (settz)
214 block_input ();
215 emacs_setenv_TZ (zone_string);
216 tzset ();
217 timezone_t old_tz = local_tz;
218 local_tz = new_tz;
219 tzfree (old_tz);
220 unblock_input ();
223 return new_tz;
226 void
227 init_editfns (bool dumping)
229 #if !defined CANNOT_DUMP
230 /* A valid but unlikely setting for the TZ environment variable.
231 It is OK (though a bit slower) if the user chooses this value. */
232 static char dump_tz_string[] = "TZ=UtC0";
233 #endif
235 const char *user_name;
236 register char *p;
237 struct passwd *pw; /* password entry for the current user */
238 Lisp_Object tem;
240 /* Set up system_name even when dumping. */
241 init_and_cache_system_name ();
243 #ifndef CANNOT_DUMP
244 /* When just dumping out, set the time zone to a known unlikely value
245 and skip the rest of this function. */
246 if (dumping)
248 xputenv (dump_tz_string);
249 tzset ();
250 return;
252 #endif
254 char *tz = getenv ("TZ");
256 #if !defined CANNOT_DUMP
257 /* If the execution TZ happens to be the same as the dump TZ,
258 change it to some other value and then change it back,
259 to force the underlying implementation to reload the TZ info.
260 This is needed on implementations that load TZ info from files,
261 since the TZ file contents may differ between dump and execution. */
262 if (tz && strcmp (tz, &dump_tz_string[tzeqlen]) == 0)
264 ++*tz;
265 tzset ();
266 --*tz;
268 #endif
270 /* Set the time zone rule now, so that the call to putenv is done
271 before multiple threads are active. */
272 tzlookup (tz ? build_string (tz) : Qwall, true);
274 pw = getpwuid (getuid ());
275 #ifdef MSDOS
276 /* We let the real user name default to "root" because that's quite
277 accurate on MS-DOS and because it lets Emacs find the init file.
278 (The DVX libraries override the Djgpp libraries here.) */
279 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
280 #else
281 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
282 #endif
284 /* Get the effective user name, by consulting environment variables,
285 or the effective uid if those are unset. */
286 user_name = getenv ("LOGNAME");
287 if (!user_name)
288 #ifdef WINDOWSNT
289 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
290 #else /* WINDOWSNT */
291 user_name = getenv ("USER");
292 #endif /* WINDOWSNT */
293 if (!user_name)
295 pw = getpwuid (geteuid ());
296 user_name = pw ? pw->pw_name : "unknown";
298 Vuser_login_name = build_string (user_name);
300 /* If the user name claimed in the environment vars differs from
301 the real uid, use the claimed name to find the full name. */
302 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
303 if (! NILP (tem))
304 tem = Vuser_login_name;
305 else
307 uid_t euid = geteuid ();
308 tem = make_fixnum_or_float (euid);
310 Vuser_full_name = Fuser_full_name (tem);
312 p = getenv ("NAME");
313 if (p)
314 Vuser_full_name = build_string (p);
315 else if (NILP (Vuser_full_name))
316 Vuser_full_name = build_string ("unknown");
318 #ifdef HAVE_SYS_UTSNAME_H
320 struct utsname uts;
321 uname (&uts);
322 Voperating_system_release = build_string (uts.release);
324 #else
325 Voperating_system_release = Qnil;
326 #endif
329 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
330 doc: /* Convert arg CHAR to a string containing that character.
331 usage: (char-to-string CHAR) */)
332 (Lisp_Object character)
334 int c, len;
335 unsigned char str[MAX_MULTIBYTE_LENGTH];
337 CHECK_CHARACTER (character);
338 c = XFASTINT (character);
340 len = CHAR_STRING (c, str);
341 return make_string_from_bytes ((char *) str, 1, len);
344 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
345 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
346 (Lisp_Object byte)
348 unsigned char b;
349 CHECK_NUMBER (byte);
350 if (XINT (byte) < 0 || XINT (byte) > 255)
351 error ("Invalid byte");
352 b = XINT (byte);
353 return make_string_from_bytes ((char *) &b, 1, 1);
356 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
357 doc: /* Return the first character in STRING. */)
358 (register Lisp_Object string)
360 register Lisp_Object val;
361 CHECK_STRING (string);
362 if (SCHARS (string))
364 if (STRING_MULTIBYTE (string))
365 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
366 else
367 XSETFASTINT (val, SREF (string, 0));
369 else
370 XSETFASTINT (val, 0);
371 return val;
374 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
375 doc: /* Return value of point, as an integer.
376 Beginning of buffer is position (point-min). */)
377 (void)
379 Lisp_Object temp;
380 XSETFASTINT (temp, PT);
381 return temp;
384 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
385 doc: /* Return value of point, as a marker object. */)
386 (void)
388 return build_marker (current_buffer, PT, PT_BYTE);
391 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
392 doc: /* Set point to POSITION, a number or marker.
393 Beginning of buffer is position (point-min), end is (point-max).
395 The return value is POSITION. */)
396 (register Lisp_Object position)
398 if (MARKERP (position))
399 set_point_from_marker (position);
400 else if (INTEGERP (position))
401 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
402 else
403 wrong_type_argument (Qinteger_or_marker_p, position);
404 return position;
408 /* Return the start or end position of the region.
409 BEGINNINGP means return the start.
410 If there is no region active, signal an error. */
412 static Lisp_Object
413 region_limit (bool beginningp)
415 Lisp_Object m;
417 if (!NILP (Vtransient_mark_mode)
418 && NILP (Vmark_even_if_inactive)
419 && NILP (BVAR (current_buffer, mark_active)))
420 xsignal0 (Qmark_inactive);
422 m = Fmarker_position (BVAR (current_buffer, mark));
423 if (NILP (m))
424 error ("The mark is not set now, so there is no region");
426 /* Clip to the current narrowing (bug#11770). */
427 return make_number ((PT < XFASTINT (m)) == beginningp
428 ? PT
429 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
432 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
433 doc: /* Return the integer value of point or mark, whichever is smaller. */)
434 (void)
436 return region_limit (1);
439 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
440 doc: /* Return the integer value of point or mark, whichever is larger. */)
441 (void)
443 return region_limit (0);
446 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
447 doc: /* Return this buffer's mark, as a marker object.
448 Watch out! Moving this marker changes the mark position.
449 If you set the marker not to point anywhere, the buffer will have no mark. */)
450 (void)
452 return BVAR (current_buffer, mark);
456 /* Find all the overlays in the current buffer that touch position POS.
457 Return the number found, and store them in a vector in VEC
458 of length LEN. */
460 static ptrdiff_t
461 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
463 Lisp_Object overlay, start, end;
464 struct Lisp_Overlay *tail;
465 ptrdiff_t startpos, endpos;
466 ptrdiff_t idx = 0;
468 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
470 XSETMISC (overlay, tail);
472 end = OVERLAY_END (overlay);
473 endpos = OVERLAY_POSITION (end);
474 if (endpos < pos)
475 break;
476 start = OVERLAY_START (overlay);
477 startpos = OVERLAY_POSITION (start);
478 if (startpos <= pos)
480 if (idx < len)
481 vec[idx] = overlay;
482 /* Keep counting overlays even if we can't return them all. */
483 idx++;
487 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
489 XSETMISC (overlay, tail);
491 start = OVERLAY_START (overlay);
492 startpos = OVERLAY_POSITION (start);
493 if (pos < startpos)
494 break;
495 end = OVERLAY_END (overlay);
496 endpos = OVERLAY_POSITION (end);
497 if (pos <= endpos)
499 if (idx < len)
500 vec[idx] = overlay;
501 idx++;
505 return idx;
508 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
509 doc: /* Return the value of POSITION's property PROP, in OBJECT.
510 Almost identical to `get-char-property' except for the following difference:
511 Whereas `get-char-property' returns the property of the char at (i.e. right
512 after) POSITION, this pays attention to properties's stickiness and overlays's
513 advancement settings, in order to find the property of POSITION itself,
514 i.e. the property that a char would inherit if it were inserted
515 at POSITION. */)
516 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
518 CHECK_NUMBER_COERCE_MARKER (position);
520 if (NILP (object))
521 XSETBUFFER (object, current_buffer);
522 else if (WINDOWP (object))
523 object = XWINDOW (object)->contents;
525 if (!BUFFERP (object))
526 /* pos-property only makes sense in buffers right now, since strings
527 have no overlays and no notion of insertion for which stickiness
528 could be obeyed. */
529 return Fget_text_property (position, prop, object);
530 else
532 EMACS_INT posn = XINT (position);
533 ptrdiff_t noverlays;
534 Lisp_Object *overlay_vec, tem;
535 struct buffer *obuf = current_buffer;
536 USE_SAFE_ALLOCA;
538 set_buffer_temp (XBUFFER (object));
540 /* First try with room for 40 overlays. */
541 Lisp_Object overlay_vecbuf[40];
542 noverlays = ARRAYELTS (overlay_vecbuf);
543 overlay_vec = overlay_vecbuf;
544 noverlays = overlays_around (posn, overlay_vec, noverlays);
546 /* If there are more than 40,
547 make enough space for all, and try again. */
548 if (ARRAYELTS (overlay_vecbuf) < noverlays)
550 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
551 noverlays = overlays_around (posn, overlay_vec, noverlays);
553 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
555 set_buffer_temp (obuf);
557 /* Now check the overlays in order of decreasing priority. */
558 while (--noverlays >= 0)
560 Lisp_Object ol = overlay_vec[noverlays];
561 tem = Foverlay_get (ol, prop);
562 if (!NILP (tem))
564 /* Check the overlay is indeed active at point. */
565 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
566 if ((OVERLAY_POSITION (start) == posn
567 && XMARKER (start)->insertion_type == 1)
568 || (OVERLAY_POSITION (finish) == posn
569 && XMARKER (finish)->insertion_type == 0))
570 ; /* The overlay will not cover a char inserted at point. */
571 else
573 SAFE_FREE ();
574 return tem;
578 SAFE_FREE ();
580 { /* Now check the text properties. */
581 int stickiness = text_property_stickiness (prop, position, object);
582 if (stickiness > 0)
583 return Fget_text_property (position, prop, object);
584 else if (stickiness < 0
585 && XINT (position) > BUF_BEGV (XBUFFER (object)))
586 return Fget_text_property (make_number (XINT (position) - 1),
587 prop, object);
588 else
589 return Qnil;
594 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
595 the value of point is used instead. If BEG or END is null,
596 means don't store the beginning or end of the field.
598 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
599 results; they do not effect boundary behavior.
601 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
602 position of a field, then the beginning of the previous field is
603 returned instead of the beginning of POS's field (since the end of a
604 field is actually also the beginning of the next input field, this
605 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
606 non-nil case, if two fields are separated by a field with the special
607 value `boundary', and POS lies within it, then the two separated
608 fields are considered to be adjacent, and POS between them, when
609 finding the beginning and ending of the "merged" field.
611 Either BEG or END may be 0, in which case the corresponding value
612 is not stored. */
614 static void
615 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
616 Lisp_Object beg_limit,
617 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
619 /* Fields right before and after the point. */
620 Lisp_Object before_field, after_field;
621 /* True if POS counts as the start of a field. */
622 bool at_field_start = 0;
623 /* True if POS counts as the end of a field. */
624 bool at_field_end = 0;
626 if (NILP (pos))
627 XSETFASTINT (pos, PT);
628 else
629 CHECK_NUMBER_COERCE_MARKER (pos);
631 after_field
632 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
633 before_field
634 = (XFASTINT (pos) > BEGV
635 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
636 Qfield, Qnil, NULL)
637 /* Using nil here would be a more obvious choice, but it would
638 fail when the buffer starts with a non-sticky field. */
639 : after_field);
641 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
642 and POS is at beginning of a field, which can also be interpreted
643 as the end of the previous field. Note that the case where if
644 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
645 more natural one; then we avoid treating the beginning of a field
646 specially. */
647 if (NILP (merge_at_boundary))
649 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
650 if (!EQ (field, after_field))
651 at_field_end = 1;
652 if (!EQ (field, before_field))
653 at_field_start = 1;
654 if (NILP (field) && at_field_start && at_field_end)
655 /* If an inserted char would have a nil field while the surrounding
656 text is non-nil, we're probably not looking at a
657 zero-length field, but instead at a non-nil field that's
658 not intended for editing (such as comint's prompts). */
659 at_field_end = at_field_start = 0;
662 /* Note about special `boundary' fields:
664 Consider the case where the point (`.') is between the fields `x' and `y':
666 xxxx.yyyy
668 In this situation, if merge_at_boundary is non-nil, consider the
669 `x' and `y' fields as forming one big merged field, and so the end
670 of the field is the end of `y'.
672 However, if `x' and `y' are separated by a special `boundary' field
673 (a field with a `field' char-property of 'boundary), then ignore
674 this special field when merging adjacent fields. Here's the same
675 situation, but with a `boundary' field between the `x' and `y' fields:
677 xxx.BBBByyyy
679 Here, if point is at the end of `x', the beginning of `y', or
680 anywhere in-between (within the `boundary' field), merge all
681 three fields and consider the beginning as being the beginning of
682 the `x' field, and the end as being the end of the `y' field. */
684 if (beg)
686 if (at_field_start)
687 /* POS is at the edge of a field, and we should consider it as
688 the beginning of the following field. */
689 *beg = XFASTINT (pos);
690 else
691 /* Find the previous field boundary. */
693 Lisp_Object p = pos;
694 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
695 /* Skip a `boundary' field. */
696 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
697 beg_limit);
699 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
700 beg_limit);
701 *beg = NILP (p) ? BEGV : XFASTINT (p);
705 if (end)
707 if (at_field_end)
708 /* POS is at the edge of a field, and we should consider it as
709 the end of the previous field. */
710 *end = XFASTINT (pos);
711 else
712 /* Find the next field boundary. */
714 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
715 /* Skip a `boundary' field. */
716 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
717 end_limit);
719 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
720 end_limit);
721 *end = NILP (pos) ? ZV : XFASTINT (pos);
727 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
728 doc: /* Delete the field surrounding POS.
729 A field is a region of text with the same `field' property.
730 If POS is nil, the value of point is used for POS. */)
731 (Lisp_Object pos)
733 ptrdiff_t beg, end;
734 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
735 if (beg != end)
736 del_range (beg, end);
737 return Qnil;
740 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
741 doc: /* Return the contents of the field surrounding POS as a string.
742 A field is a region of text with the same `field' property.
743 If POS is nil, the value of point is used for POS. */)
744 (Lisp_Object pos)
746 ptrdiff_t beg, end;
747 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
748 return make_buffer_string (beg, end, 1);
751 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
752 doc: /* Return the contents of the field around POS, without text properties.
753 A field is a region of text with the same `field' property.
754 If POS is nil, the value of point is used for POS. */)
755 (Lisp_Object pos)
757 ptrdiff_t beg, end;
758 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
759 return make_buffer_string (beg, end, 0);
762 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
763 doc: /* Return the beginning of the field surrounding POS.
764 A field is a region of text with the same `field' property.
765 If POS is nil, the value of point is used for POS.
766 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
767 field, then the beginning of the *previous* field is returned.
768 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
769 is before LIMIT, then LIMIT will be returned instead. */)
770 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
772 ptrdiff_t beg;
773 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
774 return make_number (beg);
777 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
778 doc: /* Return the end of the field surrounding POS.
779 A field is a region of text with the same `field' property.
780 If POS is nil, the value of point is used for POS.
781 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
782 then the end of the *following* field is returned.
783 If LIMIT is non-nil, it is a buffer position; if the end of the field
784 is after LIMIT, then LIMIT will be returned instead. */)
785 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
787 ptrdiff_t end;
788 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
789 return make_number (end);
792 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
793 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
794 A field is a region of text with the same `field' property.
796 If NEW-POS is nil, then use the current point instead, and move point
797 to the resulting constrained position, in addition to returning that
798 position.
800 If OLD-POS is at the boundary of two fields, then the allowable
801 positions for NEW-POS depends on the value of the optional argument
802 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
803 constrained to the field that has the same `field' char-property
804 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
805 is non-nil, NEW-POS is constrained to the union of the two adjacent
806 fields. Additionally, if two fields are separated by another field with
807 the special value `boundary', then any point within this special field is
808 also considered to be `on the boundary'.
810 If the optional argument ONLY-IN-LINE is non-nil and constraining
811 NEW-POS would move it to a different line, NEW-POS is returned
812 unconstrained. This is useful for commands that move by line, like
813 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
814 only in the case where they can still move to the right line.
816 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
817 a non-nil property of that name, then any field boundaries are ignored.
819 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
820 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
821 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
823 /* If non-zero, then the original point, before re-positioning. */
824 ptrdiff_t orig_point = 0;
825 bool fwd;
826 Lisp_Object prev_old, prev_new;
828 if (NILP (new_pos))
829 /* Use the current point, and afterwards, set it. */
831 orig_point = PT;
832 XSETFASTINT (new_pos, PT);
835 CHECK_NUMBER_COERCE_MARKER (new_pos);
836 CHECK_NUMBER_COERCE_MARKER (old_pos);
838 fwd = (XINT (new_pos) > XINT (old_pos));
840 prev_old = make_number (XINT (old_pos) - 1);
841 prev_new = make_number (XINT (new_pos) - 1);
843 if (NILP (Vinhibit_field_text_motion)
844 && !EQ (new_pos, old_pos)
845 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
846 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
847 /* To recognize field boundaries, we must also look at the
848 previous positions; we could use `Fget_pos_property'
849 instead, but in itself that would fail inside non-sticky
850 fields (like comint prompts). */
851 || (XFASTINT (new_pos) > BEGV
852 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
853 || (XFASTINT (old_pos) > BEGV
854 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
855 && (NILP (inhibit_capture_property)
856 /* Field boundaries are again a problem; but now we must
857 decide the case exactly, so we need to call
858 `get_pos_property' as well. */
859 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
860 && (XFASTINT (old_pos) <= BEGV
861 || NILP (Fget_char_property
862 (old_pos, inhibit_capture_property, Qnil))
863 || NILP (Fget_char_property
864 (prev_old, inhibit_capture_property, Qnil))))))
865 /* It is possible that NEW_POS is not within the same field as
866 OLD_POS; try to move NEW_POS so that it is. */
868 ptrdiff_t shortage;
869 Lisp_Object field_bound;
871 if (fwd)
872 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
873 else
874 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
876 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
877 other side of NEW_POS, which would mean that NEW_POS is
878 already acceptable, and it's not necessary to constrain it
879 to FIELD_BOUND. */
880 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
881 /* NEW_POS should be constrained, but only if either
882 ONLY_IN_LINE is nil (in which case any constraint is OK),
883 or NEW_POS and FIELD_BOUND are on the same line (in which
884 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
885 && (NILP (only_in_line)
886 /* This is the ONLY_IN_LINE case, check that NEW_POS and
887 FIELD_BOUND are on the same line by seeing whether
888 there's an intervening newline or not. */
889 || (find_newline (XFASTINT (new_pos), -1,
890 XFASTINT (field_bound), -1,
891 fwd ? -1 : 1, &shortage, NULL, 1),
892 shortage != 0)))
893 /* Constrain NEW_POS to FIELD_BOUND. */
894 new_pos = field_bound;
896 if (orig_point && XFASTINT (new_pos) != orig_point)
897 /* The NEW_POS argument was originally nil, so automatically set PT. */
898 SET_PT (XFASTINT (new_pos));
901 return new_pos;
905 DEFUN ("line-beginning-position",
906 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
907 doc: /* Return the character position of the first character on the current line.
908 With optional argument N, scan forward N - 1 lines first.
909 If the scan reaches the end of the buffer, return that position.
911 This function ignores text display directionality; it returns the
912 position of the first character in logical order, i.e. the smallest
913 character position on the line.
915 This function constrains the returned position to the current field
916 unless that position would be on a different line than the original,
917 unconstrained result. If N is nil or 1, and a front-sticky field
918 starts at point, the scan stops as soon as it starts. To ignore field
919 boundaries, bind `inhibit-field-text-motion' to t.
921 This function does not move point. */)
922 (Lisp_Object n)
924 ptrdiff_t charpos, bytepos;
926 if (NILP (n))
927 XSETFASTINT (n, 1);
928 else
929 CHECK_NUMBER (n);
931 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
933 /* Return END constrained to the current input field. */
934 return Fconstrain_to_field (make_number (charpos), make_number (PT),
935 XINT (n) != 1 ? Qt : Qnil,
936 Qt, Qnil);
939 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
940 doc: /* Return the character position of the last character on the current line.
941 With argument N not nil or 1, move forward N - 1 lines first.
942 If scan reaches end of buffer, return that position.
944 This function ignores text display directionality; it returns the
945 position of the last character in logical order, i.e. the largest
946 character position on the line.
948 This function constrains the returned position to the current field
949 unless that would be on a different line than the original,
950 unconstrained result. If N is nil or 1, and a rear-sticky field ends
951 at point, the scan stops as soon as it starts. To ignore field
952 boundaries bind `inhibit-field-text-motion' to t.
954 This function does not move point. */)
955 (Lisp_Object n)
957 ptrdiff_t clipped_n;
958 ptrdiff_t end_pos;
959 ptrdiff_t orig = PT;
961 if (NILP (n))
962 XSETFASTINT (n, 1);
963 else
964 CHECK_NUMBER (n);
966 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
967 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
968 NULL);
970 /* Return END_POS constrained to the current input field. */
971 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
972 Qnil, Qt, Qnil);
975 /* Save current buffer state for `save-excursion' special form.
976 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
977 offload some work from GC. */
979 Lisp_Object
980 save_excursion_save (void)
982 return make_save_obj_obj_obj_obj
983 (Fpoint_marker (),
984 Qnil,
985 /* Selected window if current buffer is shown in it, nil otherwise. */
986 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
987 ? selected_window : Qnil),
988 Qnil);
991 /* Restore saved buffer before leaving `save-excursion' special form. */
993 void
994 save_excursion_restore (Lisp_Object info)
996 Lisp_Object tem, tem1;
998 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
999 /* If we're unwinding to top level, saved buffer may be deleted. This
1000 means that all of its markers are unchained and so tem is nil. */
1001 if (NILP (tem))
1002 goto out;
1004 Fset_buffer (tem);
1006 /* Point marker. */
1007 tem = XSAVE_OBJECT (info, 0);
1008 Fgoto_char (tem);
1009 unchain_marker (XMARKER (tem));
1011 /* If buffer was visible in a window, and a different window was
1012 selected, and the old selected window is still showing this
1013 buffer, restore point in that window. */
1014 tem = XSAVE_OBJECT (info, 2);
1015 if (WINDOWP (tem)
1016 && !EQ (tem, selected_window)
1017 && (tem1 = XWINDOW (tem)->contents,
1018 (/* Window is live... */
1019 BUFFERP (tem1)
1020 /* ...and it shows the current buffer. */
1021 && XBUFFER (tem1) == current_buffer)))
1022 Fset_window_point (tem, make_number (PT));
1024 out:
1026 free_misc (info);
1029 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
1030 doc: /* Save point, and current buffer; execute BODY; restore those things.
1031 Executes BODY just like `progn'.
1032 The values of point and the current buffer are restored
1033 even in case of abnormal exit (throw or error).
1035 If you only want to save the current buffer but not point,
1036 then just use `save-current-buffer', or even `with-current-buffer'.
1038 Before Emacs 25.1, `save-excursion' used to save the mark state.
1039 To save the mark state as well as point and the current buffer, use
1040 `save-mark-and-excursion'.
1042 usage: (save-excursion &rest BODY) */)
1043 (Lisp_Object args)
1045 register Lisp_Object val;
1046 ptrdiff_t count = SPECPDL_INDEX ();
1048 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1050 val = Fprogn (args);
1051 return unbind_to (count, val);
1054 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1055 doc: /* Record which buffer is current; execute BODY; make that buffer current.
1056 BODY is executed just like `progn'.
1057 usage: (save-current-buffer &rest BODY) */)
1058 (Lisp_Object args)
1060 ptrdiff_t count = SPECPDL_INDEX ();
1062 record_unwind_current_buffer ();
1063 return unbind_to (count, Fprogn (args));
1066 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
1067 doc: /* Return the number of characters in the current buffer.
1068 If BUFFER is not nil, return the number of characters in that buffer
1069 instead.
1071 This does not take narrowing into account; to count the number of
1072 characters in the accessible portion of the current buffer, use
1073 `(- (point-max) (point-min))', and to count the number of characters
1074 in some other BUFFER, use
1075 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1076 (Lisp_Object buffer)
1078 if (NILP (buffer))
1079 return make_number (Z - BEG);
1080 else
1082 CHECK_BUFFER (buffer);
1083 return make_number (BUF_Z (XBUFFER (buffer))
1084 - BUF_BEG (XBUFFER (buffer)));
1088 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1089 doc: /* Return the minimum permissible value of point in the current buffer.
1090 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1091 (void)
1093 Lisp_Object temp;
1094 XSETFASTINT (temp, BEGV);
1095 return temp;
1098 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1099 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1100 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1101 (void)
1103 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1106 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1107 doc: /* Return the maximum permissible value of point in the current buffer.
1108 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1109 is in effect, in which case it is less. */)
1110 (void)
1112 Lisp_Object temp;
1113 XSETFASTINT (temp, ZV);
1114 return temp;
1117 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1118 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1119 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1120 is in effect, in which case it is less. */)
1121 (void)
1123 return build_marker (current_buffer, ZV, ZV_BYTE);
1126 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1127 doc: /* Return the position of the gap, in the current buffer.
1128 See also `gap-size'. */)
1129 (void)
1131 Lisp_Object temp;
1132 XSETFASTINT (temp, GPT);
1133 return temp;
1136 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1137 doc: /* Return the size of the current buffer's gap.
1138 See also `gap-position'. */)
1139 (void)
1141 Lisp_Object temp;
1142 XSETFASTINT (temp, GAP_SIZE);
1143 return temp;
1146 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1147 doc: /* Return the byte position for character position POSITION.
1148 If POSITION is out of range, the value is nil. */)
1149 (Lisp_Object position)
1151 CHECK_NUMBER_COERCE_MARKER (position);
1152 if (XINT (position) < BEG || XINT (position) > Z)
1153 return Qnil;
1154 return make_number (CHAR_TO_BYTE (XINT (position)));
1157 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1158 doc: /* Return the character position for byte position BYTEPOS.
1159 If BYTEPOS is out of range, the value is nil. */)
1160 (Lisp_Object bytepos)
1162 ptrdiff_t pos_byte;
1164 CHECK_NUMBER (bytepos);
1165 pos_byte = XINT (bytepos);
1166 if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
1167 return Qnil;
1168 if (Z != Z_BYTE)
1169 /* There are multibyte characters in the buffer.
1170 The argument of BYTE_TO_CHAR must be a byte position at
1171 a character boundary, so search for the start of the current
1172 character. */
1173 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte)))
1174 pos_byte--;
1175 return make_number (BYTE_TO_CHAR (pos_byte));
1178 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1179 doc: /* Return the character following point, as a number.
1180 At the end of the buffer or accessible region, return 0. */)
1181 (void)
1183 Lisp_Object temp;
1184 if (PT >= ZV)
1185 XSETFASTINT (temp, 0);
1186 else
1187 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1188 return temp;
1191 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1192 doc: /* Return the character preceding point, as a number.
1193 At the beginning of the buffer or accessible region, return 0. */)
1194 (void)
1196 Lisp_Object temp;
1197 if (PT <= BEGV)
1198 XSETFASTINT (temp, 0);
1199 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1201 ptrdiff_t pos = PT_BYTE;
1202 DEC_POS (pos);
1203 XSETFASTINT (temp, FETCH_CHAR (pos));
1205 else
1206 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1207 return temp;
1210 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1211 doc: /* Return t if point is at the beginning of the buffer.
1212 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1213 (void)
1215 if (PT == BEGV)
1216 return Qt;
1217 return Qnil;
1220 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1221 doc: /* Return t if point is at the end of the buffer.
1222 If the buffer is narrowed, this means the end of the narrowed part. */)
1223 (void)
1225 if (PT == ZV)
1226 return Qt;
1227 return Qnil;
1230 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1231 doc: /* Return t if point is at the beginning of a line. */)
1232 (void)
1234 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1235 return Qt;
1236 return Qnil;
1239 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1240 doc: /* Return t if point is at the end of a line.
1241 `End of a line' includes point being at the end of the buffer. */)
1242 (void)
1244 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1245 return Qt;
1246 return Qnil;
1249 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1250 doc: /* Return character in current buffer at position POS.
1251 POS is an integer or a marker and defaults to point.
1252 If POS is out of range, the value is nil. */)
1253 (Lisp_Object pos)
1255 register ptrdiff_t pos_byte;
1257 if (NILP (pos))
1259 pos_byte = PT_BYTE;
1260 XSETFASTINT (pos, PT);
1263 if (MARKERP (pos))
1265 pos_byte = marker_byte_position (pos);
1266 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1267 return Qnil;
1269 else
1271 CHECK_NUMBER_COERCE_MARKER (pos);
1272 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1273 return Qnil;
1275 pos_byte = CHAR_TO_BYTE (XINT (pos));
1278 return make_number (FETCH_CHAR (pos_byte));
1281 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1282 doc: /* Return character in current buffer preceding position POS.
1283 POS is an integer or a marker and defaults to point.
1284 If POS is out of range, the value is nil. */)
1285 (Lisp_Object pos)
1287 register Lisp_Object val;
1288 register ptrdiff_t pos_byte;
1290 if (NILP (pos))
1292 pos_byte = PT_BYTE;
1293 XSETFASTINT (pos, PT);
1296 if (MARKERP (pos))
1298 pos_byte = marker_byte_position (pos);
1300 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1301 return Qnil;
1303 else
1305 CHECK_NUMBER_COERCE_MARKER (pos);
1307 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1308 return Qnil;
1310 pos_byte = CHAR_TO_BYTE (XINT (pos));
1313 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1315 DEC_POS (pos_byte);
1316 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1318 else
1320 pos_byte--;
1321 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1323 return val;
1326 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1327 doc: /* Return the name under which the user logged in, as a string.
1328 This is based on the effective uid, not the real uid.
1329 Also, if the environment variables LOGNAME or USER are set,
1330 that determines the value of this function.
1332 If optional argument UID is an integer or a float, return the login name
1333 of the user with that uid, or nil if there is no such user. */)
1334 (Lisp_Object uid)
1336 struct passwd *pw;
1337 uid_t id;
1339 /* Set up the user name info if we didn't do it before.
1340 (That can happen if Emacs is dumpable
1341 but you decide to run `temacs -l loadup' and not dump. */
1342 if (NILP (Vuser_login_name))
1343 init_editfns (false);
1345 if (NILP (uid))
1346 return Vuser_login_name;
1348 CONS_TO_INTEGER (uid, uid_t, id);
1349 block_input ();
1350 pw = getpwuid (id);
1351 unblock_input ();
1352 return (pw ? build_string (pw->pw_name) : Qnil);
1355 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1356 0, 0, 0,
1357 doc: /* Return the name of the user's real uid, as a string.
1358 This ignores the environment variables LOGNAME and USER, so it differs from
1359 `user-login-name' when running under `su'. */)
1360 (void)
1362 /* Set up the user name info if we didn't do it before.
1363 (That can happen if Emacs is dumpable
1364 but you decide to run `temacs -l loadup' and not dump. */
1365 if (NILP (Vuser_login_name))
1366 init_editfns (false);
1367 return Vuser_real_login_name;
1370 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1371 doc: /* Return the effective uid of Emacs.
1372 Value is an integer or a float, depending on the value. */)
1373 (void)
1375 uid_t euid = geteuid ();
1376 return make_fixnum_or_float (euid);
1379 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1380 doc: /* Return the real uid of Emacs.
1381 Value is an integer or a float, depending on the value. */)
1382 (void)
1384 uid_t uid = getuid ();
1385 return make_fixnum_or_float (uid);
1388 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1389 doc: /* Return the effective gid of Emacs.
1390 Value is an integer or a float, depending on the value. */)
1391 (void)
1393 gid_t egid = getegid ();
1394 return make_fixnum_or_float (egid);
1397 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1398 doc: /* Return the real gid of Emacs.
1399 Value is an integer or a float, depending on the value. */)
1400 (void)
1402 gid_t gid = getgid ();
1403 return make_fixnum_or_float (gid);
1406 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1407 doc: /* Return the full name of the user logged in, as a string.
1408 If the full name corresponding to Emacs's userid is not known,
1409 return "unknown".
1411 If optional argument UID is an integer or float, return the full name
1412 of the user with that uid, or nil if there is no such user.
1413 If UID is a string, return the full name of the user with that login
1414 name, or nil if there is no such user. */)
1415 (Lisp_Object uid)
1417 struct passwd *pw;
1418 register char *p, *q;
1419 Lisp_Object full;
1421 if (NILP (uid))
1422 return Vuser_full_name;
1423 else if (NUMBERP (uid))
1425 uid_t u;
1426 CONS_TO_INTEGER (uid, uid_t, u);
1427 block_input ();
1428 pw = getpwuid (u);
1429 unblock_input ();
1431 else if (STRINGP (uid))
1433 block_input ();
1434 pw = getpwnam (SSDATA (uid));
1435 unblock_input ();
1437 else
1438 error ("Invalid UID specification");
1440 if (!pw)
1441 return Qnil;
1443 p = USER_FULL_NAME;
1444 /* Chop off everything after the first comma. */
1445 q = strchr (p, ',');
1446 full = make_string (p, q ? q - p : strlen (p));
1448 #ifdef AMPERSAND_FULL_NAME
1449 p = SSDATA (full);
1450 q = strchr (p, '&');
1451 /* Substitute the login name for the &, upcasing the first character. */
1452 if (q)
1454 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1455 USE_SAFE_ALLOCA;
1456 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1457 memcpy (r, p, q - p);
1458 char *s = lispstpcpy (&r[q - p], login);
1459 r[q - p] = upcase ((unsigned char) r[q - p]);
1460 strcpy (s, q + 1);
1461 full = build_string (r);
1462 SAFE_FREE ();
1464 #endif /* AMPERSAND_FULL_NAME */
1466 return full;
1469 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1470 doc: /* Return the host name of the machine you are running on, as a string. */)
1471 (void)
1473 if (EQ (Vsystem_name, cached_system_name))
1474 init_and_cache_system_name ();
1475 return Vsystem_name;
1478 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1479 doc: /* Return the process ID of Emacs, as a number. */)
1480 (void)
1482 pid_t pid = getpid ();
1483 return make_fixnum_or_float (pid);
1488 #ifndef TIME_T_MIN
1489 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1490 #endif
1491 #ifndef TIME_T_MAX
1492 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1493 #endif
1495 /* Report that a time value is out of range for Emacs. */
1496 void
1497 time_overflow (void)
1499 error ("Specified time is not representable");
1502 static _Noreturn void
1503 invalid_time (void)
1505 error ("Invalid time specification");
1508 /* Check a return value compatible with that of decode_time_components. */
1509 static void
1510 check_time_validity (int validity)
1512 if (validity <= 0)
1514 if (validity < 0)
1515 time_overflow ();
1516 else
1517 invalid_time ();
1521 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1522 static EMACS_INT
1523 hi_time (time_t t)
1525 time_t hi = t >> LO_TIME_BITS;
1526 if (FIXNUM_OVERFLOW_P (hi))
1527 time_overflow ();
1528 return hi;
1531 /* Return the bottom bits of the time T. */
1532 static int
1533 lo_time (time_t t)
1535 return t & ((1 << LO_TIME_BITS) - 1);
1538 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1539 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1540 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1541 HIGH has the most significant bits of the seconds, while LOW has the
1542 least significant 16 bits. USEC and PSEC are the microsecond and
1543 picosecond counts. */)
1544 (void)
1546 return make_lisp_time (current_timespec ());
1549 static struct lisp_time
1550 time_add (struct lisp_time ta, struct lisp_time tb)
1552 EMACS_INT hi = ta.hi + tb.hi;
1553 int lo = ta.lo + tb.lo;
1554 int us = ta.us + tb.us;
1555 int ps = ta.ps + tb.ps;
1556 us += (1000000 <= ps);
1557 ps -= (1000000 <= ps) * 1000000;
1558 lo += (1000000 <= us);
1559 us -= (1000000 <= us) * 1000000;
1560 hi += (1 << LO_TIME_BITS <= lo);
1561 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1562 return (struct lisp_time) { hi, lo, us, ps };
1565 static struct lisp_time
1566 time_subtract (struct lisp_time ta, struct lisp_time tb)
1568 EMACS_INT hi = ta.hi - tb.hi;
1569 int lo = ta.lo - tb.lo;
1570 int us = ta.us - tb.us;
1571 int ps = ta.ps - tb.ps;
1572 us -= (ps < 0);
1573 ps += (ps < 0) * 1000000;
1574 lo -= (us < 0);
1575 us += (us < 0) * 1000000;
1576 hi -= (lo < 0);
1577 lo += (lo < 0) << LO_TIME_BITS;
1578 return (struct lisp_time) { hi, lo, us, ps };
1581 static Lisp_Object
1582 time_arith (Lisp_Object a, Lisp_Object b,
1583 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1585 int alen, blen;
1586 struct lisp_time ta = lisp_time_struct (a, &alen);
1587 struct lisp_time tb = lisp_time_struct (b, &blen);
1588 struct lisp_time t = op (ta, tb);
1589 if (FIXNUM_OVERFLOW_P (t.hi))
1590 time_overflow ();
1591 Lisp_Object val = Qnil;
1593 switch (max (alen, blen))
1595 default:
1596 val = Fcons (make_number (t.ps), val);
1597 FALLTHROUGH;
1598 case 3:
1599 val = Fcons (make_number (t.us), val);
1600 FALLTHROUGH;
1601 case 2:
1602 val = Fcons (make_number (t.lo), val);
1603 val = Fcons (make_number (t.hi), val);
1604 break;
1607 return val;
1610 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1611 doc: /* Return the sum of two time values A and B, as a time value.
1612 A nil value for either argument stands for the current time.
1613 See `current-time-string' for the various forms of a time value. */)
1614 (Lisp_Object a, Lisp_Object b)
1616 return time_arith (a, b, time_add);
1619 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1620 doc: /* Return the difference between two time values A and B, as a time value.
1621 Use `float-time' to convert the difference into elapsed seconds.
1622 A nil value for either argument stands for the current time.
1623 See `current-time-string' for the various forms of a time value. */)
1624 (Lisp_Object a, Lisp_Object b)
1626 return time_arith (a, b, time_subtract);
1629 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1630 doc: /* Return non-nil if time value T1 is earlier than time value T2.
1631 A nil value for either argument stands for the current time.
1632 See `current-time-string' for the various forms of a time value. */)
1633 (Lisp_Object t1, Lisp_Object t2)
1635 int t1len, t2len;
1636 struct lisp_time a = lisp_time_struct (t1, &t1len);
1637 struct lisp_time b = lisp_time_struct (t2, &t2len);
1638 return ((a.hi != b.hi ? a.hi < b.hi
1639 : a.lo != b.lo ? a.lo < b.lo
1640 : a.us != b.us ? a.us < b.us
1641 : a.ps < b.ps)
1642 ? Qt : Qnil);
1646 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1647 0, 0, 0,
1648 doc: /* Return the current run time used by Emacs.
1649 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1650 style as (current-time).
1652 On systems that can't determine the run time, `get-internal-run-time'
1653 does the same thing as `current-time'. */)
1654 (void)
1656 #ifdef HAVE_GETRUSAGE
1657 struct rusage usage;
1658 time_t secs;
1659 int usecs;
1661 if (getrusage (RUSAGE_SELF, &usage) < 0)
1662 /* This shouldn't happen. What action is appropriate? */
1663 xsignal0 (Qerror);
1665 /* Sum up user time and system time. */
1666 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1667 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1668 if (usecs >= 1000000)
1670 usecs -= 1000000;
1671 secs++;
1673 return make_lisp_time (make_timespec (secs, usecs * 1000));
1674 #else /* ! HAVE_GETRUSAGE */
1675 #ifdef WINDOWSNT
1676 return w32_get_internal_run_time ();
1677 #else /* ! WINDOWSNT */
1678 return Fcurrent_time ();
1679 #endif /* WINDOWSNT */
1680 #endif /* HAVE_GETRUSAGE */
1684 /* Make a Lisp list that represents the Emacs time T. T may be an
1685 invalid time, with a slightly negative tv_nsec value such as
1686 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1687 correspondingly negative picosecond count. */
1688 Lisp_Object
1689 make_lisp_time (struct timespec t)
1691 time_t s = t.tv_sec;
1692 int ns = t.tv_nsec;
1693 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1696 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1697 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1698 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1699 if successful, 0 if unsuccessful. */
1700 static int
1701 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1702 Lisp_Object *plow, Lisp_Object *pusec,
1703 Lisp_Object *ppsec)
1705 Lisp_Object high = make_number (0);
1706 Lisp_Object low = specified_time;
1707 Lisp_Object usec = make_number (0);
1708 Lisp_Object psec = make_number (0);
1709 int len = 4;
1711 if (CONSP (specified_time))
1713 high = XCAR (specified_time);
1714 low = XCDR (specified_time);
1715 if (CONSP (low))
1717 Lisp_Object low_tail = XCDR (low);
1718 low = XCAR (low);
1719 if (CONSP (low_tail))
1721 usec = XCAR (low_tail);
1722 low_tail = XCDR (low_tail);
1723 if (CONSP (low_tail))
1724 psec = XCAR (low_tail);
1725 else
1726 len = 3;
1728 else if (!NILP (low_tail))
1730 usec = low_tail;
1731 len = 3;
1733 else
1734 len = 2;
1736 else
1737 len = 2;
1739 /* When combining components, require LOW to be an integer,
1740 as otherwise it would be a pain to add up times. */
1741 if (! INTEGERP (low))
1742 return 0;
1744 else if (INTEGERP (specified_time))
1745 len = 2;
1747 *phigh = high;
1748 *plow = low;
1749 *pusec = usec;
1750 *ppsec = psec;
1751 return len;
1754 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1755 Return true if T is in range, false otherwise. */
1756 static bool
1757 decode_float_time (double t, struct lisp_time *result)
1759 double lo_multiplier = 1 << LO_TIME_BITS;
1760 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1761 if (! (emacs_time_min <= t && t < -emacs_time_min))
1762 return false;
1764 double small_t = t / lo_multiplier;
1765 EMACS_INT hi = small_t;
1766 double t_sans_hi = t - hi * lo_multiplier;
1767 int lo = t_sans_hi;
1768 long double fracps = (t_sans_hi - lo) * 1e12L;
1769 #ifdef INT_FAST64_MAX
1770 int_fast64_t ifracps = fracps;
1771 int us = ifracps / 1000000;
1772 int ps = ifracps % 1000000;
1773 #else
1774 int us = fracps / 1e6L;
1775 int ps = fracps - us * 1e6L;
1776 #endif
1777 us -= (ps < 0);
1778 ps += (ps < 0) * 1000000;
1779 lo -= (us < 0);
1780 us += (us < 0) * 1000000;
1781 hi -= (lo < 0);
1782 lo += (lo < 0) << LO_TIME_BITS;
1783 result->hi = hi;
1784 result->lo = lo;
1785 result->us = us;
1786 result->ps = ps;
1787 return true;
1790 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1791 list, generate the corresponding time value.
1792 If LOW is floating point, the other components should be zero.
1794 If RESULT is not null, store into *RESULT the converted time.
1795 If *DRESULT is not null, store into *DRESULT the number of
1796 seconds since the start of the POSIX Epoch.
1798 Return 1 if successful, 0 if the components are of the
1799 wrong type, and -1 if the time is out of range. */
1801 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1802 Lisp_Object psec,
1803 struct lisp_time *result, double *dresult)
1805 EMACS_INT hi, lo, us, ps;
1806 if (! (INTEGERP (high)
1807 && INTEGERP (usec) && INTEGERP (psec)))
1808 return 0;
1809 if (! INTEGERP (low))
1811 if (FLOATP (low))
1813 double t = XFLOAT_DATA (low);
1814 if (result && ! decode_float_time (t, result))
1815 return -1;
1816 if (dresult)
1817 *dresult = t;
1818 return 1;
1820 else if (NILP (low))
1822 struct timespec now = current_timespec ();
1823 if (result)
1825 result->hi = hi_time (now.tv_sec);
1826 result->lo = lo_time (now.tv_sec);
1827 result->us = now.tv_nsec / 1000;
1828 result->ps = now.tv_nsec % 1000 * 1000;
1830 if (dresult)
1831 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1832 return 1;
1834 else
1835 return 0;
1838 hi = XINT (high);
1839 lo = XINT (low);
1840 us = XINT (usec);
1841 ps = XINT (psec);
1843 /* Normalize out-of-range lower-order components by carrying
1844 each overflow into the next higher-order component. */
1845 us += ps / 1000000 - (ps % 1000000 < 0);
1846 lo += us / 1000000 - (us % 1000000 < 0);
1847 hi += lo >> LO_TIME_BITS;
1848 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1849 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1850 lo &= (1 << LO_TIME_BITS) - 1;
1852 if (result)
1854 if (FIXNUM_OVERFLOW_P (hi))
1855 return -1;
1856 result->hi = hi;
1857 result->lo = lo;
1858 result->us = us;
1859 result->ps = ps;
1862 if (dresult)
1864 double dhi = hi;
1865 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1868 return 1;
1871 struct timespec
1872 lisp_to_timespec (struct lisp_time t)
1874 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1875 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1876 return invalid_timespec ();
1877 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1878 int ns = t.us * 1000 + t.ps / 1000;
1879 return make_timespec (s, ns);
1882 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1883 Store its effective length into *PLEN.
1884 If SPECIFIED_TIME is nil, use the current time.
1885 Signal an error if SPECIFIED_TIME does not represent a time. */
1886 static struct lisp_time
1887 lisp_time_struct (Lisp_Object specified_time, int *plen)
1889 Lisp_Object high, low, usec, psec;
1890 struct lisp_time t;
1891 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1892 if (!len)
1893 invalid_time ();
1894 int val = decode_time_components (high, low, usec, psec, &t, 0);
1895 check_time_validity (val);
1896 *plen = len;
1897 return t;
1900 /* Like lisp_time_struct, except return a struct timespec.
1901 Discard any low-order digits. */
1902 struct timespec
1903 lisp_time_argument (Lisp_Object specified_time)
1905 int len;
1906 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1907 struct timespec t = lisp_to_timespec (lt);
1908 if (! timespec_valid_p (t))
1909 time_overflow ();
1910 return t;
1913 /* Like lisp_time_argument, except decode only the seconds part,
1914 and do not check the subseconds part. */
1915 static time_t
1916 lisp_seconds_argument (Lisp_Object specified_time)
1918 Lisp_Object high, low, usec, psec;
1919 struct lisp_time t;
1921 int val = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1922 if (val != 0)
1924 val = decode_time_components (high, low, make_number (0),
1925 make_number (0), &t, 0);
1926 if (0 < val
1927 && ! ((TYPE_SIGNED (time_t)
1928 ? TIME_T_MIN >> LO_TIME_BITS <= t.hi
1929 : 0 <= t.hi)
1930 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1931 val = -1;
1933 check_time_validity (val);
1934 return (t.hi << LO_TIME_BITS) + t.lo;
1937 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1938 doc: /* Return the current time, as a float number of seconds since the epoch.
1939 If SPECIFIED-TIME is given, it is the time to convert to float
1940 instead of the current time. The argument should have the form
1941 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1942 you can use times from `current-time' and from `file-attributes'.
1943 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1944 considered obsolete.
1946 WARNING: Since the result is floating point, it may not be exact.
1947 If precise time stamps are required, use either `current-time',
1948 or (if you need time as a string) `format-time-string'. */)
1949 (Lisp_Object specified_time)
1951 double t;
1952 Lisp_Object high, low, usec, psec;
1953 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1954 && decode_time_components (high, low, usec, psec, 0, &t)))
1955 invalid_time ();
1956 return make_float (t);
1959 /* Write information into buffer S of size MAXSIZE, according to the
1960 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1961 Use the time zone specified by TZ.
1962 Use NS as the number of nanoseconds in the %N directive.
1963 Return the number of bytes written, not including the terminating
1964 '\0'. If S is NULL, nothing will be written anywhere; so to
1965 determine how many bytes would be written, use NULL for S and
1966 ((size_t) -1) for MAXSIZE.
1968 This function behaves like nstrftime, except it allows null
1969 bytes in FORMAT and it does not support nanoseconds. */
1970 static size_t
1971 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1972 size_t format_len, const struct tm *tp, timezone_t tz, int ns)
1974 size_t total = 0;
1976 /* Loop through all the null-terminated strings in the format
1977 argument. Normally there's just one null-terminated string, but
1978 there can be arbitrarily many, concatenated together, if the
1979 format contains '\0' bytes. nstrftime stops at the first
1980 '\0' byte so we must invoke it separately for each such string. */
1981 for (;;)
1983 size_t len;
1984 size_t result;
1986 if (s)
1987 s[0] = '\1';
1989 result = nstrftime (s, maxsize, format, tp, tz, ns);
1991 if (s)
1993 if (result == 0 && s[0] != '\0')
1994 return 0;
1995 s += result + 1;
1998 maxsize -= result + 1;
1999 total += result;
2000 len = strlen (format);
2001 if (len == format_len)
2002 return total;
2003 total++;
2004 format += len + 1;
2005 format_len -= len + 1;
2009 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
2010 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted or nil.
2011 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2012 `current-time' or `file-attributes'. It can also be a single integer
2013 number of seconds since the epoch. The obsolete form (HIGH . LOW) is
2014 also still accepted.
2016 The optional ZONE is omitted or nil for Emacs local time, t for
2017 Universal Time, `wall' for system wall clock time, or a string as in
2018 the TZ environment variable. It can also be a list (as from
2019 `current-time-zone') or an integer (as from `decode-time') applied
2020 without consideration for daylight saving time.
2022 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2023 by text that describes the specified date and time in TIME:
2025 %Y is the year, %y within the century, %C the century.
2026 %G is the year corresponding to the ISO week, %g within the century.
2027 %m is the numeric month.
2028 %b and %h are the locale's abbreviated month name, %B the full name.
2029 (%h is not supported on MS-Windows.)
2030 %d is the day of the month, zero-padded, %e is blank-padded.
2031 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2032 %a is the locale's abbreviated name of the day of week, %A the full name.
2033 %U is the week number starting on Sunday, %W starting on Monday,
2034 %V according to ISO 8601.
2035 %j is the day of the year.
2037 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2038 only blank-padded, %l is like %I blank-padded.
2039 %p is the locale's equivalent of either AM or PM.
2040 %q is the calendar quarter (1–4).
2041 %M is the minute (00-59).
2042 %S is the second (00-59; 00-60 on platforms with leap seconds)
2043 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2044 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2045 %Z is the time zone abbreviation, %z is the numeric form.
2047 %c is the locale's date and time format.
2048 %x is the locale's "preferred" date format.
2049 %D is like "%m/%d/%y".
2050 %F is the ISO 8601 date format (like "%Y-%m-%d").
2052 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2053 %X is the locale's "preferred" time format.
2055 Finally, %n is a newline, %t is a tab, %% is a literal %, and
2056 unrecognized %-sequences stand for themselves.
2058 Certain flags and modifiers are available with some format controls.
2059 The flags are `_', `-', `^' and `#'. For certain characters X,
2060 %_X is like %X, but padded with blanks; %-X is like %X,
2061 but without padding. %^X is like %X, but with all textual
2062 characters up-cased; %#X is like %X, but with letter-case of
2063 all textual characters reversed.
2064 %NX (where N stands for an integer) is like %X,
2065 but takes up at least N (a number) positions.
2066 The modifiers are `E' and `O'. For certain characters X,
2067 %EX is a locale's alternative version of %X;
2068 %OX is like %X, but uses the locale's number symbols.
2070 For example, to produce full ISO 8601 format, use "%FT%T%z".
2072 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2073 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object zone)
2075 struct timespec t = lisp_time_argument (timeval);
2076 struct tm tm;
2078 CHECK_STRING (format_string);
2079 format_string = code_convert_string_norecord (format_string,
2080 Vlocale_coding_system, 1);
2081 return format_time_string (SSDATA (format_string), SBYTES (format_string),
2082 t, zone, &tm);
2085 static Lisp_Object
2086 format_time_string (char const *format, ptrdiff_t formatlen,
2087 struct timespec t, Lisp_Object zone, struct tm *tmp)
2089 char buffer[4000];
2090 char *buf = buffer;
2091 ptrdiff_t size = sizeof buffer;
2092 size_t len;
2093 int ns = t.tv_nsec;
2094 USE_SAFE_ALLOCA;
2096 timezone_t tz = tzlookup (zone, false);
2097 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2098 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2099 expects a pointer to time_t value. */
2100 time_t tsec = t.tv_sec;
2101 tmp = emacs_localtime_rz (tz, &tsec, tmp);
2102 if (! tmp)
2104 xtzfree (tz);
2105 time_overflow ();
2107 synchronize_system_time_locale ();
2109 while (true)
2111 buf[0] = '\1';
2112 len = emacs_nmemftime (buf, size, format, formatlen, tmp, tz, ns);
2113 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
2114 break;
2116 /* Buffer was too small, so make it bigger and try again. */
2117 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, tz, ns);
2118 if (STRING_BYTES_BOUND <= len)
2120 xtzfree (tz);
2121 string_overflow ();
2123 size = len + 1;
2124 buf = SAFE_ALLOCA (size);
2127 xtzfree (tz);
2128 AUTO_STRING_WITH_LEN (bufstring, buf, len);
2129 Lisp_Object result = code_convert_string_norecord (bufstring,
2130 Vlocale_coding_system, 0);
2131 SAFE_FREE ();
2132 return result;
2135 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 2, 0,
2136 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2137 The optional TIME should be a list of (HIGH LOW . IGNORED),
2138 as from `current-time' and `file-attributes', or nil to use the
2139 current time. It can also be a single integer number of seconds since
2140 the epoch. The obsolete form (HIGH . LOW) is also still accepted.
2142 The optional ZONE is omitted or nil for Emacs local time, t for
2143 Universal Time, `wall' for system wall clock time, or a string as in
2144 the TZ environment variable. It can also be a list (as from
2145 `current-time-zone') or an integer (the UTC offset in seconds) applied
2146 without consideration for daylight saving time.
2148 The list has the following nine members: SEC is an integer between 0
2149 and 60; SEC is 60 for a leap second, which only some operating systems
2150 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2151 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2152 integer between 1 and 12. YEAR is an integer indicating the
2153 four-digit year. DOW is the day of week, an integer between 0 and 6,
2154 where 0 is Sunday. DST is t if daylight saving time is in effect,
2155 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2156 seconds, i.e., the number of seconds east of Greenwich. (Note that
2157 Common Lisp has different meanings for DOW and UTCOFF.)
2159 usage: (decode-time &optional TIME ZONE) */)
2160 (Lisp_Object specified_time, Lisp_Object zone)
2162 time_t time_spec = lisp_seconds_argument (specified_time);
2163 struct tm local_tm, gmt_tm;
2164 timezone_t tz = tzlookup (zone, false);
2165 struct tm *tm = emacs_localtime_rz (tz, &time_spec, &local_tm);
2166 xtzfree (tz);
2168 if (! (tm
2169 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2170 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2171 time_overflow ();
2173 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2174 EMACS_INT tm_year_base = TM_YEAR_BASE;
2176 return CALLN (Flist,
2177 make_number (local_tm.tm_sec),
2178 make_number (local_tm.tm_min),
2179 make_number (local_tm.tm_hour),
2180 make_number (local_tm.tm_mday),
2181 make_number (local_tm.tm_mon + 1),
2182 make_number (local_tm.tm_year + tm_year_base),
2183 make_number (local_tm.tm_wday),
2184 local_tm.tm_isdst ? Qt : Qnil,
2185 (HAVE_TM_GMTOFF
2186 ? make_number (tm_gmtoff (&local_tm))
2187 : gmtime_r (&time_spec, &gmt_tm)
2188 ? make_number (tm_diff (&local_tm, &gmt_tm))
2189 : Qnil));
2192 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2193 the result is representable as an int. */
2194 static int
2195 check_tm_member (Lisp_Object obj, int offset)
2197 CHECK_NUMBER (obj);
2198 EMACS_INT n = XINT (obj);
2199 int result;
2200 if (INT_SUBTRACT_WRAPV (n, offset, &result))
2201 time_overflow ();
2202 return result;
2205 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2206 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2207 This is the reverse operation of `decode-time', which see.
2209 The optional ZONE is omitted or nil for Emacs local time, t for
2210 Universal Time, `wall' for system wall clock time, or a string as in
2211 the TZ environment variable. It can also be a list (as from
2212 `current-time-zone') or an integer (as from `decode-time') applied
2213 without consideration for daylight saving time.
2215 You can pass more than 7 arguments; then the first six arguments
2216 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2217 The intervening arguments are ignored.
2218 This feature lets (apply \\='encode-time (decode-time ...)) work.
2220 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2221 for example, a DAY of 0 means the day preceding the given month.
2222 Year numbers less than 100 are treated just like other year numbers.
2223 If you want them to stand for years in this century, you must do that yourself.
2225 Years before 1970 are not guaranteed to work. On some systems,
2226 year values as low as 1901 do work.
2228 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2229 (ptrdiff_t nargs, Lisp_Object *args)
2231 time_t value;
2232 struct tm tm;
2233 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2235 tm.tm_sec = check_tm_member (args[0], 0);
2236 tm.tm_min = check_tm_member (args[1], 0);
2237 tm.tm_hour = check_tm_member (args[2], 0);
2238 tm.tm_mday = check_tm_member (args[3], 0);
2239 tm.tm_mon = check_tm_member (args[4], 1);
2240 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2241 tm.tm_isdst = -1;
2243 timezone_t tz = tzlookup (zone, false);
2244 value = emacs_mktime_z (tz, &tm);
2245 xtzfree (tz);
2247 if (value == (time_t) -1)
2248 time_overflow ();
2250 return list2i (hi_time (value), lo_time (value));
2253 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string,
2254 0, 2, 0,
2255 doc: /* Return the current local time, as a human-readable string.
2256 Programs can use this function to decode a time,
2257 since the number of columns in each field is fixed
2258 if the year is in the range 1000-9999.
2259 The format is `Sun Sep 16 01:03:52 1973'.
2260 However, see also the functions `decode-time' and `format-time-string'
2261 which provide a much more powerful and general facility.
2263 If SPECIFIED-TIME is given, it is a time to format instead of the
2264 current time. The argument should have the form (HIGH LOW . IGNORED).
2265 Thus, you can use times obtained from `current-time' and from
2266 `file-attributes'. SPECIFIED-TIME can also be a single integer number
2267 of seconds since the epoch. The obsolete form (HIGH . LOW) is also
2268 still accepted.
2270 The optional ZONE is omitted or nil for Emacs local time, t for
2271 Universal Time, `wall' for system wall clock time, or a string as in
2272 the TZ environment variable. It can also be a list (as from
2273 `current-time-zone') or an integer (as from `decode-time') applied
2274 without consideration for daylight saving time. */)
2275 (Lisp_Object specified_time, Lisp_Object zone)
2277 time_t value = lisp_seconds_argument (specified_time);
2278 timezone_t tz = tzlookup (zone, false);
2280 /* Convert to a string in ctime format, except without the trailing
2281 newline, and without the 4-digit year limit. Don't use asctime
2282 or ctime, as they might dump core if the year is outside the
2283 range -999 .. 9999. */
2284 struct tm tm;
2285 struct tm *tmp = emacs_localtime_rz (tz, &value, &tm);
2286 xtzfree (tz);
2287 if (! tmp)
2288 time_overflow ();
2290 static char const wday_name[][4] =
2291 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2292 static char const mon_name[][4] =
2293 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2294 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2295 printmax_t year_base = TM_YEAR_BASE;
2296 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2297 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2298 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2299 tm.tm_hour, tm.tm_min, tm.tm_sec,
2300 tm.tm_year + year_base);
2302 return make_unibyte_string (buf, len);
2305 /* Yield A - B, measured in seconds.
2306 This function is copied from the GNU C Library. */
2307 static int
2308 tm_diff (struct tm *a, struct tm *b)
2310 /* Compute intervening leap days correctly even if year is negative.
2311 Take care to avoid int overflow in leap day calculations,
2312 but it's OK to assume that A and B are close to each other. */
2313 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2314 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2315 int a100 = a4 / 25 - (a4 % 25 < 0);
2316 int b100 = b4 / 25 - (b4 % 25 < 0);
2317 int a400 = a100 >> 2;
2318 int b400 = b100 >> 2;
2319 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2320 int years = a->tm_year - b->tm_year;
2321 int days = (365 * years + intervening_leap_days
2322 + (a->tm_yday - b->tm_yday));
2323 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2324 + (a->tm_min - b->tm_min))
2325 + (a->tm_sec - b->tm_sec));
2328 /* Yield A's UTC offset, or an unspecified value if unknown. */
2329 static long int
2330 tm_gmtoff (struct tm *a)
2332 #if HAVE_TM_GMTOFF
2333 return a->tm_gmtoff;
2334 #else
2335 return 0;
2336 #endif
2339 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 2, 0,
2340 doc: /* Return the offset and name for the local time zone.
2341 This returns a list of the form (OFFSET NAME).
2342 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2343 A negative value means west of Greenwich.
2344 NAME is a string giving the name of the time zone.
2345 If SPECIFIED-TIME is given, the time zone offset is determined from it
2346 instead of using the current time. The argument should have the form
2347 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2348 `current-time' and from `file-attributes'. SPECIFIED-TIME can also be
2349 a single integer number of seconds since the epoch. The obsolete form
2350 (HIGH . LOW) is also still accepted.
2352 The optional ZONE is omitted or nil for Emacs local time, t for
2353 Universal Time, `wall' for system wall clock time, or a string as in
2354 the TZ environment variable. It can also be a list (as from
2355 `current-time-zone') or an integer (as from `decode-time') applied
2356 without consideration for daylight saving time.
2358 Some operating systems cannot provide all this information to Emacs;
2359 in this case, `current-time-zone' returns a list containing nil for
2360 the data it can't find. */)
2361 (Lisp_Object specified_time, Lisp_Object zone)
2363 struct timespec value;
2364 struct tm local_tm, gmt_tm;
2365 Lisp_Object zone_offset, zone_name;
2367 zone_offset = Qnil;
2368 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2369 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value,
2370 zone, &local_tm);
2372 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2373 timespec on some systems (MinGW) is a 64-bit field. */
2374 time_t tsec = value.tv_sec;
2375 if (HAVE_TM_GMTOFF || gmtime_r (&tsec, &gmt_tm))
2377 long int offset = (HAVE_TM_GMTOFF
2378 ? tm_gmtoff (&local_tm)
2379 : tm_diff (&local_tm, &gmt_tm));
2380 zone_offset = make_number (offset);
2381 if (SCHARS (zone_name) == 0)
2383 /* No local time zone name is available; use numeric zone instead. */
2384 long int hour = offset / 3600;
2385 int min_sec = offset % 3600;
2386 int amin_sec = min_sec < 0 ? - min_sec : min_sec;
2387 int min = amin_sec / 60;
2388 int sec = amin_sec % 60;
2389 int min_prec = min_sec ? 2 : 0;
2390 int sec_prec = sec ? 2 : 0;
2391 char buf[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2392 zone_name = make_formatted_string (buf, "%c%.2ld%.*d%.*d",
2393 (offset < 0 ? '-' : '+'),
2394 hour, min_prec, min, sec_prec, sec);
2398 return list2 (zone_offset, zone_name);
2401 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2402 doc: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2403 If TZ is nil or `wall', use system wall clock time; this differs from
2404 the usual Emacs convention where nil means current local time. If TZ
2405 is t, use Universal Time. If TZ is a list (as from
2406 `current-time-zone') or an integer (as from `decode-time'), use the
2407 specified time zone without consideration for daylight saving time.
2409 Instead of calling this function, you typically want something else.
2410 To temporarily use a different time zone rule for just one invocation
2411 of `decode-time', `encode-time', or `format-time-string', pass the
2412 function a ZONE argument. To change local time consistently
2413 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2414 environment of the Emacs process and the variable
2415 `process-environment', whereas `set-time-zone-rule' affects only the
2416 former. */)
2417 (Lisp_Object tz)
2419 tzlookup (NILP (tz) ? Qwall : tz, true);
2420 return Qnil;
2423 /* A buffer holding a string of the form "TZ=value", intended
2424 to be part of the environment. If TZ is supposed to be unset,
2425 the buffer string is "tZ=". */
2426 static char *tzvalbuf;
2428 /* Get the local time zone rule. */
2429 char *
2430 emacs_getenv_TZ (void)
2432 return tzvalbuf[0] == 'T' ? tzvalbuf + tzeqlen : 0;
2435 /* Set the local time zone rule to TZSTRING, which can be null to
2436 denote wall clock time. Do not record the setting in LOCAL_TZ.
2438 This function is not thread-safe, in theory because putenv is not,
2439 but mostly because of the static storage it updates. Other threads
2440 that invoke localtime etc. may be adversely affected while this
2441 function is executing. */
2444 emacs_setenv_TZ (const char *tzstring)
2446 static ptrdiff_t tzvalbufsize;
2447 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2448 char *tzval = tzvalbuf;
2449 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2451 if (new_tzvalbuf)
2453 /* Do not attempt to free the old tzvalbuf, since another thread
2454 may be using it. In practice, the first allocation is large
2455 enough and memory does not leak. */
2456 tzval = xpalloc (NULL, &tzvalbufsize,
2457 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2458 tzvalbuf = tzval;
2459 tzval[1] = 'Z';
2460 tzval[2] = '=';
2463 if (tzstring)
2465 /* Modify TZVAL in place. Although this is dicey in a
2466 multithreaded environment, we know of no portable alternative.
2467 Calling putenv or setenv could crash some other thread. */
2468 tzval[0] = 'T';
2469 strcpy (tzval + tzeqlen, tzstring);
2471 else
2473 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2474 Although this is also dicey, calling unsetenv here can crash Emacs.
2475 See Bug#8705. */
2476 tzval[0] = 't';
2477 tzval[tzeqlen] = 0;
2481 #ifndef WINDOWSNT
2482 /* Modifying *TZVAL merely requires calling tzset (which is the
2483 caller's responsibility). However, modifying TZVAL requires
2484 calling putenv; although this is not thread-safe, in practice this
2485 runs only on startup when there is only one thread. */
2486 bool need_putenv = new_tzvalbuf;
2487 #else
2488 /* MS-Windows 'putenv' copies the argument string into a block it
2489 allocates, so modifying *TZVAL will not change the environment.
2490 However, the other threads run by Emacs on MS-Windows never call
2491 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2492 dicey in-place modification technique doesn't exist there in the
2493 first place. */
2494 bool need_putenv = true;
2495 #endif
2496 if (need_putenv)
2497 xputenv (tzval);
2499 return 0;
2502 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2503 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2504 type of object is Lisp_String). INHERIT is passed to
2505 INSERT_FROM_STRING_FUNC as the last argument. */
2507 static void
2508 general_insert_function (void (*insert_func)
2509 (const char *, ptrdiff_t),
2510 void (*insert_from_string_func)
2511 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2512 ptrdiff_t, ptrdiff_t, bool),
2513 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2515 ptrdiff_t argnum;
2516 Lisp_Object val;
2518 for (argnum = 0; argnum < nargs; argnum++)
2520 val = args[argnum];
2521 if (CHARACTERP (val))
2523 int c = XFASTINT (val);
2524 unsigned char str[MAX_MULTIBYTE_LENGTH];
2525 int len;
2527 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2528 len = CHAR_STRING (c, str);
2529 else
2531 str[0] = CHAR_TO_BYTE8 (c);
2532 len = 1;
2534 (*insert_func) ((char *) str, len);
2536 else if (STRINGP (val))
2538 (*insert_from_string_func) (val, 0, 0,
2539 SCHARS (val),
2540 SBYTES (val),
2541 inherit);
2543 else
2544 wrong_type_argument (Qchar_or_string_p, val);
2548 void
2549 insert1 (Lisp_Object arg)
2551 Finsert (1, &arg);
2555 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2556 doc: /* Insert the arguments, either strings or characters, at point.
2557 Point and after-insertion markers move forward to end up
2558 after the inserted text.
2559 Any other markers at the point of insertion remain before the text.
2561 If the current buffer is multibyte, unibyte strings are converted
2562 to multibyte for insertion (see `string-make-multibyte').
2563 If the current buffer is unibyte, multibyte strings are converted
2564 to unibyte for insertion (see `string-make-unibyte').
2566 When operating on binary data, it may be necessary to preserve the
2567 original bytes of a unibyte string when inserting it into a multibyte
2568 buffer; to accomplish this, apply `string-as-multibyte' to the string
2569 and insert the result.
2571 usage: (insert &rest ARGS) */)
2572 (ptrdiff_t nargs, Lisp_Object *args)
2574 general_insert_function (insert, insert_from_string, 0, nargs, args);
2575 return Qnil;
2578 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2579 0, MANY, 0,
2580 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2581 Point and after-insertion markers move forward to end up
2582 after the inserted text.
2583 Any other markers at the point of insertion remain before the text.
2585 If the current buffer is multibyte, unibyte strings are converted
2586 to multibyte for insertion (see `unibyte-char-to-multibyte').
2587 If the current buffer is unibyte, multibyte strings are converted
2588 to unibyte for insertion.
2590 usage: (insert-and-inherit &rest ARGS) */)
2591 (ptrdiff_t nargs, Lisp_Object *args)
2593 general_insert_function (insert_and_inherit, insert_from_string, 1,
2594 nargs, args);
2595 return Qnil;
2598 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2599 doc: /* Insert strings or characters at point, relocating markers after the text.
2600 Point and markers move forward to end up after the inserted text.
2602 If the current buffer is multibyte, unibyte strings are converted
2603 to multibyte for insertion (see `unibyte-char-to-multibyte').
2604 If the current buffer is unibyte, multibyte strings are converted
2605 to unibyte for insertion.
2607 If an overlay begins at the insertion point, the inserted text falls
2608 outside the overlay; if a nonempty overlay ends at the insertion
2609 point, the inserted text falls inside that overlay.
2611 usage: (insert-before-markers &rest ARGS) */)
2612 (ptrdiff_t nargs, Lisp_Object *args)
2614 general_insert_function (insert_before_markers,
2615 insert_from_string_before_markers, 0,
2616 nargs, args);
2617 return Qnil;
2620 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2621 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2622 doc: /* Insert text at point, relocating markers and inheriting properties.
2623 Point and markers move forward to end up after the inserted text.
2625 If the current buffer is multibyte, unibyte strings are converted
2626 to multibyte for insertion (see `unibyte-char-to-multibyte').
2627 If the current buffer is unibyte, multibyte strings are converted
2628 to unibyte for insertion.
2630 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2631 (ptrdiff_t nargs, Lisp_Object *args)
2633 general_insert_function (insert_before_markers_and_inherit,
2634 insert_from_string_before_markers, 1,
2635 nargs, args);
2636 return Qnil;
2639 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2640 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2641 (prefix-numeric-value current-prefix-arg)\
2642 t))",
2643 doc: /* Insert COUNT copies of CHARACTER.
2644 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2645 of these ways:
2647 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2648 Completion is available; if you type a substring of the name
2649 preceded by an asterisk `*', Emacs shows all names which include
2650 that substring, not necessarily at the beginning of the name.
2652 - As a hexadecimal code point, e.g. 263A. Note that code points in
2653 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2654 the Unicode code space).
2656 - As a code point with a radix specified with #, e.g. #o21430
2657 (octal), #x2318 (hex), or #10r8984 (decimal).
2659 If called interactively, COUNT is given by the prefix argument. If
2660 omitted or nil, it defaults to 1.
2662 Inserting the character(s) relocates point and before-insertion
2663 markers in the same ways as the function `insert'.
2665 The optional third argument INHERIT, if non-nil, says to inherit text
2666 properties from adjoining text, if those properties are sticky. If
2667 called interactively, INHERIT is t. */)
2668 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2670 int i, stringlen;
2671 register ptrdiff_t n;
2672 int c, len;
2673 unsigned char str[MAX_MULTIBYTE_LENGTH];
2674 char string[4000];
2676 CHECK_CHARACTER (character);
2677 if (NILP (count))
2678 XSETFASTINT (count, 1);
2679 CHECK_NUMBER (count);
2680 c = XFASTINT (character);
2682 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2683 len = CHAR_STRING (c, str);
2684 else
2685 str[0] = c, len = 1;
2686 if (XINT (count) <= 0)
2687 return Qnil;
2688 if (BUF_BYTES_MAX / len < XINT (count))
2689 buffer_overflow ();
2690 n = XINT (count) * len;
2691 stringlen = min (n, sizeof string - sizeof string % len);
2692 for (i = 0; i < stringlen; i++)
2693 string[i] = str[i % len];
2694 while (n > stringlen)
2696 maybe_quit ();
2697 if (!NILP (inherit))
2698 insert_and_inherit (string, stringlen);
2699 else
2700 insert (string, stringlen);
2701 n -= stringlen;
2703 if (!NILP (inherit))
2704 insert_and_inherit (string, n);
2705 else
2706 insert (string, n);
2707 return Qnil;
2710 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2711 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2712 Both arguments are required.
2713 BYTE is a number of the range 0..255.
2715 If BYTE is 128..255 and the current buffer is multibyte, the
2716 corresponding eight-bit character is inserted.
2718 Point, and before-insertion markers, are relocated as in the function `insert'.
2719 The optional third arg INHERIT, if non-nil, says to inherit text properties
2720 from adjoining text, if those properties are sticky. */)
2721 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2723 CHECK_NUMBER (byte);
2724 if (XINT (byte) < 0 || XINT (byte) > 255)
2725 args_out_of_range_3 (byte, make_number (0), make_number (255));
2726 if (XINT (byte) >= 128
2727 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2728 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2729 return Finsert_char (byte, count, inherit);
2733 /* Making strings from buffer contents. */
2735 /* Return a Lisp_String containing the text of the current buffer from
2736 START to END. If text properties are in use and the current buffer
2737 has properties in the range specified, the resulting string will also
2738 have them, if PROPS is true.
2740 We don't want to use plain old make_string here, because it calls
2741 make_uninit_string, which can cause the buffer arena to be
2742 compacted. make_string has no way of knowing that the data has
2743 been moved, and thus copies the wrong data into the string. This
2744 doesn't effect most of the other users of make_string, so it should
2745 be left as is. But we should use this function when conjuring
2746 buffer substrings. */
2748 Lisp_Object
2749 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2751 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2752 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2754 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2757 /* Return a Lisp_String containing the text of the current buffer from
2758 START / START_BYTE to END / END_BYTE.
2760 If text properties are in use and the current buffer
2761 has properties in the range specified, the resulting string will also
2762 have them, if PROPS is true.
2764 We don't want to use plain old make_string here, because it calls
2765 make_uninit_string, which can cause the buffer arena to be
2766 compacted. make_string has no way of knowing that the data has
2767 been moved, and thus copies the wrong data into the string. This
2768 doesn't effect most of the other users of make_string, so it should
2769 be left as is. But we should use this function when conjuring
2770 buffer substrings. */
2772 Lisp_Object
2773 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2774 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2776 Lisp_Object result, tem, tem1;
2777 ptrdiff_t beg0, end0, beg1, end1, size;
2779 if (start_byte < GPT_BYTE && GPT_BYTE < end_byte)
2781 /* Two regions, before and after the gap. */
2782 beg0 = start_byte;
2783 end0 = GPT_BYTE;
2784 beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
2785 end1 = end_byte + GAP_SIZE - BEG_BYTE;
2787 else
2789 /* The only region. */
2790 beg0 = start_byte;
2791 end0 = end_byte;
2792 beg1 = -1;
2793 end1 = -1;
2796 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2797 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2798 else
2799 result = make_uninit_string (end - start);
2801 size = end0 - beg0;
2802 memcpy (SDATA (result), BYTE_POS_ADDR (beg0), size);
2803 if (beg1 != -1)
2804 memcpy (SDATA (result) + size, BEG_ADDR + beg1, end1 - beg1);
2806 /* If desired, update and copy the text properties. */
2807 if (props)
2809 update_buffer_properties (start, end);
2811 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2812 tem1 = Ftext_properties_at (make_number (start), Qnil);
2814 if (XINT (tem) != end || !NILP (tem1))
2815 copy_intervals_to_string (result, current_buffer, start,
2816 end - start);
2819 return result;
2822 /* Call Vbuffer_access_fontify_functions for the range START ... END
2823 in the current buffer, if necessary. */
2825 static void
2826 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2828 /* If this buffer has some access functions,
2829 call them, specifying the range of the buffer being accessed. */
2830 if (!NILP (Vbuffer_access_fontify_functions))
2832 /* But don't call them if we can tell that the work
2833 has already been done. */
2834 if (!NILP (Vbuffer_access_fontified_property))
2836 Lisp_Object tem
2837 = Ftext_property_any (make_number (start), make_number (end),
2838 Vbuffer_access_fontified_property,
2839 Qnil, Qnil);
2840 if (NILP (tem))
2841 return;
2844 CALLN (Frun_hook_with_args, Qbuffer_access_fontify_functions,
2845 make_number (start), make_number (end));
2849 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2850 doc: /* Return the contents of part of the current buffer as a string.
2851 The two arguments START and END are character positions;
2852 they can be in either order.
2853 The string returned is multibyte if the buffer is multibyte.
2855 This function copies the text properties of that part of the buffer
2856 into the result string; if you don't want the text properties,
2857 use `buffer-substring-no-properties' instead. */)
2858 (Lisp_Object start, Lisp_Object end)
2860 register ptrdiff_t b, e;
2862 validate_region (&start, &end);
2863 b = XINT (start);
2864 e = XINT (end);
2866 return make_buffer_string (b, e, 1);
2869 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2870 Sbuffer_substring_no_properties, 2, 2, 0,
2871 doc: /* Return the characters of part of the buffer, without the text properties.
2872 The two arguments START and END are character positions;
2873 they can be in either order. */)
2874 (Lisp_Object start, Lisp_Object end)
2876 register ptrdiff_t b, e;
2878 validate_region (&start, &end);
2879 b = XINT (start);
2880 e = XINT (end);
2882 return make_buffer_string (b, e, 0);
2885 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2886 doc: /* Return the contents of the current buffer as a string.
2887 If narrowing is in effect, this function returns only the visible part
2888 of the buffer. */)
2889 (void)
2891 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2894 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2895 1, 3, 0,
2896 doc: /* Insert before point a substring of the contents of BUFFER.
2897 BUFFER may be a buffer or a buffer name.
2898 Arguments START and END are character positions specifying the substring.
2899 They default to the values of (point-min) and (point-max) in BUFFER.
2901 Point and before-insertion markers move forward to end up after the
2902 inserted text.
2903 Any other markers at the point of insertion remain before the text.
2905 If the current buffer is multibyte and BUFFER is unibyte, or vice
2906 versa, strings are converted from unibyte to multibyte or vice versa
2907 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2908 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2910 register EMACS_INT b, e, temp;
2911 register struct buffer *bp, *obuf;
2912 Lisp_Object buf;
2914 buf = Fget_buffer (buffer);
2915 if (NILP (buf))
2916 nsberror (buffer);
2917 bp = XBUFFER (buf);
2918 if (!BUFFER_LIVE_P (bp))
2919 error ("Selecting deleted buffer");
2921 if (NILP (start))
2922 b = BUF_BEGV (bp);
2923 else
2925 CHECK_NUMBER_COERCE_MARKER (start);
2926 b = XINT (start);
2928 if (NILP (end))
2929 e = BUF_ZV (bp);
2930 else
2932 CHECK_NUMBER_COERCE_MARKER (end);
2933 e = XINT (end);
2936 if (b > e)
2937 temp = b, b = e, e = temp;
2939 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2940 args_out_of_range (start, end);
2942 obuf = current_buffer;
2943 set_buffer_internal_1 (bp);
2944 update_buffer_properties (b, e);
2945 set_buffer_internal_1 (obuf);
2947 insert_from_buffer (bp, b, e - b, 0);
2948 return Qnil;
2951 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2952 6, 6, 0,
2953 doc: /* Compare two substrings of two buffers; return result as number.
2954 Return -N if first string is less after N-1 chars, +N if first string is
2955 greater after N-1 chars, or 0 if strings match.
2956 The first substring is in BUFFER1 from START1 to END1 and the second
2957 is in BUFFER2 from START2 to END2.
2958 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2959 buffer is used. If START1 or START2 is nil, the value of `point-min'
2960 in the respective buffers is used. If END1 or END2 is nil, the value
2961 of `point-max' in the respective buffers is used.
2962 The value of `case-fold-search' in the current buffer
2963 determines whether case is significant or ignored. */)
2964 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2966 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2967 register struct buffer *bp1, *bp2;
2968 register Lisp_Object trt
2969 = (!NILP (BVAR (current_buffer, case_fold_search))
2970 ? BVAR (current_buffer, case_canon_table) : Qnil);
2971 ptrdiff_t chars = 0;
2972 ptrdiff_t i1, i2, i1_byte, i2_byte;
2974 /* Find the first buffer and its substring. */
2976 if (NILP (buffer1))
2977 bp1 = current_buffer;
2978 else
2980 Lisp_Object buf1;
2981 buf1 = Fget_buffer (buffer1);
2982 if (NILP (buf1))
2983 nsberror (buffer1);
2984 bp1 = XBUFFER (buf1);
2985 if (!BUFFER_LIVE_P (bp1))
2986 error ("Selecting deleted buffer");
2989 if (NILP (start1))
2990 begp1 = BUF_BEGV (bp1);
2991 else
2993 CHECK_NUMBER_COERCE_MARKER (start1);
2994 begp1 = XINT (start1);
2996 if (NILP (end1))
2997 endp1 = BUF_ZV (bp1);
2998 else
3000 CHECK_NUMBER_COERCE_MARKER (end1);
3001 endp1 = XINT (end1);
3004 if (begp1 > endp1)
3005 temp = begp1, begp1 = endp1, endp1 = temp;
3007 if (!(BUF_BEGV (bp1) <= begp1
3008 && begp1 <= endp1
3009 && endp1 <= BUF_ZV (bp1)))
3010 args_out_of_range (start1, end1);
3012 /* Likewise for second substring. */
3014 if (NILP (buffer2))
3015 bp2 = current_buffer;
3016 else
3018 Lisp_Object buf2;
3019 buf2 = Fget_buffer (buffer2);
3020 if (NILP (buf2))
3021 nsberror (buffer2);
3022 bp2 = XBUFFER (buf2);
3023 if (!BUFFER_LIVE_P (bp2))
3024 error ("Selecting deleted buffer");
3027 if (NILP (start2))
3028 begp2 = BUF_BEGV (bp2);
3029 else
3031 CHECK_NUMBER_COERCE_MARKER (start2);
3032 begp2 = XINT (start2);
3034 if (NILP (end2))
3035 endp2 = BUF_ZV (bp2);
3036 else
3038 CHECK_NUMBER_COERCE_MARKER (end2);
3039 endp2 = XINT (end2);
3042 if (begp2 > endp2)
3043 temp = begp2, begp2 = endp2, endp2 = temp;
3045 if (!(BUF_BEGV (bp2) <= begp2
3046 && begp2 <= endp2
3047 && endp2 <= BUF_ZV (bp2)))
3048 args_out_of_range (start2, end2);
3050 i1 = begp1;
3051 i2 = begp2;
3052 i1_byte = buf_charpos_to_bytepos (bp1, i1);
3053 i2_byte = buf_charpos_to_bytepos (bp2, i2);
3055 while (i1 < endp1 && i2 < endp2)
3057 /* When we find a mismatch, we must compare the
3058 characters, not just the bytes. */
3059 int c1, c2;
3061 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
3063 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
3064 BUF_INC_POS (bp1, i1_byte);
3065 i1++;
3067 else
3069 c1 = BUF_FETCH_BYTE (bp1, i1);
3070 MAKE_CHAR_MULTIBYTE (c1);
3071 i1++;
3074 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
3076 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
3077 BUF_INC_POS (bp2, i2_byte);
3078 i2++;
3080 else
3082 c2 = BUF_FETCH_BYTE (bp2, i2);
3083 MAKE_CHAR_MULTIBYTE (c2);
3084 i2++;
3087 if (!NILP (trt))
3089 c1 = char_table_translate (trt, c1);
3090 c2 = char_table_translate (trt, c2);
3093 if (c1 != c2)
3094 return make_number (c1 < c2 ? -1 - chars : chars + 1);
3096 chars++;
3097 rarely_quit (chars);
3100 /* The strings match as far as they go.
3101 If one is shorter, that one is less. */
3102 if (chars < endp1 - begp1)
3103 return make_number (chars + 1);
3104 else if (chars < endp2 - begp2)
3105 return make_number (- chars - 1);
3107 /* Same length too => they are equal. */
3108 return make_number (0);
3112 /* Set up necessary definitions for diffseq.h; see comments in
3113 diffseq.h for explanation. */
3115 #undef ELEMENT
3116 #undef EQUAL
3118 /* Counter used to rarely_quit in replace-buffer-contents. */
3119 static unsigned short rbc_quitcounter;
3121 #define XVECREF_YVECREF_EQUAL(ctx, xoff, yoff) \
3122 buffer_chars_equal ((ctx), (xoff), (yoff))
3124 #define OFFSET ptrdiff_t
3126 #define EXTRA_CONTEXT_FIELDS \
3127 /* Buffers to compare. */ \
3128 struct buffer *buffer_a; \
3129 struct buffer *buffer_b; \
3130 /* BEGV of each buffer */ \
3131 ptrdiff_t beg_a; \
3132 ptrdiff_t beg_b; \
3133 /* Whether each buffer is unibyte/plain-ASCII or not. */ \
3134 bool a_unibyte; \
3135 bool b_unibyte; \
3136 /* Bit vectors recording for each character whether it was deleted
3137 or inserted. */ \
3138 unsigned char *deletions; \
3139 unsigned char *insertions;
3141 #define NOTE_DELETE(ctx, xoff) set_bit ((ctx)->deletions, (xoff))
3142 #define NOTE_INSERT(ctx, yoff) set_bit ((ctx)->insertions, (yoff))
3144 struct context;
3145 static void set_bit (unsigned char *, OFFSET);
3146 static bool bit_is_set (const unsigned char *, OFFSET);
3147 static bool buffer_chars_equal (struct context *, OFFSET, OFFSET);
3149 #include "minmax.h"
3150 #include "diffseq.h"
3152 DEFUN ("replace-buffer-contents", Freplace_buffer_contents,
3153 Sreplace_buffer_contents, 1, 1, "bSource buffer: ",
3154 doc: /* Replace accessible portion of current buffer with that of SOURCE.
3155 SOURCE can be a buffer or a string that names a buffer.
3156 Interactively, prompt for SOURCE.
3157 As far as possible the replacement is non-destructive, i.e. existing
3158 buffer contents, markers, properties, and overlays in the current
3159 buffer stay intact.
3160 Warning: this function can be slow if there's a large number of small
3161 differences between the two buffers. */)
3162 (Lisp_Object source)
3164 struct buffer *a = current_buffer;
3165 Lisp_Object source_buffer = Fget_buffer (source);
3166 if (NILP (source_buffer))
3167 nsberror (source);
3168 struct buffer *b = XBUFFER (source_buffer);
3169 if (! BUFFER_LIVE_P (b))
3170 error ("Selecting deleted buffer");
3171 if (a == b)
3172 error ("Cannot replace a buffer with itself");
3174 ptrdiff_t min_a = BEGV;
3175 ptrdiff_t min_b = BUF_BEGV (b);
3176 ptrdiff_t size_a = ZV - min_a;
3177 ptrdiff_t size_b = BUF_ZV (b) - min_b;
3178 eassume (size_a >= 0);
3179 eassume (size_b >= 0);
3180 bool a_empty = size_a == 0;
3181 bool b_empty = size_b == 0;
3183 /* Handle trivial cases where at least one accessible portion is
3184 empty. */
3186 if (a_empty && b_empty)
3187 return Qnil;
3189 if (a_empty)
3190 return Finsert_buffer_substring (source, Qnil, Qnil);
3192 if (b_empty)
3194 del_range_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, true);
3195 return Qnil;
3198 /* FIXME: It is not documented how to initialize the contents of the
3199 context structure. This code cargo-cults from the existing
3200 caller in src/analyze.c of GNU Diffutils, which appears to
3201 work. */
3203 ptrdiff_t diags = size_a + size_b + 3;
3204 ptrdiff_t *buffer;
3205 USE_SAFE_ALLOCA;
3206 SAFE_NALLOCA (buffer, 2, diags);
3207 /* Micro-optimization: Casting to size_t generates much better
3208 code. */
3209 ptrdiff_t del_bytes = (size_t) size_a / CHAR_BIT + 1;
3210 ptrdiff_t ins_bytes = (size_t) size_b / CHAR_BIT + 1;
3211 struct context ctx = {
3212 .buffer_a = a,
3213 .buffer_b = b,
3214 .beg_a = min_a,
3215 .beg_b = min_b,
3216 .a_unibyte = BUF_ZV (a) == BUF_ZV_BYTE (a),
3217 .b_unibyte = BUF_ZV (b) == BUF_ZV_BYTE (b),
3218 .deletions = SAFE_ALLOCA (del_bytes),
3219 .insertions = SAFE_ALLOCA (ins_bytes),
3220 .fdiag = buffer + size_b + 1,
3221 .bdiag = buffer + diags + size_b + 1,
3222 /* FIXME: Find a good number for .too_expensive. */
3223 .too_expensive = 1000000,
3225 memclear (ctx.deletions, del_bytes);
3226 memclear (ctx.insertions, ins_bytes);
3227 /* compareseq requires indices to be zero-based. We add BEGV back
3228 later. */
3229 bool early_abort = compareseq (0, size_a, 0, size_b, false, &ctx);
3230 /* Since we didn’t define EARLY_ABORT, we should never abort
3231 early. */
3232 eassert (! early_abort);
3234 rbc_quitcounter = 0;
3236 Fundo_boundary ();
3237 bool modification_hooks_inhibited = false;
3238 ptrdiff_t count = SPECPDL_INDEX ();
3239 record_unwind_protect (save_excursion_restore, save_excursion_save ());
3241 /* We are going to make a lot of small modifications, and having the
3242 modification hooks called for each of them will slow us down.
3243 Instead, we announce a single modification for the entire
3244 modified region. But don't do that if the caller inhibited
3245 modification hooks, because then they don't want that. */
3246 ptrdiff_t from, to;
3247 if (!inhibit_modification_hooks)
3249 ptrdiff_t k, l;
3251 /* Find the first character position to be changed. */
3252 for (k = 0; k < size_a && !bit_is_set (ctx.deletions, k); k++)
3254 from = BEGV + k;
3256 /* Find the last character position to be changed. */
3257 for (l = size_a; l > 0 && !bit_is_set (ctx.deletions, l - 1); l--)
3259 to = BEGV + l;
3260 prepare_to_modify_buffer (from, to, NULL);
3261 specbind (Qinhibit_modification_hooks, Qt);
3262 modification_hooks_inhibited = true;
3265 ptrdiff_t i = size_a;
3266 ptrdiff_t j = size_b;
3267 /* Walk backwards through the lists of changes. This was also
3268 cargo-culted from src/analyze.c in GNU Diffutils. Because we
3269 walk backwards, we don’t have to keep the positions in sync. */
3270 while (i >= 0 || j >= 0)
3272 /* Allow the user to quit if this gets too slow. */
3273 rarely_quit (++rbc_quitcounter);
3275 /* Check whether there is a change (insertion or deletion)
3276 before the current position. */
3277 if ((i > 0 && bit_is_set (ctx.deletions, i - 1)) ||
3278 (j > 0 && bit_is_set (ctx.insertions, j - 1)))
3280 ptrdiff_t end_a = min_a + i;
3281 ptrdiff_t end_b = min_b + j;
3282 /* Find the beginning of the current change run. */
3283 while (i > 0 && bit_is_set (ctx.deletions, i - 1))
3284 --i;
3285 while (j > 0 && bit_is_set (ctx.insertions, j - 1))
3286 --j;
3288 rarely_quit (rbc_quitcounter++);
3290 ptrdiff_t beg_a = min_a + i;
3291 ptrdiff_t beg_b = min_b + j;
3292 eassert (beg_a <= end_a);
3293 eassert (beg_b <= end_b);
3294 eassert (beg_a < end_a || beg_b < end_b);
3295 if (beg_a < end_a)
3296 del_range (beg_a, end_a);
3297 if (beg_b < end_b)
3299 SET_PT (beg_a);
3300 Finsert_buffer_substring (source, make_natnum (beg_b),
3301 make_natnum (end_b));
3304 --i;
3305 --j;
3307 unbind_to (count, Qnil);
3308 SAFE_FREE ();
3309 rbc_quitcounter = 0;
3311 if (modification_hooks_inhibited)
3313 ptrdiff_t updated_to = to + ZV - BEGV - size_a;
3314 signal_after_change (from, to - from, updated_to - from);
3315 update_compositions (from, updated_to, CHECK_INSIDE);
3318 return Qnil;
3321 static void
3322 set_bit (unsigned char *a, ptrdiff_t i)
3324 eassert (i >= 0);
3325 /* Micro-optimization: Casting to size_t generates much better
3326 code. */
3327 size_t j = i;
3328 a[j / CHAR_BIT] |= (1 << (j % CHAR_BIT));
3331 static bool
3332 bit_is_set (const unsigned char *a, ptrdiff_t i)
3334 eassert (i >= 0);
3335 /* Micro-optimization: Casting to size_t generates much better
3336 code. */
3337 size_t j = i;
3338 return a[j / CHAR_BIT] & (1 << (j % CHAR_BIT));
3341 /* Return true if the characters at position POS_A of buffer
3342 CTX->buffer_a and at position POS_B of buffer CTX->buffer_b are
3343 equal. POS_A and POS_B are zero-based. Text properties are
3344 ignored.
3346 Implementation note: this function is called inside the inner-most
3347 loops of compareseq, so it absolutely must be optimized for speed,
3348 every last bit of it. E.g., each additional use of BEGV or such
3349 likes will slow down replace-buffer-contents by dozens of percents,
3350 because builtin_lisp_symbol will be called one more time in the
3351 innermost loop. */
3353 static bool
3354 buffer_chars_equal (struct context *ctx,
3355 ptrdiff_t pos_a, ptrdiff_t pos_b)
3357 pos_a += ctx->beg_a;
3358 pos_b += ctx->beg_b;
3360 /* Allow the user to escape out of a slow compareseq call. */
3361 rarely_quit (++rbc_quitcounter);
3363 ptrdiff_t bpos_a =
3364 ctx->a_unibyte ? pos_a : buf_charpos_to_bytepos (ctx->buffer_a, pos_a);
3365 ptrdiff_t bpos_b =
3366 ctx->b_unibyte ? pos_b : buf_charpos_to_bytepos (ctx->buffer_b, pos_b);
3368 /* We make the below a series of specific test to avoid using
3369 BUF_FETCH_CHAR_AS_MULTIBYTE, which references Lisp symbols, and
3370 is therefore significantly slower (see the note in the commentary
3371 to this function). */
3372 if (ctx->a_unibyte && ctx->b_unibyte)
3373 return BUF_FETCH_BYTE (ctx->buffer_a, bpos_a)
3374 == BUF_FETCH_BYTE (ctx->buffer_b, bpos_b);
3375 if (ctx->a_unibyte && !ctx->b_unibyte)
3376 return UNIBYTE_TO_CHAR (BUF_FETCH_BYTE (ctx->buffer_a, bpos_a))
3377 == BUF_FETCH_MULTIBYTE_CHAR (ctx->buffer_b, bpos_b);
3378 if (!ctx->a_unibyte && ctx->b_unibyte)
3379 return BUF_FETCH_MULTIBYTE_CHAR (ctx->buffer_a, bpos_a)
3380 == UNIBYTE_TO_CHAR (BUF_FETCH_BYTE (ctx->buffer_b, bpos_b));
3381 return BUF_FETCH_MULTIBYTE_CHAR (ctx->buffer_a, bpos_a)
3382 == BUF_FETCH_MULTIBYTE_CHAR (ctx->buffer_b, bpos_b);
3386 static void
3387 subst_char_in_region_unwind (Lisp_Object arg)
3389 bset_undo_list (current_buffer, arg);
3392 static void
3393 subst_char_in_region_unwind_1 (Lisp_Object arg)
3395 bset_filename (current_buffer, arg);
3398 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
3399 Ssubst_char_in_region, 4, 5, 0,
3400 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3401 If optional arg NOUNDO is non-nil, don't record this change for undo
3402 and don't mark the buffer as really changed.
3403 Both characters must have the same length of multi-byte form. */)
3404 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
3406 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
3407 /* Keep track of the first change in the buffer:
3408 if 0 we haven't found it yet.
3409 if < 0 we've found it and we've run the before-change-function.
3410 if > 0 we've actually performed it and the value is its position. */
3411 ptrdiff_t changed = 0;
3412 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
3413 unsigned char *p;
3414 ptrdiff_t count = SPECPDL_INDEX ();
3415 #define COMBINING_NO 0
3416 #define COMBINING_BEFORE 1
3417 #define COMBINING_AFTER 2
3418 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3419 int maybe_byte_combining = COMBINING_NO;
3420 ptrdiff_t last_changed = 0;
3421 bool multibyte_p
3422 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3423 int fromc, toc;
3425 restart:
3427 validate_region (&start, &end);
3428 CHECK_CHARACTER (fromchar);
3429 CHECK_CHARACTER (tochar);
3430 fromc = XFASTINT (fromchar);
3431 toc = XFASTINT (tochar);
3433 if (multibyte_p)
3435 len = CHAR_STRING (fromc, fromstr);
3436 if (CHAR_STRING (toc, tostr) != len)
3437 error ("Characters in `subst-char-in-region' have different byte-lengths");
3438 if (!ASCII_CHAR_P (*tostr))
3440 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3441 complete multibyte character, it may be combined with the
3442 after bytes. If it is in the range 0xA0..0xFF, it may be
3443 combined with the before and after bytes. */
3444 if (!CHAR_HEAD_P (*tostr))
3445 maybe_byte_combining = COMBINING_BOTH;
3446 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3447 maybe_byte_combining = COMBINING_AFTER;
3450 else
3452 len = 1;
3453 fromstr[0] = fromc;
3454 tostr[0] = toc;
3457 pos = XINT (start);
3458 pos_byte = CHAR_TO_BYTE (pos);
3459 stop = CHAR_TO_BYTE (XINT (end));
3460 end_byte = stop;
3462 /* If we don't want undo, turn off putting stuff on the list.
3463 That's faster than getting rid of things,
3464 and it prevents even the entry for a first change.
3465 Also inhibit locking the file. */
3466 if (!changed && !NILP (noundo))
3468 record_unwind_protect (subst_char_in_region_unwind,
3469 BVAR (current_buffer, undo_list));
3470 bset_undo_list (current_buffer, Qt);
3471 /* Don't do file-locking. */
3472 record_unwind_protect (subst_char_in_region_unwind_1,
3473 BVAR (current_buffer, filename));
3474 bset_filename (current_buffer, Qnil);
3477 if (pos_byte < GPT_BYTE)
3478 stop = min (stop, GPT_BYTE);
3479 while (1)
3481 ptrdiff_t pos_byte_next = pos_byte;
3483 if (pos_byte >= stop)
3485 if (pos_byte >= end_byte) break;
3486 stop = end_byte;
3488 p = BYTE_POS_ADDR (pos_byte);
3489 if (multibyte_p)
3490 INC_POS (pos_byte_next);
3491 else
3492 ++pos_byte_next;
3493 if (pos_byte_next - pos_byte == len
3494 && p[0] == fromstr[0]
3495 && (len == 1
3496 || (p[1] == fromstr[1]
3497 && (len == 2 || (p[2] == fromstr[2]
3498 && (len == 3 || p[3] == fromstr[3]))))))
3500 if (changed < 0)
3501 /* We've already seen this and run the before-change-function;
3502 this time we only need to record the actual position. */
3503 changed = pos;
3504 else if (!changed)
3506 changed = -1;
3507 modify_text (pos, XINT (end));
3509 if (! NILP (noundo))
3511 if (MODIFF - 1 == SAVE_MODIFF)
3512 SAVE_MODIFF++;
3513 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3514 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3517 /* The before-change-function may have moved the gap
3518 or even modified the buffer so we should start over. */
3519 goto restart;
3522 /* Take care of the case where the new character
3523 combines with neighboring bytes. */
3524 if (maybe_byte_combining
3525 && (maybe_byte_combining == COMBINING_AFTER
3526 ? (pos_byte_next < Z_BYTE
3527 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3528 : ((pos_byte_next < Z_BYTE
3529 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3530 || (pos_byte > BEG_BYTE
3531 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3533 Lisp_Object tem, string;
3535 tem = BVAR (current_buffer, undo_list);
3537 /* Make a multibyte string containing this single character. */
3538 string = make_multibyte_string ((char *) tostr, 1, len);
3539 /* replace_range is less efficient, because it moves the gap,
3540 but it handles combining correctly. */
3541 replace_range (pos, pos + 1, string,
3542 0, 0, 1, 0);
3543 pos_byte_next = CHAR_TO_BYTE (pos);
3544 if (pos_byte_next > pos_byte)
3545 /* Before combining happened. We should not increment
3546 POS. So, to cancel the later increment of POS,
3547 decrease it now. */
3548 pos--;
3549 else
3550 INC_POS (pos_byte_next);
3552 if (! NILP (noundo))
3553 bset_undo_list (current_buffer, tem);
3555 else
3557 if (NILP (noundo))
3558 record_change (pos, 1);
3559 for (i = 0; i < len; i++) *p++ = tostr[i];
3561 last_changed = pos + 1;
3563 pos_byte = pos_byte_next;
3564 pos++;
3567 if (changed > 0)
3569 signal_after_change (changed,
3570 last_changed - changed, last_changed - changed);
3571 update_compositions (changed, last_changed, CHECK_ALL);
3574 unbind_to (count, Qnil);
3575 return Qnil;
3579 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3580 Lisp_Object);
3582 /* Helper function for Ftranslate_region_internal.
3584 Check if a character sequence at POS (POS_BYTE) matches an element
3585 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3586 element is found, return it. Otherwise return Qnil. */
3588 static Lisp_Object
3589 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3590 Lisp_Object val)
3592 int initial_buf[16];
3593 int *buf = initial_buf;
3594 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3595 int *bufalloc = 0;
3596 ptrdiff_t buf_used = 0;
3597 Lisp_Object result = Qnil;
3599 for (; CONSP (val); val = XCDR (val))
3601 Lisp_Object elt;
3602 ptrdiff_t len, i;
3604 elt = XCAR (val);
3605 if (! CONSP (elt))
3606 continue;
3607 elt = XCAR (elt);
3608 if (! VECTORP (elt))
3609 continue;
3610 len = ASIZE (elt);
3611 if (len <= end - pos)
3613 for (i = 0; i < len; i++)
3615 if (buf_used <= i)
3617 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3618 int len1;
3620 if (buf_used == buf_size)
3622 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3623 sizeof *bufalloc);
3624 if (buf == initial_buf)
3625 memcpy (bufalloc, buf, sizeof initial_buf);
3626 buf = bufalloc;
3628 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3629 pos_byte += len1;
3631 if (XINT (AREF (elt, i)) != buf[i])
3632 break;
3634 if (i == len)
3636 result = XCAR (val);
3637 break;
3642 xfree (bufalloc);
3643 return result;
3647 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3648 Stranslate_region_internal, 3, 3, 0,
3649 doc: /* Internal use only.
3650 From START to END, translate characters according to TABLE.
3651 TABLE is a string or a char-table; the Nth character in it is the
3652 mapping for the character with code N.
3653 It returns the number of characters changed. */)
3654 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3656 register unsigned char *tt; /* Trans table. */
3657 register int nc; /* New character. */
3658 int cnt; /* Number of changes made. */
3659 ptrdiff_t size; /* Size of translate table. */
3660 ptrdiff_t pos, pos_byte, end_pos;
3661 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3662 bool string_multibyte UNINIT;
3664 validate_region (&start, &end);
3665 if (CHAR_TABLE_P (table))
3667 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3668 error ("Not a translation table");
3669 size = MAX_CHAR;
3670 tt = NULL;
3672 else
3674 CHECK_STRING (table);
3676 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3677 table = string_make_unibyte (table);
3678 string_multibyte = SCHARS (table) < SBYTES (table);
3679 size = SBYTES (table);
3680 tt = SDATA (table);
3683 pos = XINT (start);
3684 pos_byte = CHAR_TO_BYTE (pos);
3685 end_pos = XINT (end);
3686 modify_text (pos, end_pos);
3688 cnt = 0;
3689 for (; pos < end_pos; )
3691 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3692 unsigned char *str UNINIT;
3693 unsigned char buf[MAX_MULTIBYTE_LENGTH];
3694 int len, str_len;
3695 int oc;
3696 Lisp_Object val;
3698 if (multibyte)
3699 oc = STRING_CHAR_AND_LENGTH (p, len);
3700 else
3701 oc = *p, len = 1;
3702 if (oc < size)
3704 if (tt)
3706 /* Reload as signal_after_change in last iteration may GC. */
3707 tt = SDATA (table);
3708 if (string_multibyte)
3710 str = tt + string_char_to_byte (table, oc);
3711 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3713 else
3715 nc = tt[oc];
3716 if (! ASCII_CHAR_P (nc) && multibyte)
3718 str_len = BYTE8_STRING (nc, buf);
3719 str = buf;
3721 else
3723 str_len = 1;
3724 str = tt + oc;
3728 else
3730 nc = oc;
3731 val = CHAR_TABLE_REF (table, oc);
3732 if (CHARACTERP (val))
3734 nc = XFASTINT (val);
3735 str_len = CHAR_STRING (nc, buf);
3736 str = buf;
3738 else if (VECTORP (val) || (CONSP (val)))
3740 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3741 where TO is TO-CHAR or [TO-CHAR ...]. */
3742 nc = -1;
3746 if (nc != oc && nc >= 0)
3748 /* Simple one char to one char translation. */
3749 if (len != str_len)
3751 Lisp_Object string;
3753 /* This is less efficient, because it moves the gap,
3754 but it should handle multibyte characters correctly. */
3755 string = make_multibyte_string ((char *) str, 1, str_len);
3756 replace_range (pos, pos + 1, string, 1, 0, 1, 0);
3757 len = str_len;
3759 else
3761 record_change (pos, 1);
3762 while (str_len-- > 0)
3763 *p++ = *str++;
3764 signal_after_change (pos, 1, 1);
3765 update_compositions (pos, pos + 1, CHECK_BORDER);
3767 ++cnt;
3769 else if (nc < 0)
3771 Lisp_Object string;
3773 if (CONSP (val))
3775 val = check_translation (pos, pos_byte, end_pos, val);
3776 if (NILP (val))
3778 pos_byte += len;
3779 pos++;
3780 continue;
3782 /* VAL is ([FROM-CHAR ...] . TO). */
3783 len = ASIZE (XCAR (val));
3784 val = XCDR (val);
3786 else
3787 len = 1;
3789 if (VECTORP (val))
3791 string = Fconcat (1, &val);
3793 else
3795 string = Fmake_string (make_number (1), val);
3797 replace_range (pos, pos + len, string, 1, 0, 1, 0);
3798 pos_byte += SBYTES (string);
3799 pos += SCHARS (string);
3800 cnt += SCHARS (string);
3801 end_pos += SCHARS (string) - len;
3802 continue;
3805 pos_byte += len;
3806 pos++;
3809 return make_number (cnt);
3812 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3813 doc: /* Delete the text between START and END.
3814 If called interactively, delete the region between point and mark.
3815 This command deletes buffer text without modifying the kill ring. */)
3816 (Lisp_Object start, Lisp_Object end)
3818 validate_region (&start, &end);
3819 del_range (XINT (start), XINT (end));
3820 return Qnil;
3823 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3824 Sdelete_and_extract_region, 2, 2, 0,
3825 doc: /* Delete the text between START and END and return it. */)
3826 (Lisp_Object start, Lisp_Object end)
3828 validate_region (&start, &end);
3829 if (XINT (start) == XINT (end))
3830 return empty_unibyte_string;
3831 return del_range_1 (XINT (start), XINT (end), 1, 1);
3834 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3835 doc: /* Remove restrictions (narrowing) from current buffer.
3836 This allows the buffer's full text to be seen and edited. */)
3837 (void)
3839 if (BEG != BEGV || Z != ZV)
3840 current_buffer->clip_changed = 1;
3841 BEGV = BEG;
3842 BEGV_BYTE = BEG_BYTE;
3843 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3844 /* Changing the buffer bounds invalidates any recorded current column. */
3845 invalidate_current_column ();
3846 return Qnil;
3849 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3850 doc: /* Restrict editing in this buffer to the current region.
3851 The rest of the text becomes temporarily invisible and untouchable
3852 but is not deleted; if you save the buffer in a file, the invisible
3853 text is included in the file. \\[widen] makes all visible again.
3854 See also `save-restriction'.
3856 When calling from a program, pass two arguments; positions (integers
3857 or markers) bounding the text that should remain visible. */)
3858 (register Lisp_Object start, Lisp_Object end)
3860 CHECK_NUMBER_COERCE_MARKER (start);
3861 CHECK_NUMBER_COERCE_MARKER (end);
3863 if (XINT (start) > XINT (end))
3865 Lisp_Object tem;
3866 tem = start; start = end; end = tem;
3869 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3870 args_out_of_range (start, end);
3872 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3873 current_buffer->clip_changed = 1;
3875 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3876 SET_BUF_ZV (current_buffer, XFASTINT (end));
3877 if (PT < XFASTINT (start))
3878 SET_PT (XFASTINT (start));
3879 if (PT > XFASTINT (end))
3880 SET_PT (XFASTINT (end));
3881 /* Changing the buffer bounds invalidates any recorded current column. */
3882 invalidate_current_column ();
3883 return Qnil;
3886 Lisp_Object
3887 save_restriction_save (void)
3889 if (BEGV == BEG && ZV == Z)
3890 /* The common case that the buffer isn't narrowed.
3891 We return just the buffer object, which save_restriction_restore
3892 recognizes as meaning `no restriction'. */
3893 return Fcurrent_buffer ();
3894 else
3895 /* We have to save a restriction, so return a pair of markers, one
3896 for the beginning and one for the end. */
3898 Lisp_Object beg, end;
3900 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3901 end = build_marker (current_buffer, ZV, ZV_BYTE);
3903 /* END must move forward if text is inserted at its exact location. */
3904 XMARKER (end)->insertion_type = 1;
3906 return Fcons (beg, end);
3910 void
3911 save_restriction_restore (Lisp_Object data)
3913 struct buffer *cur = NULL;
3914 struct buffer *buf = (CONSP (data)
3915 ? XMARKER (XCAR (data))->buffer
3916 : XBUFFER (data));
3918 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3919 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3920 is the case if it is or has an indirect buffer), then make
3921 sure it is current before we update BEGV, so
3922 set_buffer_internal takes care of managing those markers. */
3923 cur = current_buffer;
3924 set_buffer_internal (buf);
3927 if (CONSP (data))
3928 /* A pair of marks bounding a saved restriction. */
3930 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3931 struct Lisp_Marker *end = XMARKER (XCDR (data));
3932 eassert (buf == end->buffer);
3934 if (buf /* Verify marker still points to a buffer. */
3935 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3936 /* The restriction has changed from the saved one, so restore
3937 the saved restriction. */
3939 ptrdiff_t pt = BUF_PT (buf);
3941 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3942 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3944 if (pt < beg->charpos || pt > end->charpos)
3945 /* The point is outside the new visible range, move it inside. */
3946 SET_BUF_PT_BOTH (buf,
3947 clip_to_bounds (beg->charpos, pt, end->charpos),
3948 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3949 end->bytepos));
3951 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3953 /* Detach the markers, and free the cons instead of waiting for GC. */
3954 detach_marker (XCAR (data));
3955 detach_marker (XCDR (data));
3956 free_cons (XCONS (data));
3958 else
3959 /* A buffer, which means that there was no old restriction. */
3961 if (buf /* Verify marker still points to a buffer. */
3962 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3963 /* The buffer has been narrowed, get rid of the narrowing. */
3965 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3966 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3968 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3972 /* Changing the buffer bounds invalidates any recorded current column. */
3973 invalidate_current_column ();
3975 if (cur)
3976 set_buffer_internal (cur);
3979 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3980 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3981 The buffer's restrictions make parts of the beginning and end invisible.
3982 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3983 This special form, `save-restriction', saves the current buffer's restrictions
3984 when it is entered, and restores them when it is exited.
3985 So any `narrow-to-region' within BODY lasts only until the end of the form.
3986 The old restrictions settings are restored
3987 even in case of abnormal exit (throw or error).
3989 The value returned is the value of the last form in BODY.
3991 Note: if you are using both `save-excursion' and `save-restriction',
3992 use `save-excursion' outermost:
3993 (save-excursion (save-restriction ...))
3995 usage: (save-restriction &rest BODY) */)
3996 (Lisp_Object body)
3998 register Lisp_Object val;
3999 ptrdiff_t count = SPECPDL_INDEX ();
4001 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4002 val = Fprogn (body);
4003 return unbind_to (count, val);
4006 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
4007 doc: /* Display a message at the bottom of the screen.
4008 The message also goes into the `*Messages*' buffer, if `message-log-max'
4009 is non-nil. (In keyboard macros, that's all it does.)
4010 Return the message.
4012 In batch mode, the message is printed to the standard error stream,
4013 followed by a newline.
4015 The first argument is a format control string, and the rest are data
4016 to be formatted under control of the string. Percent sign (%), grave
4017 accent (\\=`) and apostrophe (\\=') are special in the format; see
4018 `format-message' for details. To display STRING without special
4019 treatment, use (message "%s" STRING).
4021 If the first argument is nil or the empty string, the function clears
4022 any existing message; this lets the minibuffer contents show. See
4023 also `current-message'.
4025 usage: (message FORMAT-STRING &rest ARGS) */)
4026 (ptrdiff_t nargs, Lisp_Object *args)
4028 if (NILP (args[0])
4029 || (STRINGP (args[0])
4030 && SBYTES (args[0]) == 0))
4032 message1 (0);
4033 return args[0];
4035 else
4037 Lisp_Object val = Fformat_message (nargs, args);
4038 message3 (val);
4039 return val;
4043 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
4044 doc: /* Display a message, in a dialog box if possible.
4045 If a dialog box is not available, use the echo area.
4046 The first argument is a format control string, and the rest are data
4047 to be formatted under control of the string. See `format-message' for
4048 details.
4050 If the first argument is nil or the empty string, clear any existing
4051 message; let the minibuffer contents show.
4053 usage: (message-box FORMAT-STRING &rest ARGS) */)
4054 (ptrdiff_t nargs, Lisp_Object *args)
4056 if (NILP (args[0]))
4058 message1 (0);
4059 return Qnil;
4061 else
4063 Lisp_Object val = Fformat_message (nargs, args);
4064 Lisp_Object pane, menu;
4066 pane = list1 (Fcons (build_string ("OK"), Qt));
4067 menu = Fcons (val, pane);
4068 Fx_popup_dialog (Qt, menu, Qt);
4069 return val;
4073 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
4074 doc: /* Display a message in a dialog box or in the echo area.
4075 If this command was invoked with the mouse, use a dialog box if
4076 `use-dialog-box' is non-nil.
4077 Otherwise, use the echo area.
4078 The first argument is a format control string, and the rest are data
4079 to be formatted under control of the string. See `format-message' for
4080 details.
4082 If the first argument is nil or the empty string, clear any existing
4083 message; let the minibuffer contents show.
4085 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
4086 (ptrdiff_t nargs, Lisp_Object *args)
4088 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
4089 && use_dialog_box)
4090 return Fmessage_box (nargs, args);
4091 return Fmessage (nargs, args);
4094 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
4095 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
4096 (void)
4098 return current_message ();
4102 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
4103 doc: /* Return a copy of STRING with text properties added.
4104 First argument is the string to copy.
4105 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4106 properties to add to the result.
4107 usage: (propertize STRING &rest PROPERTIES) */)
4108 (ptrdiff_t nargs, Lisp_Object *args)
4110 Lisp_Object properties, string;
4111 ptrdiff_t i;
4113 /* Number of args must be odd. */
4114 if ((nargs & 1) == 0)
4115 error ("Wrong number of arguments");
4117 properties = string = Qnil;
4119 /* First argument must be a string. */
4120 CHECK_STRING (args[0]);
4121 string = Fcopy_sequence (args[0]);
4123 for (i = 1; i < nargs; i += 2)
4124 properties = Fcons (args[i], Fcons (args[i + 1], properties));
4126 Fadd_text_properties (make_number (0),
4127 make_number (SCHARS (string)),
4128 properties, string);
4129 return string;
4132 /* Convert the prefix of STR from ASCII decimal digits to a number.
4133 Set *STR_END to the address of the first non-digit. Return the
4134 number, or PTRDIFF_MAX on overflow. Return 0 if there is no number.
4135 This is like strtol for ptrdiff_t and base 10 and C locale,
4136 except without negative numbers or errno. */
4138 static ptrdiff_t
4139 str2num (char *str, char **str_end)
4141 ptrdiff_t n = 0;
4142 for (; c_isdigit (*str); str++)
4143 if (INT_MULTIPLY_WRAPV (n, 10, &n) || INT_ADD_WRAPV (n, *str - '0', &n))
4144 n = PTRDIFF_MAX;
4145 *str_end = str;
4146 return n;
4149 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
4150 doc: /* Format a string out of a format-string and arguments.
4151 The first argument is a format control string.
4152 The other arguments are substituted into it to make the result, a string.
4154 The format control string may contain %-sequences meaning to substitute
4155 the next available argument, or the argument explicitly specified:
4157 %s means print a string argument. Actually, prints any object, with `princ'.
4158 %d means print as signed number in decimal.
4159 %o means print as unsigned number in octal.
4160 %x means print as unsigned number in hex.
4161 %X is like %x, but uses upper case.
4162 %e means print a number in exponential notation.
4163 %f means print a number in decimal-point notation.
4164 %g means print a number in exponential notation if the exponent would be
4165 less than -4 or greater than or equal to the precision (default: 6);
4166 otherwise it prints in decimal-point notation.
4167 %c means print a number as a single character.
4168 %S means print any object as an s-expression (using `prin1').
4170 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4171 Use %% to put a single % into the output.
4173 A %-sequence other than %% may contain optional field number, flag,
4174 width, and precision specifiers, as follows:
4176 %<field><flags><width><precision>character
4178 where field is [0-9]+ followed by a literal dollar "$", flags is
4179 [+ #-0]+, width is [0-9]+, and precision is a literal period "."
4180 followed by [0-9]+.
4182 If a %-sequence is numbered with a field with positive value N, the
4183 Nth argument is substituted instead of the next one. A format can
4184 contain either numbered or unnumbered %-sequences but not both, except
4185 that %% can be mixed with numbered %-sequences.
4187 The + flag character inserts a + before any positive number, while a
4188 space inserts a space before any positive number; these flags only
4189 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
4190 The - and 0 flags affect the width specifier, as described below.
4192 The # flag means to use an alternate display form for %o, %x, %X, %e,
4193 %f, and %g sequences: for %o, it ensures that the result begins with
4194 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
4195 for %e and %f, it causes a decimal point to be included even if the
4196 precision is zero; for %g, it causes a decimal point to be
4197 included even if the precision is zero, and also forces trailing
4198 zeros after the decimal point to be left in place.
4200 The width specifier supplies a lower limit for the length of the
4201 printed representation. The padding, if any, normally goes on the
4202 left, but it goes on the right if the - flag is present. The padding
4203 character is normally a space, but it is 0 if the 0 flag is present.
4204 The 0 flag is ignored if the - flag is present, or the format sequence
4205 is something other than %d, %e, %f, and %g.
4207 For %e and %f sequences, the number after the "." in the precision
4208 specifier says how many decimal places to show; if zero, the decimal
4209 point itself is omitted. For %g, the precision specifies how many
4210 significant digits to print; zero or omitted are treated as 1.
4211 For %s and %S, the precision specifier truncates the string to the
4212 given width.
4214 Text properties, if any, are copied from the format-string to the
4215 produced text.
4217 usage: (format STRING &rest OBJECTS) */)
4218 (ptrdiff_t nargs, Lisp_Object *args)
4220 return styled_format (nargs, args, false);
4223 DEFUN ("format-message", Fformat_message, Sformat_message, 1, MANY, 0,
4224 doc: /* Format a string out of a format-string and arguments.
4225 The first argument is a format control string.
4226 The other arguments are substituted into it to make the result, a string.
4228 This acts like `format', except it also replaces each grave accent (\\=`)
4229 by a left quote, and each apostrophe (\\=') by a right quote. The left
4230 and right quote replacement characters are specified by
4231 `text-quoting-style'.
4233 usage: (format-message STRING &rest OBJECTS) */)
4234 (ptrdiff_t nargs, Lisp_Object *args)
4236 return styled_format (nargs, args, true);
4239 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise. */
4241 static Lisp_Object
4242 styled_format (ptrdiff_t nargs, Lisp_Object *args, bool message)
4244 ptrdiff_t n; /* The number of the next arg to substitute. */
4245 char initial_buffer[4000];
4246 char *buf = initial_buffer;
4247 ptrdiff_t bufsize = sizeof initial_buffer;
4248 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
4249 char *p;
4250 ptrdiff_t buf_save_value_index UNINIT;
4251 char *format, *end;
4252 ptrdiff_t nchars;
4253 /* When we make a multibyte string, we must pay attention to the
4254 byte combining problem, i.e., a byte may be combined with a
4255 multibyte character of the previous string. This flag tells if we
4256 must consider such a situation or not. */
4257 bool maybe_combine_byte;
4258 Lisp_Object val;
4259 bool arg_intervals = false;
4260 USE_SAFE_ALLOCA;
4261 sa_avail -= sizeof initial_buffer;
4263 /* Information recorded for each format spec. */
4264 struct info
4266 /* The corresponding argument, converted to string if conversion
4267 was needed. */
4268 Lisp_Object argument;
4270 /* The start and end bytepos in the output string. */
4271 ptrdiff_t start, end;
4273 /* Whether the argument is a string with intervals. */
4274 bool_bf intervals : 1;
4275 } *info;
4277 CHECK_STRING (args[0]);
4278 char *format_start = SSDATA (args[0]);
4279 bool multibyte_format = STRING_MULTIBYTE (args[0]);
4280 ptrdiff_t formatlen = SBYTES (args[0]);
4282 /* Upper bound on number of format specs. Each uses at least 2 chars. */
4283 ptrdiff_t nspec_bound = SCHARS (args[0]) >> 1;
4285 /* Allocate the info and discarded tables. */
4286 ptrdiff_t alloca_size;
4287 if (INT_MULTIPLY_WRAPV (nspec_bound, sizeof *info, &alloca_size)
4288 || INT_ADD_WRAPV (formatlen, alloca_size, &alloca_size)
4289 || SIZE_MAX < alloca_size)
4290 memory_full (SIZE_MAX);
4291 info = SAFE_ALLOCA (alloca_size);
4292 /* discarded[I] is 1 if byte I of the format
4293 string was not copied into the output.
4294 It is 2 if byte I was not the first byte of its character. */
4295 char *discarded = (char *) &info[nspec_bound];
4296 memset (discarded, 0, formatlen);
4298 /* Try to determine whether the result should be multibyte.
4299 This is not always right; sometimes the result needs to be multibyte
4300 because of an object that we will pass through prin1.
4301 or because a grave accent or apostrophe is requoted,
4302 and in that case, we won't know it here. */
4304 /* True if the output should be a multibyte string,
4305 which is true if any of the inputs is one. */
4306 bool multibyte = multibyte_format;
4307 for (ptrdiff_t i = 1; !multibyte && i < nargs; i++)
4308 if (STRINGP (args[i]) && STRING_MULTIBYTE (args[i]))
4309 multibyte = true;
4311 int quoting_style = message ? text_quoting_style () : -1;
4313 ptrdiff_t ispec;
4314 ptrdiff_t nspec = 0;
4316 /* True if a string needs to be allocated to hold the result. */
4317 bool new_result = false;
4319 /* If we start out planning a unibyte result,
4320 then discover it has to be multibyte, we jump back to retry. */
4321 retry:
4323 p = buf;
4324 nchars = 0;
4326 /* N is the argument index, ISPEC is the specification index. */
4327 n = 0;
4328 ispec = 0;
4330 /* Scan the format and store result in BUF. */
4331 format = format_start;
4332 end = format + formatlen;
4333 maybe_combine_byte = false;
4335 while (format != end)
4337 /* The values of N, ISPEC, and FORMAT when the loop body is
4338 entered. */
4339 ptrdiff_t n0 = n;
4340 ptrdiff_t ispec0 = ispec;
4341 char *format0 = format;
4342 char const *convsrc = format;
4343 unsigned char format_char = *format++;
4345 /* Bytes needed to represent the output of this conversion. */
4346 ptrdiff_t convbytes = 1;
4348 if (format_char == '%')
4350 /* General format specifications look like
4352 '%' [field-number] [flags] [field-width] [precision] format
4354 where
4356 field-number ::= [0-9]+ '$'
4357 flags ::= [-+0# ]+
4358 field-width ::= [0-9]+
4359 precision ::= '.' [0-9]*
4361 If present, a field-number specifies the argument number
4362 to substitute. Otherwise, the next argument is taken.
4364 If a field-width is specified, it specifies to which width
4365 the output should be padded with blanks, if the output
4366 string is shorter than field-width.
4368 If precision is specified, it specifies the number of
4369 digits to print after the '.' for floats, or the max.
4370 number of chars to print from a string. */
4372 ptrdiff_t num;
4373 char *num_end;
4374 if (c_isdigit (*format))
4376 num = str2num (format, &num_end);
4377 if (*num_end == '$')
4379 n = num - 1;
4380 format = num_end + 1;
4384 bool minus_flag = false;
4385 bool plus_flag = false;
4386 bool space_flag = false;
4387 bool sharp_flag = false;
4388 bool zero_flag = false;
4390 for (; ; format++)
4392 switch (*format)
4394 case '-': minus_flag = true; continue;
4395 case '+': plus_flag = true; continue;
4396 case ' ': space_flag = true; continue;
4397 case '#': sharp_flag = true; continue;
4398 case '0': zero_flag = true; continue;
4400 break;
4403 /* Ignore flags when sprintf ignores them. */
4404 space_flag &= ! plus_flag;
4405 zero_flag &= ! minus_flag;
4407 num = str2num (format, &num_end);
4408 if (max_bufsize <= num)
4409 string_overflow ();
4410 ptrdiff_t field_width = num;
4412 bool precision_given = *num_end == '.';
4413 ptrdiff_t precision = (precision_given
4414 ? str2num (num_end + 1, &num_end)
4415 : PTRDIFF_MAX);
4416 format = num_end;
4418 if (format == end)
4419 error ("Format string ends in middle of format specifier");
4421 char conversion = *format++;
4422 memset (&discarded[format0 - format_start], 1,
4423 format - format0 - (conversion == '%'));
4424 if (conversion == '%')
4426 new_result = true;
4427 goto copy_char;
4430 ++n;
4431 if (! (n < nargs))
4432 error ("Not enough arguments for format string");
4434 struct info *spec = &info[ispec++];
4435 if (nspec < ispec)
4437 spec->argument = args[n];
4438 spec->intervals = false;
4439 nspec = ispec;
4441 Lisp_Object arg = spec->argument;
4443 /* For 'S', prin1 the argument, and then treat like 's'.
4444 For 's', princ any argument that is not a string or
4445 symbol. But don't do this conversion twice, which might
4446 happen after retrying. */
4447 if ((conversion == 'S'
4448 || (conversion == 's'
4449 && ! STRINGP (arg) && ! SYMBOLP (arg))))
4451 if (EQ (arg, args[n]))
4453 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
4454 spec->argument = arg = Fprin1_to_string (arg, noescape);
4455 if (STRING_MULTIBYTE (arg) && ! multibyte)
4457 multibyte = true;
4458 goto retry;
4461 conversion = 's';
4463 else if (conversion == 'c')
4465 if (INTEGERP (arg) && ! ASCII_CHAR_P (XINT (arg)))
4467 if (!multibyte)
4469 multibyte = true;
4470 goto retry;
4472 spec->argument = arg = Fchar_to_string (arg);
4475 if (!EQ (arg, args[n]))
4476 conversion = 's';
4477 zero_flag = false;
4480 if (SYMBOLP (arg))
4482 spec->argument = arg = SYMBOL_NAME (arg);
4483 if (STRING_MULTIBYTE (arg) && ! multibyte)
4485 multibyte = true;
4486 goto retry;
4490 bool float_conversion
4491 = conversion == 'e' || conversion == 'f' || conversion == 'g';
4493 if (conversion == 's')
4495 if (format == end && format - format_start == 2
4496 && ! string_intervals (args[0]))
4498 val = arg;
4499 goto return_val;
4502 /* handle case (precision[n] >= 0) */
4504 ptrdiff_t prec = -1;
4505 if (precision_given)
4506 prec = precision;
4508 /* lisp_string_width ignores a precision of 0, but GNU
4509 libc functions print 0 characters when the precision
4510 is 0. Imitate libc behavior here. Changing
4511 lisp_string_width is the right thing, and will be
4512 done, but meanwhile we work with it. */
4514 ptrdiff_t width, nbytes;
4515 ptrdiff_t nchars_string;
4516 if (prec == 0)
4517 width = nchars_string = nbytes = 0;
4518 else
4520 ptrdiff_t nch, nby;
4521 width = lisp_string_width (arg, prec, &nch, &nby);
4522 if (prec < 0)
4524 nchars_string = SCHARS (arg);
4525 nbytes = SBYTES (arg);
4527 else
4529 nchars_string = nch;
4530 nbytes = nby;
4534 convbytes = nbytes;
4535 if (convbytes && multibyte && ! STRING_MULTIBYTE (arg))
4536 convbytes = count_size_as_multibyte (SDATA (arg), nbytes);
4538 ptrdiff_t padding
4539 = width < field_width ? field_width - width : 0;
4541 if (max_bufsize - padding <= convbytes)
4542 string_overflow ();
4543 convbytes += padding;
4544 if (convbytes <= buf + bufsize - p)
4546 if (! minus_flag)
4548 memset (p, ' ', padding);
4549 p += padding;
4550 nchars += padding;
4552 spec->start = nchars;
4554 if (p > buf
4555 && multibyte
4556 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4557 && STRING_MULTIBYTE (arg)
4558 && !CHAR_HEAD_P (SREF (arg, 0)))
4559 maybe_combine_byte = true;
4561 p += copy_text (SDATA (arg), (unsigned char *) p,
4562 nbytes,
4563 STRING_MULTIBYTE (arg), multibyte);
4565 nchars += nchars_string;
4567 if (minus_flag)
4569 memset (p, ' ', padding);
4570 p += padding;
4571 nchars += padding;
4573 spec->end = nchars;
4575 /* If this argument has text properties, record where
4576 in the result string it appears. */
4577 if (string_intervals (arg))
4578 spec->intervals = arg_intervals = true;
4580 new_result = true;
4581 continue;
4584 else if (! (conversion == 'c' || conversion == 'd'
4585 || float_conversion || conversion == 'i'
4586 || conversion == 'o' || conversion == 'x'
4587 || conversion == 'X'))
4588 error ("Invalid format operation %%%c",
4589 STRING_CHAR ((unsigned char *) format - 1));
4590 else if (! (INTEGERP (arg) || (FLOATP (arg) && conversion != 'c')))
4591 error ("Format specifier doesn't match argument type");
4592 else
4594 enum
4596 /* Lower bound on the number of bits per
4597 base-FLT_RADIX digit. */
4598 DIG_BITS_LBOUND = FLT_RADIX < 16 ? 1 : 4,
4600 /* 1 if integers should be formatted as long doubles,
4601 because they may be so large that there is a rounding
4602 error when converting them to double, and long doubles
4603 are wider than doubles. */
4604 INT_AS_LDBL = (DIG_BITS_LBOUND * DBL_MANT_DIG < FIXNUM_BITS - 1
4605 && DBL_MANT_DIG < LDBL_MANT_DIG),
4607 /* Maximum precision for a %f conversion such that the
4608 trailing output digit might be nonzero. Any precision
4609 larger than this will not yield useful information. */
4610 USEFUL_PRECISION_MAX =
4611 ((1 - LDBL_MIN_EXP)
4612 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4613 : FLT_RADIX == 16 ? 4
4614 : -1)),
4616 /* Maximum number of bytes generated by any format, if
4617 precision is no more than USEFUL_PRECISION_MAX.
4618 On all practical hosts, %f is the worst case. */
4619 SPRINTF_BUFSIZE =
4620 sizeof "-." + (LDBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4622 /* Length of pM (that is, of pMd without the
4623 trailing "d"). */
4624 pMlen = sizeof pMd - 2
4626 verify (USEFUL_PRECISION_MAX > 0);
4628 /* Avoid undefined behavior in underlying sprintf. */
4629 if (conversion == 'd' || conversion == 'i')
4630 sharp_flag = false;
4632 /* Create the copy of the conversion specification, with
4633 any width and precision removed, with ".*" inserted,
4634 with "L" possibly inserted for floating-point formats,
4635 and with pM inserted for integer formats.
4636 At most two flags F can be specified at once. */
4637 char convspec[sizeof "%FF.*d" + max (INT_AS_LDBL, pMlen)];
4639 char *f = convspec;
4640 *f++ = '%';
4641 /* MINUS_FLAG and ZERO_FLAG are dealt with later. */
4642 *f = '+'; f += plus_flag;
4643 *f = ' '; f += space_flag;
4644 *f = '#'; f += sharp_flag;
4645 *f++ = '.';
4646 *f++ = '*';
4647 if (float_conversion)
4649 if (INT_AS_LDBL)
4651 *f = 'L';
4652 f += INTEGERP (arg);
4655 else if (conversion != 'c')
4657 memcpy (f, pMd, pMlen);
4658 f += pMlen;
4659 zero_flag &= ! precision_given;
4661 *f++ = conversion;
4662 *f = '\0';
4665 int prec = -1;
4666 if (precision_given)
4667 prec = min (precision, USEFUL_PRECISION_MAX);
4669 /* Use sprintf to format this number into sprintf_buf. Omit
4670 padding and excess precision, though, because sprintf limits
4671 output length to INT_MAX.
4673 There are four types of conversion: double, unsigned
4674 char (passed as int), wide signed int, and wide
4675 unsigned int. Treat them separately because the
4676 sprintf ABI is sensitive to which type is passed. Be
4677 careful about integer overflow, NaNs, infinities, and
4678 conversions; for example, the min and max macros are
4679 not suitable here. */
4680 char sprintf_buf[SPRINTF_BUFSIZE];
4681 ptrdiff_t sprintf_bytes;
4682 if (float_conversion)
4684 if (INT_AS_LDBL && INTEGERP (arg))
4686 /* Although long double may have a rounding error if
4687 DIG_BITS_LBOUND * LDBL_MANT_DIG < FIXNUM_BITS - 1,
4688 it is more accurate than plain 'double'. */
4689 long double x = XINT (arg);
4690 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4692 else
4693 sprintf_bytes = sprintf (sprintf_buf, convspec, prec,
4694 XFLOATINT (arg));
4696 else if (conversion == 'c')
4698 /* Don't use sprintf here, as it might mishandle prec. */
4699 sprintf_buf[0] = XINT (arg);
4700 sprintf_bytes = prec != 0;
4702 else if (conversion == 'd' || conversion == 'i')
4704 /* For float, maybe we should use "%1.0f"
4705 instead so it also works for values outside
4706 the integer range. */
4707 printmax_t x;
4708 if (INTEGERP (arg))
4709 x = XINT (arg);
4710 else
4712 double d = XFLOAT_DATA (arg);
4713 if (d < 0)
4715 x = TYPE_MINIMUM (printmax_t);
4716 if (x < d)
4717 x = d;
4719 else
4721 x = TYPE_MAXIMUM (printmax_t);
4722 if (d < x)
4723 x = d;
4726 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4728 else
4730 /* Don't sign-extend for octal or hex printing. */
4731 uprintmax_t x;
4732 if (INTEGERP (arg))
4733 x = XUINT (arg);
4734 else
4736 double d = XFLOAT_DATA (arg);
4737 if (d < 0)
4738 x = 0;
4739 else
4741 x = TYPE_MAXIMUM (uprintmax_t);
4742 if (d < x)
4743 x = d;
4746 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4749 /* Now the length of the formatted item is known, except it omits
4750 padding and excess precision. Deal with excess precision
4751 first. This happens only when the format specifies
4752 ridiculously large precision. */
4753 ptrdiff_t excess_precision
4754 = precision_given ? precision - prec : 0;
4755 ptrdiff_t leading_zeros = 0, trailing_zeros = 0;
4756 if (excess_precision)
4758 if (float_conversion)
4760 if ((conversion == 'g' && ! sharp_flag)
4761 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4762 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4763 excess_precision = 0;
4764 else
4766 if (conversion == 'g')
4768 char *dot = strchr (sprintf_buf, '.');
4769 if (!dot)
4770 excess_precision = 0;
4773 trailing_zeros = excess_precision;
4775 else
4776 leading_zeros = excess_precision;
4779 /* Compute the total bytes needed for this item, including
4780 excess precision and padding. */
4781 ptrdiff_t numwidth;
4782 if (INT_ADD_WRAPV (sprintf_bytes, excess_precision, &numwidth))
4783 numwidth = PTRDIFF_MAX;
4784 ptrdiff_t padding
4785 = numwidth < field_width ? field_width - numwidth : 0;
4786 if (max_bufsize - sprintf_bytes <= excess_precision
4787 || max_bufsize - padding <= numwidth)
4788 string_overflow ();
4789 convbytes = numwidth + padding;
4791 if (convbytes <= buf + bufsize - p)
4793 /* Copy the formatted item from sprintf_buf into buf,
4794 inserting padding and excess-precision zeros. */
4796 char *src = sprintf_buf;
4797 char src0 = src[0];
4798 int exponent_bytes = 0;
4799 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4800 unsigned char after_sign = src[signedp];
4801 if (zero_flag && 0 <= char_hexdigit (after_sign))
4803 leading_zeros += padding;
4804 padding = 0;
4807 if (excess_precision
4808 && (conversion == 'e' || conversion == 'g'))
4810 char *e = strchr (src, 'e');
4811 if (e)
4812 exponent_bytes = src + sprintf_bytes - e;
4815 spec->start = nchars;
4816 if (! minus_flag)
4818 memset (p, ' ', padding);
4819 p += padding;
4820 nchars += padding;
4823 *p = src0;
4824 src += signedp;
4825 p += signedp;
4826 memset (p, '0', leading_zeros);
4827 p += leading_zeros;
4828 int significand_bytes
4829 = sprintf_bytes - signedp - exponent_bytes;
4830 memcpy (p, src, significand_bytes);
4831 p += significand_bytes;
4832 src += significand_bytes;
4833 memset (p, '0', trailing_zeros);
4834 p += trailing_zeros;
4835 memcpy (p, src, exponent_bytes);
4836 p += exponent_bytes;
4838 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4840 if (minus_flag)
4842 memset (p, ' ', padding);
4843 p += padding;
4844 nchars += padding;
4846 spec->end = nchars;
4848 new_result = true;
4849 continue;
4853 else
4855 unsigned char str[MAX_MULTIBYTE_LENGTH];
4857 if ((format_char == '`' || format_char == '\'')
4858 && quoting_style == CURVE_QUOTING_STYLE)
4860 if (! multibyte)
4862 multibyte = true;
4863 goto retry;
4865 convsrc = format_char == '`' ? uLSQM : uRSQM;
4866 convbytes = 3;
4867 new_result = true;
4869 else if (format_char == '`' && quoting_style == STRAIGHT_QUOTING_STYLE)
4871 convsrc = "'";
4872 new_result = true;
4874 else
4876 /* Copy a single character from format to buf. */
4877 if (multibyte_format)
4879 /* Copy a whole multibyte character. */
4880 if (p > buf
4881 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4882 && !CHAR_HEAD_P (format_char))
4883 maybe_combine_byte = true;
4885 while (! CHAR_HEAD_P (*format))
4886 format++;
4888 convbytes = format - format0;
4889 memset (&discarded[format0 + 1 - format_start], 2,
4890 convbytes - 1);
4892 else if (multibyte && !ASCII_CHAR_P (format_char))
4894 int c = BYTE8_TO_CHAR (format_char);
4895 convbytes = CHAR_STRING (c, str);
4896 convsrc = (char *) str;
4897 new_result = true;
4901 copy_char:
4902 if (convbytes <= buf + bufsize - p)
4904 memcpy (p, convsrc, convbytes);
4905 p += convbytes;
4906 nchars++;
4907 continue;
4911 /* There wasn't enough room to store this conversion or single
4912 character. CONVBYTES says how much room is needed. Allocate
4913 enough room (and then some) and do it again. */
4915 ptrdiff_t used = p - buf;
4916 if (max_bufsize - used < convbytes)
4917 string_overflow ();
4918 bufsize = used + convbytes;
4919 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4921 if (buf == initial_buffer)
4923 buf = xmalloc (bufsize);
4924 sa_must_free = true;
4925 buf_save_value_index = SPECPDL_INDEX ();
4926 record_unwind_protect_ptr (xfree, buf);
4927 memcpy (buf, initial_buffer, used);
4929 else
4931 buf = xrealloc (buf, bufsize);
4932 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4935 p = buf + used;
4936 format = format0;
4937 n = n0;
4938 ispec = ispec0;
4941 if (bufsize < p - buf)
4942 emacs_abort ();
4944 if (! new_result)
4946 val = args[0];
4947 goto return_val;
4950 if (maybe_combine_byte)
4951 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4952 val = make_specified_string (buf, nchars, p - buf, multibyte);
4954 /* If the format string has text properties, or any of the string
4955 arguments has text properties, set up text properties of the
4956 result string. */
4958 if (string_intervals (args[0]) || arg_intervals)
4960 /* Add text properties from the format string. */
4961 Lisp_Object len = make_number (SCHARS (args[0]));
4962 Lisp_Object props = text_property_list (args[0], make_number (0),
4963 len, Qnil);
4964 if (CONSP (props))
4966 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4967 ptrdiff_t fieldn = 0;
4969 /* Adjust the bounds of each text property
4970 to the proper start and end in the output string. */
4972 /* Put the positions in PROPS in increasing order, so that
4973 we can do (effectively) one scan through the position
4974 space of the format string. */
4975 props = Fnreverse (props);
4977 /* BYTEPOS is the byte position in the format string,
4978 POSITION is the untranslated char position in it,
4979 TRANSLATED is the translated char position in BUF,
4980 and ARGN is the number of the next arg we will come to. */
4981 for (Lisp_Object list = props; CONSP (list); list = XCDR (list))
4983 Lisp_Object item = XCAR (list);
4985 /* First adjust the property start position. */
4986 ptrdiff_t pos = XINT (XCAR (item));
4988 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4989 up to this position. */
4990 for (; position < pos; bytepos++)
4992 if (! discarded[bytepos])
4993 position++, translated++;
4994 else if (discarded[bytepos] == 1)
4996 position++;
4997 if (fieldn < nspec && translated == info[fieldn].start)
4999 translated += info[fieldn].end - info[fieldn].start;
5000 fieldn++;
5005 XSETCAR (item, make_number (translated));
5007 /* Likewise adjust the property end position. */
5008 pos = XINT (XCAR (XCDR (item)));
5010 for (; position < pos; bytepos++)
5012 if (! discarded[bytepos])
5013 position++, translated++;
5014 else if (discarded[bytepos] == 1)
5016 position++;
5017 if (fieldn < nspec && translated == info[fieldn].start)
5019 translated += info[fieldn].end - info[fieldn].start;
5020 fieldn++;
5025 XSETCAR (XCDR (item), make_number (translated));
5028 add_text_properties_from_list (val, props, make_number (0));
5031 /* Add text properties from arguments. */
5032 if (arg_intervals)
5033 for (ptrdiff_t i = 0; i < nspec; i++)
5034 if (info[i].intervals)
5036 len = make_number (SCHARS (info[i].argument));
5037 Lisp_Object new_len = make_number (info[i].end - info[i].start);
5038 props = text_property_list (info[i].argument,
5039 make_number (0), len, Qnil);
5040 props = extend_property_ranges (props, len, new_len);
5041 /* If successive arguments have properties, be sure that
5042 the value of `composition' property be the copy. */
5043 if (1 < i && info[i - 1].end)
5044 make_composition_value_copy (props);
5045 add_text_properties_from_list (val, props,
5046 make_number (info[i].start));
5050 return_val:
5051 /* If we allocated BUF or INFO with malloc, free it too. */
5052 SAFE_FREE ();
5054 return val;
5057 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
5058 doc: /* Return t if two characters match, optionally ignoring case.
5059 Both arguments must be characters (i.e. integers).
5060 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
5061 (register Lisp_Object c1, Lisp_Object c2)
5063 int i1, i2;
5064 /* Check they're chars, not just integers, otherwise we could get array
5065 bounds violations in downcase. */
5066 CHECK_CHARACTER (c1);
5067 CHECK_CHARACTER (c2);
5069 if (XINT (c1) == XINT (c2))
5070 return Qt;
5071 if (NILP (BVAR (current_buffer, case_fold_search)))
5072 return Qnil;
5074 i1 = XFASTINT (c1);
5075 i2 = XFASTINT (c2);
5077 /* FIXME: It is possible to compare multibyte characters even when
5078 the current buffer is unibyte. Unfortunately this is ambiguous
5079 for characters between 128 and 255, as they could be either
5080 eight-bit raw bytes or Latin-1 characters. Assume the former for
5081 now. See Bug#17011, and also see casefiddle.c's casify_object,
5082 which has a similar problem. */
5083 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
5085 if (SINGLE_BYTE_CHAR_P (i1))
5086 i1 = UNIBYTE_TO_CHAR (i1);
5087 if (SINGLE_BYTE_CHAR_P (i2))
5088 i2 = UNIBYTE_TO_CHAR (i2);
5091 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
5094 /* Transpose the markers in two regions of the current buffer, and
5095 adjust the ones between them if necessary (i.e.: if the regions
5096 differ in size).
5098 START1, END1 are the character positions of the first region.
5099 START1_BYTE, END1_BYTE are the byte positions.
5100 START2, END2 are the character positions of the second region.
5101 START2_BYTE, END2_BYTE are the byte positions.
5103 Traverses the entire marker list of the buffer to do so, adding an
5104 appropriate amount to some, subtracting from some, and leaving the
5105 rest untouched. Most of this is copied from adjust_markers in insdel.c.
5107 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
5109 static void
5110 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
5111 ptrdiff_t start2, ptrdiff_t end2,
5112 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
5113 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
5115 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
5116 register struct Lisp_Marker *marker;
5118 /* Update point as if it were a marker. */
5119 if (PT < start1)
5121 else if (PT < end1)
5122 TEMP_SET_PT_BOTH (PT + (end2 - end1),
5123 PT_BYTE + (end2_byte - end1_byte));
5124 else if (PT < start2)
5125 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
5126 (PT_BYTE + (end2_byte - start2_byte)
5127 - (end1_byte - start1_byte)));
5128 else if (PT < end2)
5129 TEMP_SET_PT_BOTH (PT - (start2 - start1),
5130 PT_BYTE - (start2_byte - start1_byte));
5132 /* We used to adjust the endpoints here to account for the gap, but that
5133 isn't good enough. Even if we assume the caller has tried to move the
5134 gap out of our way, it might still be at start1 exactly, for example;
5135 and that places it `inside' the interval, for our purposes. The amount
5136 of adjustment is nontrivial if there's a `denormalized' marker whose
5137 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
5138 the dirty work to Fmarker_position, below. */
5140 /* The difference between the region's lengths */
5141 diff = (end2 - start2) - (end1 - start1);
5142 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
5144 /* For shifting each marker in a region by the length of the other
5145 region plus the distance between the regions. */
5146 amt1 = (end2 - start2) + (start2 - end1);
5147 amt2 = (end1 - start1) + (start2 - end1);
5148 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
5149 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
5151 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
5153 mpos = marker->bytepos;
5154 if (mpos >= start1_byte && mpos < end2_byte)
5156 if (mpos < end1_byte)
5157 mpos += amt1_byte;
5158 else if (mpos < start2_byte)
5159 mpos += diff_byte;
5160 else
5161 mpos -= amt2_byte;
5162 marker->bytepos = mpos;
5164 mpos = marker->charpos;
5165 if (mpos >= start1 && mpos < end2)
5167 if (mpos < end1)
5168 mpos += amt1;
5169 else if (mpos < start2)
5170 mpos += diff;
5171 else
5172 mpos -= amt2;
5174 marker->charpos = mpos;
5178 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
5179 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
5180 The regions should not be overlapping, because the size of the buffer is
5181 never changed in a transposition.
5183 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
5184 any markers that happen to be located in the regions.
5186 Transposing beyond buffer boundaries is an error. */)
5187 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
5189 register ptrdiff_t start1, end1, start2, end2;
5190 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
5191 ptrdiff_t gap, len1, len_mid, len2;
5192 unsigned char *start1_addr, *start2_addr, *temp;
5194 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
5195 Lisp_Object buf;
5197 XSETBUFFER (buf, current_buffer);
5198 cur_intv = buffer_intervals (current_buffer);
5200 validate_region (&startr1, &endr1);
5201 validate_region (&startr2, &endr2);
5203 start1 = XFASTINT (startr1);
5204 end1 = XFASTINT (endr1);
5205 start2 = XFASTINT (startr2);
5206 end2 = XFASTINT (endr2);
5207 gap = GPT;
5209 /* Swap the regions if they're reversed. */
5210 if (start2 < end1)
5212 register ptrdiff_t glumph = start1;
5213 start1 = start2;
5214 start2 = glumph;
5215 glumph = end1;
5216 end1 = end2;
5217 end2 = glumph;
5220 len1 = end1 - start1;
5221 len2 = end2 - start2;
5223 if (start2 < end1)
5224 error ("Transposed regions overlap");
5225 /* Nothing to change for adjacent regions with one being empty */
5226 else if ((start1 == end1 || start2 == end2) && end1 == start2)
5227 return Qnil;
5229 /* The possibilities are:
5230 1. Adjacent (contiguous) regions, or separate but equal regions
5231 (no, really equal, in this case!), or
5232 2. Separate regions of unequal size.
5234 The worst case is usually No. 2. It means that (aside from
5235 potential need for getting the gap out of the way), there also
5236 needs to be a shifting of the text between the two regions. So
5237 if they are spread far apart, we are that much slower... sigh. */
5239 /* It must be pointed out that the really studly thing to do would
5240 be not to move the gap at all, but to leave it in place and work
5241 around it if necessary. This would be extremely efficient,
5242 especially considering that people are likely to do
5243 transpositions near where they are working interactively, which
5244 is exactly where the gap would be found. However, such code
5245 would be much harder to write and to read. So, if you are
5246 reading this comment and are feeling squirrely, by all means have
5247 a go! I just didn't feel like doing it, so I will simply move
5248 the gap the minimum distance to get it out of the way, and then
5249 deal with an unbroken array. */
5251 start1_byte = CHAR_TO_BYTE (start1);
5252 end2_byte = CHAR_TO_BYTE (end2);
5254 /* Make sure the gap won't interfere, by moving it out of the text
5255 we will operate on. */
5256 if (start1 < gap && gap < end2)
5258 if (gap - start1 < end2 - gap)
5259 move_gap_both (start1, start1_byte);
5260 else
5261 move_gap_both (end2, end2_byte);
5264 start2_byte = CHAR_TO_BYTE (start2);
5265 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
5266 len2_byte = end2_byte - start2_byte;
5268 #ifdef BYTE_COMBINING_DEBUG
5269 if (end1 == start2)
5271 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
5272 len2_byte, start1, start1_byte)
5273 || count_combining_before (BYTE_POS_ADDR (start1_byte),
5274 len1_byte, end2, start2_byte + len2_byte)
5275 || count_combining_after (BYTE_POS_ADDR (start1_byte),
5276 len1_byte, end2, start2_byte + len2_byte))
5277 emacs_abort ();
5279 else
5281 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
5282 len2_byte, start1, start1_byte)
5283 || count_combining_before (BYTE_POS_ADDR (start1_byte),
5284 len1_byte, start2, start2_byte)
5285 || count_combining_after (BYTE_POS_ADDR (start2_byte),
5286 len2_byte, end1, start1_byte + len1_byte)
5287 || count_combining_after (BYTE_POS_ADDR (start1_byte),
5288 len1_byte, end2, start2_byte + len2_byte))
5289 emacs_abort ();
5291 #endif
5293 /* Hmmm... how about checking to see if the gap is large
5294 enough to use as the temporary storage? That would avoid an
5295 allocation... interesting. Later, don't fool with it now. */
5297 /* Working without memmove, for portability (sigh), so must be
5298 careful of overlapping subsections of the array... */
5300 if (end1 == start2) /* adjacent regions */
5302 modify_text (start1, end2);
5303 record_change (start1, len1 + len2);
5305 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5306 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5307 /* Don't use Fset_text_properties: that can cause GC, which can
5308 clobber objects stored in the tmp_intervals. */
5309 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5310 if (tmp_interval3)
5311 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5313 USE_SAFE_ALLOCA;
5315 /* First region smaller than second. */
5316 if (len1_byte < len2_byte)
5318 temp = SAFE_ALLOCA (len2_byte);
5320 /* Don't precompute these addresses. We have to compute them
5321 at the last minute, because the relocating allocator might
5322 have moved the buffer around during the xmalloc. */
5323 start1_addr = BYTE_POS_ADDR (start1_byte);
5324 start2_addr = BYTE_POS_ADDR (start2_byte);
5326 memcpy (temp, start2_addr, len2_byte);
5327 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
5328 memcpy (start1_addr, temp, len2_byte);
5330 else
5331 /* First region not smaller than second. */
5333 temp = SAFE_ALLOCA (len1_byte);
5334 start1_addr = BYTE_POS_ADDR (start1_byte);
5335 start2_addr = BYTE_POS_ADDR (start2_byte);
5336 memcpy (temp, start1_addr, len1_byte);
5337 memcpy (start1_addr, start2_addr, len2_byte);
5338 memcpy (start1_addr + len2_byte, temp, len1_byte);
5341 SAFE_FREE ();
5342 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
5343 len1, current_buffer, 0);
5344 graft_intervals_into_buffer (tmp_interval2, start1,
5345 len2, current_buffer, 0);
5346 update_compositions (start1, start1 + len2, CHECK_BORDER);
5347 update_compositions (start1 + len2, end2, CHECK_TAIL);
5349 /* Non-adjacent regions, because end1 != start2, bleagh... */
5350 else
5352 len_mid = start2_byte - (start1_byte + len1_byte);
5354 if (len1_byte == len2_byte)
5355 /* Regions are same size, though, how nice. */
5357 USE_SAFE_ALLOCA;
5359 modify_text (start1, end1);
5360 modify_text (start2, end2);
5361 record_change (start1, len1);
5362 record_change (start2, len2);
5363 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5364 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5366 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
5367 if (tmp_interval3)
5368 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
5370 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
5371 if (tmp_interval3)
5372 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
5374 temp = SAFE_ALLOCA (len1_byte);
5375 start1_addr = BYTE_POS_ADDR (start1_byte);
5376 start2_addr = BYTE_POS_ADDR (start2_byte);
5377 memcpy (temp, start1_addr, len1_byte);
5378 memcpy (start1_addr, start2_addr, len2_byte);
5379 memcpy (start2_addr, temp, len1_byte);
5380 SAFE_FREE ();
5382 graft_intervals_into_buffer (tmp_interval1, start2,
5383 len1, current_buffer, 0);
5384 graft_intervals_into_buffer (tmp_interval2, start1,
5385 len2, current_buffer, 0);
5388 else if (len1_byte < len2_byte) /* Second region larger than first */
5389 /* Non-adjacent & unequal size, area between must also be shifted. */
5391 USE_SAFE_ALLOCA;
5393 modify_text (start1, end2);
5394 record_change (start1, (end2 - start1));
5395 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5396 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5397 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5399 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5400 if (tmp_interval3)
5401 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5403 /* holds region 2 */
5404 temp = SAFE_ALLOCA (len2_byte);
5405 start1_addr = BYTE_POS_ADDR (start1_byte);
5406 start2_addr = BYTE_POS_ADDR (start2_byte);
5407 memcpy (temp, start2_addr, len2_byte);
5408 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
5409 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5410 memcpy (start1_addr, temp, len2_byte);
5411 SAFE_FREE ();
5413 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5414 len1, current_buffer, 0);
5415 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5416 len_mid, current_buffer, 0);
5417 graft_intervals_into_buffer (tmp_interval2, start1,
5418 len2, current_buffer, 0);
5420 else
5421 /* Second region smaller than first. */
5423 USE_SAFE_ALLOCA;
5425 record_change (start1, (end2 - start1));
5426 modify_text (start1, end2);
5428 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5429 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5430 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5432 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5433 if (tmp_interval3)
5434 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5436 /* holds region 1 */
5437 temp = SAFE_ALLOCA (len1_byte);
5438 start1_addr = BYTE_POS_ADDR (start1_byte);
5439 start2_addr = BYTE_POS_ADDR (start2_byte);
5440 memcpy (temp, start1_addr, len1_byte);
5441 memcpy (start1_addr, start2_addr, len2_byte);
5442 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5443 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
5444 SAFE_FREE ();
5446 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5447 len1, current_buffer, 0);
5448 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5449 len_mid, current_buffer, 0);
5450 graft_intervals_into_buffer (tmp_interval2, start1,
5451 len2, current_buffer, 0);
5454 update_compositions (start1, start1 + len2, CHECK_BORDER);
5455 update_compositions (end2 - len1, end2, CHECK_BORDER);
5458 /* When doing multiple transpositions, it might be nice
5459 to optimize this. Perhaps the markers in any one buffer
5460 should be organized in some sorted data tree. */
5461 if (NILP (leave_markers))
5463 transpose_markers (start1, end1, start2, end2,
5464 start1_byte, start1_byte + len1_byte,
5465 start2_byte, start2_byte + len2_byte);
5466 fix_start_end_in_overlays (start1, end2);
5468 else
5470 /* The character positions of the markers remain intact, but we
5471 still need to update their byte positions, because the
5472 transposed regions might include multibyte sequences which
5473 make some original byte positions of the markers invalid. */
5474 adjust_markers_bytepos (start1, start1_byte, end2, end2_byte, 0);
5477 signal_after_change (start1, end2 - start1, end2 - start1);
5478 return Qnil;
5482 void
5483 syms_of_editfns (void)
5485 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
5486 DEFSYM (Qwall, "wall");
5488 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
5489 doc: /* Non-nil means text motion commands don't notice fields. */);
5490 Vinhibit_field_text_motion = Qnil;
5492 DEFVAR_LISP ("buffer-access-fontify-functions",
5493 Vbuffer_access_fontify_functions,
5494 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
5495 Each function is called with two arguments which specify the range
5496 of the buffer being accessed. */);
5497 Vbuffer_access_fontify_functions = Qnil;
5500 Lisp_Object obuf;
5501 obuf = Fcurrent_buffer ();
5502 /* Do this here, because init_buffer_once is too early--it won't work. */
5503 Fset_buffer (Vprin1_to_string_buffer);
5504 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5505 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions), Qnil);
5506 Fset_buffer (obuf);
5509 DEFVAR_LISP ("buffer-access-fontified-property",
5510 Vbuffer_access_fontified_property,
5511 doc: /* Property which (if non-nil) indicates text has been fontified.
5512 `buffer-substring' need not call the `buffer-access-fontify-functions'
5513 functions if all the text being accessed has this property. */);
5514 Vbuffer_access_fontified_property = Qnil;
5516 DEFVAR_LISP ("system-name", Vsystem_name,
5517 doc: /* The host name of the machine Emacs is running on. */);
5518 Vsystem_name = cached_system_name = Qnil;
5520 DEFVAR_LISP ("user-full-name", Vuser_full_name,
5521 doc: /* The full name of the user logged in. */);
5523 DEFVAR_LISP ("user-login-name", Vuser_login_name,
5524 doc: /* The user's name, taken from environment variables if possible. */);
5525 Vuser_login_name = Qnil;
5527 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
5528 doc: /* The user's name, based upon the real uid only. */);
5530 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
5531 doc: /* The release of the operating system Emacs is running on. */);
5533 defsubr (&Spropertize);
5534 defsubr (&Schar_equal);
5535 defsubr (&Sgoto_char);
5536 defsubr (&Sstring_to_char);
5537 defsubr (&Schar_to_string);
5538 defsubr (&Sbyte_to_string);
5539 defsubr (&Sbuffer_substring);
5540 defsubr (&Sbuffer_substring_no_properties);
5541 defsubr (&Sbuffer_string);
5542 defsubr (&Sget_pos_property);
5544 defsubr (&Spoint_marker);
5545 defsubr (&Smark_marker);
5546 defsubr (&Spoint);
5547 defsubr (&Sregion_beginning);
5548 defsubr (&Sregion_end);
5550 /* Symbol for the text property used to mark fields. */
5551 DEFSYM (Qfield, "field");
5553 /* A special value for Qfield properties. */
5554 DEFSYM (Qboundary, "boundary");
5556 defsubr (&Sfield_beginning);
5557 defsubr (&Sfield_end);
5558 defsubr (&Sfield_string);
5559 defsubr (&Sfield_string_no_properties);
5560 defsubr (&Sdelete_field);
5561 defsubr (&Sconstrain_to_field);
5563 defsubr (&Sline_beginning_position);
5564 defsubr (&Sline_end_position);
5566 defsubr (&Ssave_excursion);
5567 defsubr (&Ssave_current_buffer);
5569 defsubr (&Sbuffer_size);
5570 defsubr (&Spoint_max);
5571 defsubr (&Spoint_min);
5572 defsubr (&Spoint_min_marker);
5573 defsubr (&Spoint_max_marker);
5574 defsubr (&Sgap_position);
5575 defsubr (&Sgap_size);
5576 defsubr (&Sposition_bytes);
5577 defsubr (&Sbyte_to_position);
5579 defsubr (&Sbobp);
5580 defsubr (&Seobp);
5581 defsubr (&Sbolp);
5582 defsubr (&Seolp);
5583 defsubr (&Sfollowing_char);
5584 defsubr (&Sprevious_char);
5585 defsubr (&Schar_after);
5586 defsubr (&Schar_before);
5587 defsubr (&Sinsert);
5588 defsubr (&Sinsert_before_markers);
5589 defsubr (&Sinsert_and_inherit);
5590 defsubr (&Sinsert_and_inherit_before_markers);
5591 defsubr (&Sinsert_char);
5592 defsubr (&Sinsert_byte);
5594 defsubr (&Suser_login_name);
5595 defsubr (&Suser_real_login_name);
5596 defsubr (&Suser_uid);
5597 defsubr (&Suser_real_uid);
5598 defsubr (&Sgroup_gid);
5599 defsubr (&Sgroup_real_gid);
5600 defsubr (&Suser_full_name);
5601 defsubr (&Semacs_pid);
5602 defsubr (&Scurrent_time);
5603 defsubr (&Stime_add);
5604 defsubr (&Stime_subtract);
5605 defsubr (&Stime_less_p);
5606 defsubr (&Sget_internal_run_time);
5607 defsubr (&Sformat_time_string);
5608 defsubr (&Sfloat_time);
5609 defsubr (&Sdecode_time);
5610 defsubr (&Sencode_time);
5611 defsubr (&Scurrent_time_string);
5612 defsubr (&Scurrent_time_zone);
5613 defsubr (&Sset_time_zone_rule);
5614 defsubr (&Ssystem_name);
5615 defsubr (&Smessage);
5616 defsubr (&Smessage_box);
5617 defsubr (&Smessage_or_box);
5618 defsubr (&Scurrent_message);
5619 defsubr (&Sformat);
5620 defsubr (&Sformat_message);
5622 defsubr (&Sinsert_buffer_substring);
5623 defsubr (&Scompare_buffer_substrings);
5624 defsubr (&Sreplace_buffer_contents);
5625 defsubr (&Ssubst_char_in_region);
5626 defsubr (&Stranslate_region_internal);
5627 defsubr (&Sdelete_region);
5628 defsubr (&Sdelete_and_extract_region);
5629 defsubr (&Swiden);
5630 defsubr (&Snarrow_to_region);
5631 defsubr (&Ssave_restriction);
5632 defsubr (&Stranspose_regions);