; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / src / editfns.c
blob30d585cd01897a24ecd7be813805a1134a4ee380
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 #ifdef HAVE_TIMEZONE_T
52 # include <sys/param.h>
53 # if defined __NetBSD_Version__ && __NetBSD_Version__ < 700000000
54 # define HAVE_TZALLOC_BUG true
55 # endif
56 #endif
57 #ifndef HAVE_TZALLOC_BUG
58 # define HAVE_TZALLOC_BUG false
59 #endif
61 #include <c-ctype.h>
62 #include <intprops.h>
63 #include <stdlib.h>
64 #include <strftime.h>
65 #include <verify.h>
67 #include "composite.h"
68 #include "intervals.h"
69 #include "ptr-bounds.h"
70 #include "character.h"
71 #include "buffer.h"
72 #include "coding.h"
73 #include "window.h"
74 #include "blockinput.h"
76 #define TM_YEAR_BASE 1900
78 #ifdef WINDOWSNT
79 extern Lisp_Object w32_get_internal_run_time (void);
80 #endif
82 static struct lisp_time lisp_time_struct (Lisp_Object, int *);
83 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
84 Lisp_Object, struct tm *);
85 static long int tm_gmtoff (struct tm *);
86 static int tm_diff (struct tm *, struct tm *);
87 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
88 static Lisp_Object styled_format (ptrdiff_t, Lisp_Object *, bool);
90 #ifndef HAVE_TM_GMTOFF
91 # define HAVE_TM_GMTOFF false
92 #endif
94 enum { tzeqlen = sizeof "TZ=" - 1 };
96 /* Time zones equivalent to current local time and to UTC, respectively. */
97 static timezone_t local_tz;
98 static timezone_t const utc_tz = 0;
100 /* The cached value of Vsystem_name. This is used only to compare it
101 to Vsystem_name, so it need not be visible to the GC. */
102 static Lisp_Object cached_system_name;
104 static void
105 init_and_cache_system_name (void)
107 init_system_name ();
108 cached_system_name = Vsystem_name;
111 static struct tm *
112 emacs_localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
114 tm = localtime_rz (tz, t, tm);
115 if (!tm && errno == ENOMEM)
116 memory_full (SIZE_MAX);
117 return tm;
120 static time_t
121 emacs_mktime_z (timezone_t tz, struct tm *tm)
123 errno = 0;
124 time_t t = mktime_z (tz, tm);
125 if (t == (time_t) -1 && errno == ENOMEM)
126 memory_full (SIZE_MAX);
127 return t;
130 static _Noreturn void
131 invalid_time_zone_specification (Lisp_Object zone)
133 xsignal2 (Qerror, build_string ("Invalid time zone specification"), zone);
136 /* Free a timezone, except do not free the time zone for local time.
137 Freeing utc_tz is also a no-op. */
138 static void
139 xtzfree (timezone_t tz)
141 if (tz != local_tz)
142 tzfree (tz);
145 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
146 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
147 If SETTZ, set Emacs local time to the time zone rule; otherwise,
148 the caller should eventually pass the returned value to xtzfree. */
149 static timezone_t
150 tzlookup (Lisp_Object zone, bool settz)
152 static char const tzbuf_format[] = "<%+.*"pI"d>%s%"pI"d:%02d:%02d";
153 char const *trailing_tzbuf_format = tzbuf_format + sizeof "<%+.*"pI"d" - 1;
154 char tzbuf[sizeof tzbuf_format + 2 * INT_STRLEN_BOUND (EMACS_INT)];
155 char const *zone_string;
156 timezone_t new_tz;
158 if (NILP (zone))
159 return local_tz;
160 else if (EQ (zone, Qt) || EQ (zone, make_number (0)))
162 zone_string = "UTC0";
163 new_tz = utc_tz;
165 else
167 bool plain_integer = INTEGERP (zone);
169 if (EQ (zone, Qwall))
170 zone_string = 0;
171 else if (STRINGP (zone))
172 zone_string = SSDATA (ENCODE_SYSTEM (zone));
173 else if (plain_integer || (CONSP (zone) && INTEGERP (XCAR (zone))
174 && CONSP (XCDR (zone))))
176 Lisp_Object abbr;
177 if (!plain_integer)
179 abbr = XCAR (XCDR (zone));
180 zone = XCAR (zone);
183 EMACS_INT abszone = eabs (XINT (zone)), hour = abszone / (60 * 60);
184 int hour_remainder = abszone % (60 * 60);
185 int min = hour_remainder / 60, sec = hour_remainder % 60;
187 if (plain_integer)
189 int prec = 2;
190 EMACS_INT numzone = hour;
191 if (hour_remainder != 0)
193 prec += 2, numzone = 100 * numzone + min;
194 if (sec != 0)
195 prec += 2, numzone = 100 * numzone + sec;
197 sprintf (tzbuf, tzbuf_format, prec,
198 XINT (zone) < 0 ? -numzone : numzone,
199 &"-"[XINT (zone) < 0], hour, min, sec);
200 zone_string = tzbuf;
202 else
204 AUTO_STRING (leading, "<");
205 AUTO_STRING_WITH_LEN (trailing, tzbuf,
206 sprintf (tzbuf, trailing_tzbuf_format,
207 &"-"[XINT (zone) < 0],
208 hour, min, sec));
209 zone_string = SSDATA (concat3 (leading, ENCODE_SYSTEM (abbr),
210 trailing));
213 else
214 invalid_time_zone_specification (zone);
216 new_tz = tzalloc (zone_string);
218 if (HAVE_TZALLOC_BUG && !new_tz && errno != ENOMEM && plain_integer
219 && XINT (zone) % (60 * 60) == 0)
221 /* tzalloc mishandles POSIX strings; fall back on tzdb if
222 possible (Bug#30738). */
223 sprintf (tzbuf, "Etc/GMT%+"pI"d", - (XINT (zone) / (60 * 60)));
224 new_tz = tzalloc (zone_string);
227 if (!new_tz)
229 if (errno == ENOMEM)
230 memory_full (SIZE_MAX);
231 invalid_time_zone_specification (zone);
235 if (settz)
237 block_input ();
238 emacs_setenv_TZ (zone_string);
239 tzset ();
240 timezone_t old_tz = local_tz;
241 local_tz = new_tz;
242 tzfree (old_tz);
243 unblock_input ();
246 return new_tz;
249 void
250 init_editfns (bool dumping)
252 #if !defined CANNOT_DUMP
253 /* A valid but unlikely setting for the TZ environment variable.
254 It is OK (though a bit slower) if the user chooses this value. */
255 static char dump_tz_string[] = "TZ=UtC0";
256 #endif
258 const char *user_name;
259 register char *p;
260 struct passwd *pw; /* password entry for the current user */
261 Lisp_Object tem;
263 /* Set up system_name even when dumping. */
264 init_and_cache_system_name ();
266 #ifndef CANNOT_DUMP
267 /* When just dumping out, set the time zone to a known unlikely value
268 and skip the rest of this function. */
269 if (dumping)
271 xputenv (dump_tz_string);
272 tzset ();
273 return;
275 #endif
277 char *tz = getenv ("TZ");
279 #if !defined CANNOT_DUMP
280 /* If the execution TZ happens to be the same as the dump TZ,
281 change it to some other value and then change it back,
282 to force the underlying implementation to reload the TZ info.
283 This is needed on implementations that load TZ info from files,
284 since the TZ file contents may differ between dump and execution. */
285 if (tz && strcmp (tz, &dump_tz_string[tzeqlen]) == 0)
287 ++*tz;
288 tzset ();
289 --*tz;
291 #endif
293 /* Set the time zone rule now, so that the call to putenv is done
294 before multiple threads are active. */
295 tzlookup (tz ? build_string (tz) : Qwall, true);
297 pw = getpwuid (getuid ());
298 #ifdef MSDOS
299 /* We let the real user name default to "root" because that's quite
300 accurate on MS-DOS and because it lets Emacs find the init file.
301 (The DVX libraries override the Djgpp libraries here.) */
302 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
303 #else
304 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
305 #endif
307 /* Get the effective user name, by consulting environment variables,
308 or the effective uid if those are unset. */
309 user_name = getenv ("LOGNAME");
310 if (!user_name)
311 #ifdef WINDOWSNT
312 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
313 #else /* WINDOWSNT */
314 user_name = getenv ("USER");
315 #endif /* WINDOWSNT */
316 if (!user_name)
318 pw = getpwuid (geteuid ());
319 user_name = pw ? pw->pw_name : "unknown";
321 Vuser_login_name = build_string (user_name);
323 /* If the user name claimed in the environment vars differs from
324 the real uid, use the claimed name to find the full name. */
325 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
326 if (! NILP (tem))
327 tem = Vuser_login_name;
328 else
330 uid_t euid = geteuid ();
331 tem = make_fixnum_or_float (euid);
333 Vuser_full_name = Fuser_full_name (tem);
335 p = getenv ("NAME");
336 if (p)
337 Vuser_full_name = build_string (p);
338 else if (NILP (Vuser_full_name))
339 Vuser_full_name = build_string ("unknown");
341 #ifdef HAVE_SYS_UTSNAME_H
343 struct utsname uts;
344 uname (&uts);
345 Voperating_system_release = build_string (uts.release);
347 #else
348 Voperating_system_release = Qnil;
349 #endif
352 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
353 doc: /* Convert arg CHAR to a string containing that character.
354 usage: (char-to-string CHAR) */)
355 (Lisp_Object character)
357 int c, len;
358 unsigned char str[MAX_MULTIBYTE_LENGTH];
360 CHECK_CHARACTER (character);
361 c = XFASTINT (character);
363 len = CHAR_STRING (c, str);
364 return make_string_from_bytes ((char *) str, 1, len);
367 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
368 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
369 (Lisp_Object byte)
371 unsigned char b;
372 CHECK_NUMBER (byte);
373 if (XINT (byte) < 0 || XINT (byte) > 255)
374 error ("Invalid byte");
375 b = XINT (byte);
376 return make_string_from_bytes ((char *) &b, 1, 1);
379 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
380 doc: /* Return the first character in STRING. */)
381 (register Lisp_Object string)
383 register Lisp_Object val;
384 CHECK_STRING (string);
385 if (SCHARS (string))
387 if (STRING_MULTIBYTE (string))
388 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
389 else
390 XSETFASTINT (val, SREF (string, 0));
392 else
393 XSETFASTINT (val, 0);
394 return val;
397 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
398 doc: /* Return value of point, as an integer.
399 Beginning of buffer is position (point-min). */)
400 (void)
402 Lisp_Object temp;
403 XSETFASTINT (temp, PT);
404 return temp;
407 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
408 doc: /* Return value of point, as a marker object. */)
409 (void)
411 return build_marker (current_buffer, PT, PT_BYTE);
414 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
415 doc: /* Set point to POSITION, a number or marker.
416 Beginning of buffer is position (point-min), end is (point-max).
418 The return value is POSITION. */)
419 (register Lisp_Object position)
421 if (MARKERP (position))
422 set_point_from_marker (position);
423 else if (INTEGERP (position))
424 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
425 else
426 wrong_type_argument (Qinteger_or_marker_p, position);
427 return position;
431 /* Return the start or end position of the region.
432 BEGINNINGP means return the start.
433 If there is no region active, signal an error. */
435 static Lisp_Object
436 region_limit (bool beginningp)
438 Lisp_Object m;
440 if (!NILP (Vtransient_mark_mode)
441 && NILP (Vmark_even_if_inactive)
442 && NILP (BVAR (current_buffer, mark_active)))
443 xsignal0 (Qmark_inactive);
445 m = Fmarker_position (BVAR (current_buffer, mark));
446 if (NILP (m))
447 error ("The mark is not set now, so there is no region");
449 /* Clip to the current narrowing (bug#11770). */
450 return make_number ((PT < XFASTINT (m)) == beginningp
451 ? PT
452 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
455 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
456 doc: /* Return the integer value of point or mark, whichever is smaller. */)
457 (void)
459 return region_limit (1);
462 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
463 doc: /* Return the integer value of point or mark, whichever is larger. */)
464 (void)
466 return region_limit (0);
469 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
470 doc: /* Return this buffer's mark, as a marker object.
471 Watch out! Moving this marker changes the mark position.
472 If you set the marker not to point anywhere, the buffer will have no mark. */)
473 (void)
475 return BVAR (current_buffer, mark);
479 /* Find all the overlays in the current buffer that touch position POS.
480 Return the number found, and store them in a vector in VEC
481 of length LEN. */
483 static ptrdiff_t
484 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
486 Lisp_Object overlay, start, end;
487 struct Lisp_Overlay *tail;
488 ptrdiff_t startpos, endpos;
489 ptrdiff_t idx = 0;
491 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
493 XSETMISC (overlay, tail);
495 end = OVERLAY_END (overlay);
496 endpos = OVERLAY_POSITION (end);
497 if (endpos < pos)
498 break;
499 start = OVERLAY_START (overlay);
500 startpos = OVERLAY_POSITION (start);
501 if (startpos <= pos)
503 if (idx < len)
504 vec[idx] = overlay;
505 /* Keep counting overlays even if we can't return them all. */
506 idx++;
510 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
512 XSETMISC (overlay, tail);
514 start = OVERLAY_START (overlay);
515 startpos = OVERLAY_POSITION (start);
516 if (pos < startpos)
517 break;
518 end = OVERLAY_END (overlay);
519 endpos = OVERLAY_POSITION (end);
520 if (pos <= endpos)
522 if (idx < len)
523 vec[idx] = overlay;
524 idx++;
528 return idx;
531 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
532 doc: /* Return the value of POSITION's property PROP, in OBJECT.
533 Almost identical to `get-char-property' except for the following difference:
534 Whereas `get-char-property' returns the property of the char at (i.e. right
535 after) POSITION, this pays attention to properties's stickiness and overlays's
536 advancement settings, in order to find the property of POSITION itself,
537 i.e. the property that a char would inherit if it were inserted
538 at POSITION. */)
539 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
541 CHECK_NUMBER_COERCE_MARKER (position);
543 if (NILP (object))
544 XSETBUFFER (object, current_buffer);
545 else if (WINDOWP (object))
546 object = XWINDOW (object)->contents;
548 if (!BUFFERP (object))
549 /* pos-property only makes sense in buffers right now, since strings
550 have no overlays and no notion of insertion for which stickiness
551 could be obeyed. */
552 return Fget_text_property (position, prop, object);
553 else
555 EMACS_INT posn = XINT (position);
556 ptrdiff_t noverlays;
557 Lisp_Object *overlay_vec, tem;
558 struct buffer *obuf = current_buffer;
559 USE_SAFE_ALLOCA;
561 set_buffer_temp (XBUFFER (object));
563 /* First try with room for 40 overlays. */
564 Lisp_Object overlay_vecbuf[40];
565 noverlays = ARRAYELTS (overlay_vecbuf);
566 overlay_vec = overlay_vecbuf;
567 noverlays = overlays_around (posn, overlay_vec, noverlays);
569 /* If there are more than 40,
570 make enough space for all, and try again. */
571 if (ARRAYELTS (overlay_vecbuf) < noverlays)
573 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
574 noverlays = overlays_around (posn, overlay_vec, noverlays);
576 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
578 set_buffer_temp (obuf);
580 /* Now check the overlays in order of decreasing priority. */
581 while (--noverlays >= 0)
583 Lisp_Object ol = overlay_vec[noverlays];
584 tem = Foverlay_get (ol, prop);
585 if (!NILP (tem))
587 /* Check the overlay is indeed active at point. */
588 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
589 if ((OVERLAY_POSITION (start) == posn
590 && XMARKER (start)->insertion_type == 1)
591 || (OVERLAY_POSITION (finish) == posn
592 && XMARKER (finish)->insertion_type == 0))
593 ; /* The overlay will not cover a char inserted at point. */
594 else
596 SAFE_FREE ();
597 return tem;
601 SAFE_FREE ();
603 { /* Now check the text properties. */
604 int stickiness = text_property_stickiness (prop, position, object);
605 if (stickiness > 0)
606 return Fget_text_property (position, prop, object);
607 else if (stickiness < 0
608 && XINT (position) > BUF_BEGV (XBUFFER (object)))
609 return Fget_text_property (make_number (XINT (position) - 1),
610 prop, object);
611 else
612 return Qnil;
617 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
618 the value of point is used instead. If BEG or END is null,
619 means don't store the beginning or end of the field.
621 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
622 results; they do not effect boundary behavior.
624 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
625 position of a field, then the beginning of the previous field is
626 returned instead of the beginning of POS's field (since the end of a
627 field is actually also the beginning of the next input field, this
628 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
629 non-nil case, if two fields are separated by a field with the special
630 value `boundary', and POS lies within it, then the two separated
631 fields are considered to be adjacent, and POS between them, when
632 finding the beginning and ending of the "merged" field.
634 Either BEG or END may be 0, in which case the corresponding value
635 is not stored. */
637 static void
638 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
639 Lisp_Object beg_limit,
640 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
642 /* Fields right before and after the point. */
643 Lisp_Object before_field, after_field;
644 /* True if POS counts as the start of a field. */
645 bool at_field_start = 0;
646 /* True if POS counts as the end of a field. */
647 bool at_field_end = 0;
649 if (NILP (pos))
650 XSETFASTINT (pos, PT);
651 else
652 CHECK_NUMBER_COERCE_MARKER (pos);
654 after_field
655 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
656 before_field
657 = (XFASTINT (pos) > BEGV
658 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
659 Qfield, Qnil, NULL)
660 /* Using nil here would be a more obvious choice, but it would
661 fail when the buffer starts with a non-sticky field. */
662 : after_field);
664 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
665 and POS is at beginning of a field, which can also be interpreted
666 as the end of the previous field. Note that the case where if
667 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
668 more natural one; then we avoid treating the beginning of a field
669 specially. */
670 if (NILP (merge_at_boundary))
672 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
673 if (!EQ (field, after_field))
674 at_field_end = 1;
675 if (!EQ (field, before_field))
676 at_field_start = 1;
677 if (NILP (field) && at_field_start && at_field_end)
678 /* If an inserted char would have a nil field while the surrounding
679 text is non-nil, we're probably not looking at a
680 zero-length field, but instead at a non-nil field that's
681 not intended for editing (such as comint's prompts). */
682 at_field_end = at_field_start = 0;
685 /* Note about special `boundary' fields:
687 Consider the case where the point (`.') is between the fields `x' and `y':
689 xxxx.yyyy
691 In this situation, if merge_at_boundary is non-nil, consider the
692 `x' and `y' fields as forming one big merged field, and so the end
693 of the field is the end of `y'.
695 However, if `x' and `y' are separated by a special `boundary' field
696 (a field with a `field' char-property of 'boundary), then ignore
697 this special field when merging adjacent fields. Here's the same
698 situation, but with a `boundary' field between the `x' and `y' fields:
700 xxx.BBBByyyy
702 Here, if point is at the end of `x', the beginning of `y', or
703 anywhere in-between (within the `boundary' field), merge all
704 three fields and consider the beginning as being the beginning of
705 the `x' field, and the end as being the end of the `y' field. */
707 if (beg)
709 if (at_field_start)
710 /* POS is at the edge of a field, and we should consider it as
711 the beginning of the following field. */
712 *beg = XFASTINT (pos);
713 else
714 /* Find the previous field boundary. */
716 Lisp_Object p = pos;
717 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
718 /* Skip a `boundary' field. */
719 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
720 beg_limit);
722 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
723 beg_limit);
724 *beg = NILP (p) ? BEGV : XFASTINT (p);
728 if (end)
730 if (at_field_end)
731 /* POS is at the edge of a field, and we should consider it as
732 the end of the previous field. */
733 *end = XFASTINT (pos);
734 else
735 /* Find the next field boundary. */
737 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
738 /* Skip a `boundary' field. */
739 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
740 end_limit);
742 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
743 end_limit);
744 *end = NILP (pos) ? ZV : XFASTINT (pos);
750 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
751 doc: /* Delete the field surrounding POS.
752 A field is a region of text with the same `field' property.
753 If POS is nil, the value of point is used for POS. */)
754 (Lisp_Object pos)
756 ptrdiff_t beg, end;
757 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
758 if (beg != end)
759 del_range (beg, end);
760 return Qnil;
763 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
764 doc: /* Return the contents of the field surrounding POS as a string.
765 A field is a region of text with the same `field' property.
766 If POS is nil, the value of point is used for POS. */)
767 (Lisp_Object pos)
769 ptrdiff_t beg, end;
770 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
771 return make_buffer_string (beg, end, 1);
774 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
775 doc: /* Return the contents of the field around POS, without text properties.
776 A field is a region of text with the same `field' property.
777 If POS is nil, the value of point is used for POS. */)
778 (Lisp_Object pos)
780 ptrdiff_t beg, end;
781 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
782 return make_buffer_string (beg, end, 0);
785 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
786 doc: /* Return the beginning of the field surrounding POS.
787 A field is a region of text with the same `field' property.
788 If POS is nil, the value of point is used for POS.
789 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
790 field, then the beginning of the *previous* field is returned.
791 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
792 is before LIMIT, then LIMIT will be returned instead. */)
793 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
795 ptrdiff_t beg;
796 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
797 return make_number (beg);
800 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
801 doc: /* Return the end of the field surrounding POS.
802 A field is a region of text with the same `field' property.
803 If POS is nil, the value of point is used for POS.
804 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
805 then the end of the *following* field is returned.
806 If LIMIT is non-nil, it is a buffer position; if the end of the field
807 is after LIMIT, then LIMIT will be returned instead. */)
808 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
810 ptrdiff_t end;
811 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
812 return make_number (end);
815 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
816 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
817 A field is a region of text with the same `field' property.
819 If NEW-POS is nil, then use the current point instead, and move point
820 to the resulting constrained position, in addition to returning that
821 position.
823 If OLD-POS is at the boundary of two fields, then the allowable
824 positions for NEW-POS depends on the value of the optional argument
825 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
826 constrained to the field that has the same `field' char-property
827 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
828 is non-nil, NEW-POS is constrained to the union of the two adjacent
829 fields. Additionally, if two fields are separated by another field with
830 the special value `boundary', then any point within this special field is
831 also considered to be `on the boundary'.
833 If the optional argument ONLY-IN-LINE is non-nil and constraining
834 NEW-POS would move it to a different line, NEW-POS is returned
835 unconstrained. This is useful for commands that move by line, like
836 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
837 only in the case where they can still move to the right line.
839 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
840 a non-nil property of that name, then any field boundaries are ignored.
842 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
843 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
844 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
846 /* If non-zero, then the original point, before re-positioning. */
847 ptrdiff_t orig_point = 0;
848 bool fwd;
849 Lisp_Object prev_old, prev_new;
851 if (NILP (new_pos))
852 /* Use the current point, and afterwards, set it. */
854 orig_point = PT;
855 XSETFASTINT (new_pos, PT);
858 CHECK_NUMBER_COERCE_MARKER (new_pos);
859 CHECK_NUMBER_COERCE_MARKER (old_pos);
861 fwd = (XINT (new_pos) > XINT (old_pos));
863 prev_old = make_number (XINT (old_pos) - 1);
864 prev_new = make_number (XINT (new_pos) - 1);
866 if (NILP (Vinhibit_field_text_motion)
867 && !EQ (new_pos, old_pos)
868 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
869 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
870 /* To recognize field boundaries, we must also look at the
871 previous positions; we could use `Fget_pos_property'
872 instead, but in itself that would fail inside non-sticky
873 fields (like comint prompts). */
874 || (XFASTINT (new_pos) > BEGV
875 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
876 || (XFASTINT (old_pos) > BEGV
877 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
878 && (NILP (inhibit_capture_property)
879 /* Field boundaries are again a problem; but now we must
880 decide the case exactly, so we need to call
881 `get_pos_property' as well. */
882 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
883 && (XFASTINT (old_pos) <= BEGV
884 || NILP (Fget_char_property
885 (old_pos, inhibit_capture_property, Qnil))
886 || NILP (Fget_char_property
887 (prev_old, inhibit_capture_property, Qnil))))))
888 /* It is possible that NEW_POS is not within the same field as
889 OLD_POS; try to move NEW_POS so that it is. */
891 ptrdiff_t shortage;
892 Lisp_Object field_bound;
894 if (fwd)
895 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
896 else
897 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
899 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
900 other side of NEW_POS, which would mean that NEW_POS is
901 already acceptable, and it's not necessary to constrain it
902 to FIELD_BOUND. */
903 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
904 /* NEW_POS should be constrained, but only if either
905 ONLY_IN_LINE is nil (in which case any constraint is OK),
906 or NEW_POS and FIELD_BOUND are on the same line (in which
907 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
908 && (NILP (only_in_line)
909 /* This is the ONLY_IN_LINE case, check that NEW_POS and
910 FIELD_BOUND are on the same line by seeing whether
911 there's an intervening newline or not. */
912 || (find_newline (XFASTINT (new_pos), -1,
913 XFASTINT (field_bound), -1,
914 fwd ? -1 : 1, &shortage, NULL, 1),
915 shortage != 0)))
916 /* Constrain NEW_POS to FIELD_BOUND. */
917 new_pos = field_bound;
919 if (orig_point && XFASTINT (new_pos) != orig_point)
920 /* The NEW_POS argument was originally nil, so automatically set PT. */
921 SET_PT (XFASTINT (new_pos));
924 return new_pos;
928 DEFUN ("line-beginning-position",
929 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
930 doc: /* Return the character position of the first character on the current line.
931 With optional argument N, scan forward N - 1 lines first.
932 If the scan reaches the end of the buffer, return that position.
934 This function ignores text display directionality; it returns the
935 position of the first character in logical order, i.e. the smallest
936 character position on the line.
938 This function constrains the returned position to the current field
939 unless that position would be on a different line than the original,
940 unconstrained result. If N is nil or 1, and a front-sticky field
941 starts at point, the scan stops as soon as it starts. To ignore field
942 boundaries, bind `inhibit-field-text-motion' to t.
944 This function does not move point. */)
945 (Lisp_Object n)
947 ptrdiff_t charpos, bytepos;
949 if (NILP (n))
950 XSETFASTINT (n, 1);
951 else
952 CHECK_NUMBER (n);
954 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
956 /* Return END constrained to the current input field. */
957 return Fconstrain_to_field (make_number (charpos), make_number (PT),
958 XINT (n) != 1 ? Qt : Qnil,
959 Qt, Qnil);
962 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
963 doc: /* Return the character position of the last character on the current line.
964 With argument N not nil or 1, move forward N - 1 lines first.
965 If scan reaches end of buffer, return that position.
967 This function ignores text display directionality; it returns the
968 position of the last character in logical order, i.e. the largest
969 character position on the line.
971 This function constrains the returned position to the current field
972 unless that would be on a different line than the original,
973 unconstrained result. If N is nil or 1, and a rear-sticky field ends
974 at point, the scan stops as soon as it starts. To ignore field
975 boundaries bind `inhibit-field-text-motion' to t.
977 This function does not move point. */)
978 (Lisp_Object n)
980 ptrdiff_t clipped_n;
981 ptrdiff_t end_pos;
982 ptrdiff_t orig = PT;
984 if (NILP (n))
985 XSETFASTINT (n, 1);
986 else
987 CHECK_NUMBER (n);
989 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
990 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
991 NULL);
993 /* Return END_POS constrained to the current input field. */
994 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
995 Qnil, Qt, Qnil);
998 /* Save current buffer state for save-excursion special form. */
1000 void
1001 save_excursion_save (union specbinding *pdl)
1003 eassert (pdl->unwind_excursion.kind == SPECPDL_UNWIND_EXCURSION);
1004 pdl->unwind_excursion.marker = Fpoint_marker ();
1005 /* Selected window if current buffer is shown in it, nil otherwise. */
1006 pdl->unwind_excursion.window
1007 = (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
1008 ? selected_window : Qnil);
1011 /* Restore saved buffer before leaving `save-excursion' special form. */
1013 void
1014 save_excursion_restore (Lisp_Object marker, Lisp_Object window)
1016 Lisp_Object buffer = Fmarker_buffer (marker);
1017 /* If we're unwinding to top level, saved buffer may be deleted. This
1018 means that all of its markers are unchained and so BUFFER is nil. */
1019 if (NILP (buffer))
1020 return;
1022 Fset_buffer (buffer);
1024 /* Point marker. */
1025 Fgoto_char (marker);
1026 unchain_marker (XMARKER (marker));
1028 /* If buffer was visible in a window, and a different window was
1029 selected, and the old selected window is still showing this
1030 buffer, restore point in that window. */
1031 if (WINDOWP (window) && !EQ (window, selected_window))
1033 /* Set window point if WINDOW is live and shows the current buffer. */
1034 Lisp_Object contents = XWINDOW (window)->contents;
1035 if (BUFFERP (contents) && XBUFFER (contents) == current_buffer)
1036 Fset_window_point (window, make_number (PT));
1040 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
1041 doc: /* Save point, and current buffer; execute BODY; restore those things.
1042 Executes BODY just like `progn'.
1043 The values of point and the current buffer are restored
1044 even in case of abnormal exit (throw or error).
1046 If you only want to save the current buffer but not point,
1047 then just use `save-current-buffer', or even `with-current-buffer'.
1049 Before Emacs 25.1, `save-excursion' used to save the mark state.
1050 To save the mark state as well as point and the current buffer, use
1051 `save-mark-and-excursion'.
1053 usage: (save-excursion &rest BODY) */)
1054 (Lisp_Object args)
1056 register Lisp_Object val;
1057 ptrdiff_t count = SPECPDL_INDEX ();
1059 record_unwind_protect_excursion ();
1061 val = Fprogn (args);
1062 return unbind_to (count, val);
1065 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1066 doc: /* Record which buffer is current; execute BODY; make that buffer current.
1067 BODY is executed just like `progn'.
1068 usage: (save-current-buffer &rest BODY) */)
1069 (Lisp_Object args)
1071 ptrdiff_t count = SPECPDL_INDEX ();
1073 record_unwind_current_buffer ();
1074 return unbind_to (count, Fprogn (args));
1077 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
1078 doc: /* Return the number of characters in the current buffer.
1079 If BUFFER is not nil, return the number of characters in that buffer
1080 instead.
1082 This does not take narrowing into account; to count the number of
1083 characters in the accessible portion of the current buffer, use
1084 `(- (point-max) (point-min))', and to count the number of characters
1085 in some other BUFFER, use
1086 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1087 (Lisp_Object buffer)
1089 if (NILP (buffer))
1090 return make_number (Z - BEG);
1091 else
1093 CHECK_BUFFER (buffer);
1094 return make_number (BUF_Z (XBUFFER (buffer))
1095 - BUF_BEG (XBUFFER (buffer)));
1099 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1100 doc: /* Return the minimum permissible value of point in the current buffer.
1101 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1102 (void)
1104 Lisp_Object temp;
1105 XSETFASTINT (temp, BEGV);
1106 return temp;
1109 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1110 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1111 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1112 (void)
1114 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1117 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1118 doc: /* Return the maximum permissible value of point in the current 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 Lisp_Object temp;
1124 XSETFASTINT (temp, ZV);
1125 return temp;
1128 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1129 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1130 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1131 is in effect, in which case it is less. */)
1132 (void)
1134 return build_marker (current_buffer, ZV, ZV_BYTE);
1137 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1138 doc: /* Return the position of the gap, in the current buffer.
1139 See also `gap-size'. */)
1140 (void)
1142 Lisp_Object temp;
1143 XSETFASTINT (temp, GPT);
1144 return temp;
1147 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1148 doc: /* Return the size of the current buffer's gap.
1149 See also `gap-position'. */)
1150 (void)
1152 Lisp_Object temp;
1153 XSETFASTINT (temp, GAP_SIZE);
1154 return temp;
1157 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1158 doc: /* Return the byte position for character position POSITION.
1159 If POSITION is out of range, the value is nil. */)
1160 (Lisp_Object position)
1162 CHECK_NUMBER_COERCE_MARKER (position);
1163 if (XINT (position) < BEG || XINT (position) > Z)
1164 return Qnil;
1165 return make_number (CHAR_TO_BYTE (XINT (position)));
1168 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1169 doc: /* Return the character position for byte position BYTEPOS.
1170 If BYTEPOS is out of range, the value is nil. */)
1171 (Lisp_Object bytepos)
1173 ptrdiff_t pos_byte;
1175 CHECK_NUMBER (bytepos);
1176 pos_byte = XINT (bytepos);
1177 if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
1178 return Qnil;
1179 if (Z != Z_BYTE)
1180 /* There are multibyte characters in the buffer.
1181 The argument of BYTE_TO_CHAR must be a byte position at
1182 a character boundary, so search for the start of the current
1183 character. */
1184 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte)))
1185 pos_byte--;
1186 return make_number (BYTE_TO_CHAR (pos_byte));
1189 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1190 doc: /* Return the character following point, as a number.
1191 At the end of the buffer or accessible region, return 0. */)
1192 (void)
1194 Lisp_Object temp;
1195 if (PT >= ZV)
1196 XSETFASTINT (temp, 0);
1197 else
1198 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1199 return temp;
1202 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1203 doc: /* Return the character preceding point, as a number.
1204 At the beginning of the buffer or accessible region, return 0. */)
1205 (void)
1207 Lisp_Object temp;
1208 if (PT <= BEGV)
1209 XSETFASTINT (temp, 0);
1210 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1212 ptrdiff_t pos = PT_BYTE;
1213 DEC_POS (pos);
1214 XSETFASTINT (temp, FETCH_CHAR (pos));
1216 else
1217 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1218 return temp;
1221 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1222 doc: /* Return t if point is at the beginning of the buffer.
1223 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1224 (void)
1226 if (PT == BEGV)
1227 return Qt;
1228 return Qnil;
1231 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1232 doc: /* Return t if point is at the end of the buffer.
1233 If the buffer is narrowed, this means the end of the narrowed part. */)
1234 (void)
1236 if (PT == ZV)
1237 return Qt;
1238 return Qnil;
1241 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1242 doc: /* Return t if point is at the beginning of a line. */)
1243 (void)
1245 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1246 return Qt;
1247 return Qnil;
1250 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1251 doc: /* Return t if point is at the end of a line.
1252 `End of a line' includes point being at the end of the buffer. */)
1253 (void)
1255 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1256 return Qt;
1257 return Qnil;
1260 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1261 doc: /* Return character in current buffer at position POS.
1262 POS is an integer or a marker and defaults to point.
1263 If POS is out of range, the value is nil. */)
1264 (Lisp_Object pos)
1266 register ptrdiff_t pos_byte;
1268 if (NILP (pos))
1270 pos_byte = PT_BYTE;
1271 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1272 return Qnil;
1274 else if (MARKERP (pos))
1276 pos_byte = marker_byte_position (pos);
1277 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1278 return Qnil;
1280 else
1282 CHECK_NUMBER_COERCE_MARKER (pos);
1283 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1284 return Qnil;
1286 pos_byte = CHAR_TO_BYTE (XINT (pos));
1289 return make_number (FETCH_CHAR (pos_byte));
1292 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1293 doc: /* Return character in current buffer preceding position POS.
1294 POS is an integer or a marker and defaults to point.
1295 If POS is out of range, the value is nil. */)
1296 (Lisp_Object pos)
1298 register Lisp_Object val;
1299 register ptrdiff_t pos_byte;
1301 if (NILP (pos))
1303 pos_byte = PT_BYTE;
1304 XSETFASTINT (pos, PT);
1307 if (MARKERP (pos))
1309 pos_byte = marker_byte_position (pos);
1311 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1312 return Qnil;
1314 else
1316 CHECK_NUMBER_COERCE_MARKER (pos);
1318 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1319 return Qnil;
1321 pos_byte = CHAR_TO_BYTE (XINT (pos));
1324 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1326 DEC_POS (pos_byte);
1327 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1329 else
1331 pos_byte--;
1332 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1334 return val;
1337 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1338 doc: /* Return the name under which the user logged in, as a string.
1339 This is based on the effective uid, not the real uid.
1340 Also, if the environment variables LOGNAME or USER are set,
1341 that determines the value of this function.
1343 If optional argument UID is an integer or a float, return the login name
1344 of the user with that uid, or nil if there is no such user. */)
1345 (Lisp_Object uid)
1347 struct passwd *pw;
1348 uid_t id;
1350 /* Set up the user name info if we didn't do it before.
1351 (That can happen if Emacs is dumpable
1352 but you decide to run `temacs -l loadup' and not dump. */
1353 if (NILP (Vuser_login_name))
1354 init_editfns (false);
1356 if (NILP (uid))
1357 return Vuser_login_name;
1359 CONS_TO_INTEGER (uid, uid_t, id);
1360 block_input ();
1361 pw = getpwuid (id);
1362 unblock_input ();
1363 return (pw ? build_string (pw->pw_name) : Qnil);
1366 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1367 0, 0, 0,
1368 doc: /* Return the name of the user's real uid, as a string.
1369 This ignores the environment variables LOGNAME and USER, so it differs from
1370 `user-login-name' when running under `su'. */)
1371 (void)
1373 /* Set up the user name info if we didn't do it before.
1374 (That can happen if Emacs is dumpable
1375 but you decide to run `temacs -l loadup' and not dump. */
1376 if (NILP (Vuser_login_name))
1377 init_editfns (false);
1378 return Vuser_real_login_name;
1381 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1382 doc: /* Return the effective uid of Emacs.
1383 Value is an integer or a float, depending on the value. */)
1384 (void)
1386 uid_t euid = geteuid ();
1387 return make_fixnum_or_float (euid);
1390 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1391 doc: /* Return the real uid of Emacs.
1392 Value is an integer or a float, depending on the value. */)
1393 (void)
1395 uid_t uid = getuid ();
1396 return make_fixnum_or_float (uid);
1399 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1400 doc: /* Return the effective gid of Emacs.
1401 Value is an integer or a float, depending on the value. */)
1402 (void)
1404 gid_t egid = getegid ();
1405 return make_fixnum_or_float (egid);
1408 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1409 doc: /* Return the real gid of Emacs.
1410 Value is an integer or a float, depending on the value. */)
1411 (void)
1413 gid_t gid = getgid ();
1414 return make_fixnum_or_float (gid);
1417 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1418 doc: /* Return the full name of the user logged in, as a string.
1419 If the full name corresponding to Emacs's userid is not known,
1420 return "unknown".
1422 If optional argument UID is an integer or float, return the full name
1423 of the user with that uid, or nil if there is no such user.
1424 If UID is a string, return the full name of the user with that login
1425 name, or nil if there is no such user. */)
1426 (Lisp_Object uid)
1428 struct passwd *pw;
1429 register char *p, *q;
1430 Lisp_Object full;
1432 if (NILP (uid))
1433 return Vuser_full_name;
1434 else if (NUMBERP (uid))
1436 uid_t u;
1437 CONS_TO_INTEGER (uid, uid_t, u);
1438 block_input ();
1439 pw = getpwuid (u);
1440 unblock_input ();
1442 else if (STRINGP (uid))
1444 block_input ();
1445 pw = getpwnam (SSDATA (uid));
1446 unblock_input ();
1448 else
1449 error ("Invalid UID specification");
1451 if (!pw)
1452 return Qnil;
1454 p = USER_FULL_NAME;
1455 /* Chop off everything after the first comma. */
1456 q = strchr (p, ',');
1457 full = make_string (p, q ? q - p : strlen (p));
1459 #ifdef AMPERSAND_FULL_NAME
1460 p = SSDATA (full);
1461 q = strchr (p, '&');
1462 /* Substitute the login name for the &, upcasing the first character. */
1463 if (q)
1465 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1466 USE_SAFE_ALLOCA;
1467 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1468 memcpy (r, p, q - p);
1469 char *s = lispstpcpy (&r[q - p], login);
1470 r[q - p] = upcase ((unsigned char) r[q - p]);
1471 strcpy (s, q + 1);
1472 full = build_string (r);
1473 SAFE_FREE ();
1475 #endif /* AMPERSAND_FULL_NAME */
1477 return full;
1480 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1481 doc: /* Return the host name of the machine you are running on, as a string. */)
1482 (void)
1484 if (EQ (Vsystem_name, cached_system_name))
1485 init_and_cache_system_name ();
1486 return Vsystem_name;
1489 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1490 doc: /* Return the process ID of Emacs, as a number. */)
1491 (void)
1493 pid_t pid = getpid ();
1494 return make_fixnum_or_float (pid);
1499 #ifndef TIME_T_MIN
1500 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1501 #endif
1502 #ifndef TIME_T_MAX
1503 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1504 #endif
1506 /* Report that a time value is out of range for Emacs. */
1507 void
1508 time_overflow (void)
1510 error ("Specified time is not representable");
1513 static _Noreturn void
1514 invalid_time (void)
1516 error ("Invalid time specification");
1519 /* Check a return value compatible with that of decode_time_components. */
1520 static void
1521 check_time_validity (int validity)
1523 if (validity <= 0)
1525 if (validity < 0)
1526 time_overflow ();
1527 else
1528 invalid_time ();
1532 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1533 static EMACS_INT
1534 hi_time (time_t t)
1536 time_t hi = t >> LO_TIME_BITS;
1537 if (FIXNUM_OVERFLOW_P (hi))
1538 time_overflow ();
1539 return hi;
1542 /* Return the bottom bits of the time T. */
1543 static int
1544 lo_time (time_t t)
1546 return t & ((1 << LO_TIME_BITS) - 1);
1549 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1550 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1551 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1552 HIGH has the most significant bits of the seconds, while LOW has the
1553 least significant 16 bits. USEC and PSEC are the microsecond and
1554 picosecond counts. */)
1555 (void)
1557 return make_lisp_time (current_timespec ());
1560 static struct lisp_time
1561 time_add (struct lisp_time ta, struct lisp_time tb)
1563 EMACS_INT hi = ta.hi + tb.hi;
1564 int lo = ta.lo + tb.lo;
1565 int us = ta.us + tb.us;
1566 int ps = ta.ps + tb.ps;
1567 us += (1000000 <= ps);
1568 ps -= (1000000 <= ps) * 1000000;
1569 lo += (1000000 <= us);
1570 us -= (1000000 <= us) * 1000000;
1571 hi += (1 << LO_TIME_BITS <= lo);
1572 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1573 return (struct lisp_time) { hi, lo, us, ps };
1576 static struct lisp_time
1577 time_subtract (struct lisp_time ta, struct lisp_time tb)
1579 EMACS_INT hi = ta.hi - tb.hi;
1580 int lo = ta.lo - tb.lo;
1581 int us = ta.us - tb.us;
1582 int ps = ta.ps - tb.ps;
1583 us -= (ps < 0);
1584 ps += (ps < 0) * 1000000;
1585 lo -= (us < 0);
1586 us += (us < 0) * 1000000;
1587 hi -= (lo < 0);
1588 lo += (lo < 0) << LO_TIME_BITS;
1589 return (struct lisp_time) { hi, lo, us, ps };
1592 static Lisp_Object
1593 time_arith (Lisp_Object a, Lisp_Object b,
1594 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1596 int alen, blen;
1597 struct lisp_time ta = lisp_time_struct (a, &alen);
1598 struct lisp_time tb = lisp_time_struct (b, &blen);
1599 struct lisp_time t = op (ta, tb);
1600 if (FIXNUM_OVERFLOW_P (t.hi))
1601 time_overflow ();
1602 Lisp_Object val = Qnil;
1604 switch (max (alen, blen))
1606 default:
1607 val = Fcons (make_number (t.ps), val);
1608 FALLTHROUGH;
1609 case 3:
1610 val = Fcons (make_number (t.us), val);
1611 FALLTHROUGH;
1612 case 2:
1613 val = Fcons (make_number (t.lo), val);
1614 val = Fcons (make_number (t.hi), val);
1615 break;
1618 return val;
1621 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1622 doc: /* Return the sum of two time values A and B, as a time value.
1623 A nil value for either argument stands for the current time.
1624 See `current-time-string' for the various forms of a time value. */)
1625 (Lisp_Object a, Lisp_Object b)
1627 return time_arith (a, b, time_add);
1630 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1631 doc: /* Return the difference between two time values A and B, as a time value.
1632 Use `float-time' to convert the difference into elapsed seconds.
1633 A nil value for either argument stands for the current time.
1634 See `current-time-string' for the various forms of a time value. */)
1635 (Lisp_Object a, Lisp_Object b)
1637 return time_arith (a, b, time_subtract);
1640 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1641 doc: /* Return non-nil if time value T1 is earlier than time value T2.
1642 A nil value for either argument stands for the current time.
1643 See `current-time-string' for the various forms of a time value. */)
1644 (Lisp_Object t1, Lisp_Object t2)
1646 int t1len, t2len;
1647 struct lisp_time a = lisp_time_struct (t1, &t1len);
1648 struct lisp_time b = lisp_time_struct (t2, &t2len);
1649 return ((a.hi != b.hi ? a.hi < b.hi
1650 : a.lo != b.lo ? a.lo < b.lo
1651 : a.us != b.us ? a.us < b.us
1652 : a.ps < b.ps)
1653 ? Qt : Qnil);
1657 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1658 0, 0, 0,
1659 doc: /* Return the current run time used by Emacs.
1660 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1661 style as (current-time).
1663 On systems that can't determine the run time, `get-internal-run-time'
1664 does the same thing as `current-time'. */)
1665 (void)
1667 #ifdef HAVE_GETRUSAGE
1668 struct rusage usage;
1669 time_t secs;
1670 int usecs;
1672 if (getrusage (RUSAGE_SELF, &usage) < 0)
1673 /* This shouldn't happen. What action is appropriate? */
1674 xsignal0 (Qerror);
1676 /* Sum up user time and system time. */
1677 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1678 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1679 if (usecs >= 1000000)
1681 usecs -= 1000000;
1682 secs++;
1684 return make_lisp_time (make_timespec (secs, usecs * 1000));
1685 #else /* ! HAVE_GETRUSAGE */
1686 #ifdef WINDOWSNT
1687 return w32_get_internal_run_time ();
1688 #else /* ! WINDOWSNT */
1689 return Fcurrent_time ();
1690 #endif /* WINDOWSNT */
1691 #endif /* HAVE_GETRUSAGE */
1695 /* Make a Lisp list that represents the Emacs time T. T may be an
1696 invalid time, with a slightly negative tv_nsec value such as
1697 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1698 correspondingly negative picosecond count. */
1699 Lisp_Object
1700 make_lisp_time (struct timespec t)
1702 time_t s = t.tv_sec;
1703 int ns = t.tv_nsec;
1704 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1707 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1708 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1709 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1710 if successful, 0 if unsuccessful. */
1711 static int
1712 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1713 Lisp_Object *plow, Lisp_Object *pusec,
1714 Lisp_Object *ppsec)
1716 Lisp_Object high = make_number (0);
1717 Lisp_Object low = specified_time;
1718 Lisp_Object usec = make_number (0);
1719 Lisp_Object psec = make_number (0);
1720 int len = 4;
1722 if (CONSP (specified_time))
1724 high = XCAR (specified_time);
1725 low = XCDR (specified_time);
1726 if (CONSP (low))
1728 Lisp_Object low_tail = XCDR (low);
1729 low = XCAR (low);
1730 if (CONSP (low_tail))
1732 usec = XCAR (low_tail);
1733 low_tail = XCDR (low_tail);
1734 if (CONSP (low_tail))
1735 psec = XCAR (low_tail);
1736 else
1737 len = 3;
1739 else if (!NILP (low_tail))
1741 usec = low_tail;
1742 len = 3;
1744 else
1745 len = 2;
1747 else
1748 len = 2;
1750 /* When combining components, require LOW to be an integer,
1751 as otherwise it would be a pain to add up times. */
1752 if (! INTEGERP (low))
1753 return 0;
1755 else if (INTEGERP (specified_time))
1756 len = 2;
1758 *phigh = high;
1759 *plow = low;
1760 *pusec = usec;
1761 *ppsec = psec;
1762 return len;
1765 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1766 Return true if T is in range, false otherwise. */
1767 static bool
1768 decode_float_time (double t, struct lisp_time *result)
1770 double lo_multiplier = 1 << LO_TIME_BITS;
1771 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1772 if (! (emacs_time_min <= t && t < -emacs_time_min))
1773 return false;
1775 double small_t = t / lo_multiplier;
1776 EMACS_INT hi = small_t;
1777 double t_sans_hi = t - hi * lo_multiplier;
1778 int lo = t_sans_hi;
1779 long double fracps = (t_sans_hi - lo) * 1e12L;
1780 #ifdef INT_FAST64_MAX
1781 int_fast64_t ifracps = fracps;
1782 int us = ifracps / 1000000;
1783 int ps = ifracps % 1000000;
1784 #else
1785 int us = fracps / 1e6L;
1786 int ps = fracps - us * 1e6L;
1787 #endif
1788 us -= (ps < 0);
1789 ps += (ps < 0) * 1000000;
1790 lo -= (us < 0);
1791 us += (us < 0) * 1000000;
1792 hi -= (lo < 0);
1793 lo += (lo < 0) << LO_TIME_BITS;
1794 result->hi = hi;
1795 result->lo = lo;
1796 result->us = us;
1797 result->ps = ps;
1798 return true;
1801 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1802 list, generate the corresponding time value.
1803 If LOW is floating point, the other components should be zero.
1805 If RESULT is not null, store into *RESULT the converted time.
1806 If *DRESULT is not null, store into *DRESULT the number of
1807 seconds since the start of the POSIX Epoch.
1809 Return 1 if successful, 0 if the components are of the
1810 wrong type, and -1 if the time is out of range. */
1812 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1813 Lisp_Object psec,
1814 struct lisp_time *result, double *dresult)
1816 EMACS_INT hi, lo, us, ps;
1817 if (! (INTEGERP (high)
1818 && INTEGERP (usec) && INTEGERP (psec)))
1819 return 0;
1820 if (! INTEGERP (low))
1822 if (FLOATP (low))
1824 double t = XFLOAT_DATA (low);
1825 if (result && ! decode_float_time (t, result))
1826 return -1;
1827 if (dresult)
1828 *dresult = t;
1829 return 1;
1831 else if (NILP (low))
1833 struct timespec now = current_timespec ();
1834 if (result)
1836 result->hi = hi_time (now.tv_sec);
1837 result->lo = lo_time (now.tv_sec);
1838 result->us = now.tv_nsec / 1000;
1839 result->ps = now.tv_nsec % 1000 * 1000;
1841 if (dresult)
1842 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1843 return 1;
1845 else
1846 return 0;
1849 hi = XINT (high);
1850 lo = XINT (low);
1851 us = XINT (usec);
1852 ps = XINT (psec);
1854 /* Normalize out-of-range lower-order components by carrying
1855 each overflow into the next higher-order component. */
1856 us += ps / 1000000 - (ps % 1000000 < 0);
1857 lo += us / 1000000 - (us % 1000000 < 0);
1858 hi += lo >> LO_TIME_BITS;
1859 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1860 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1861 lo &= (1 << LO_TIME_BITS) - 1;
1863 if (result)
1865 if (FIXNUM_OVERFLOW_P (hi))
1866 return -1;
1867 result->hi = hi;
1868 result->lo = lo;
1869 result->us = us;
1870 result->ps = ps;
1873 if (dresult)
1875 double dhi = hi;
1876 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1879 return 1;
1882 struct timespec
1883 lisp_to_timespec (struct lisp_time t)
1885 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1886 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1887 return invalid_timespec ();
1888 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1889 int ns = t.us * 1000 + t.ps / 1000;
1890 return make_timespec (s, ns);
1893 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1894 Store its effective length into *PLEN.
1895 If SPECIFIED_TIME is nil, use the current time.
1896 Signal an error if SPECIFIED_TIME does not represent a time. */
1897 static struct lisp_time
1898 lisp_time_struct (Lisp_Object specified_time, int *plen)
1900 Lisp_Object high, low, usec, psec;
1901 struct lisp_time t;
1902 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1903 if (!len)
1904 invalid_time ();
1905 int val = decode_time_components (high, low, usec, psec, &t, 0);
1906 check_time_validity (val);
1907 *plen = len;
1908 return t;
1911 /* Like lisp_time_struct, except return a struct timespec.
1912 Discard any low-order digits. */
1913 struct timespec
1914 lisp_time_argument (Lisp_Object specified_time)
1916 int len;
1917 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1918 struct timespec t = lisp_to_timespec (lt);
1919 if (! timespec_valid_p (t))
1920 time_overflow ();
1921 return t;
1924 /* Like lisp_time_argument, except decode only the seconds part,
1925 and do not check the subseconds part. */
1926 static time_t
1927 lisp_seconds_argument (Lisp_Object specified_time)
1929 Lisp_Object high, low, usec, psec;
1930 struct lisp_time t;
1932 int val = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1933 if (val != 0)
1935 val = decode_time_components (high, low, make_number (0),
1936 make_number (0), &t, 0);
1937 if (0 < val
1938 && ! ((TYPE_SIGNED (time_t)
1939 ? TIME_T_MIN >> LO_TIME_BITS <= t.hi
1940 : 0 <= t.hi)
1941 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1942 val = -1;
1944 check_time_validity (val);
1945 return (t.hi << LO_TIME_BITS) + t.lo;
1948 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1949 doc: /* Return the current time, as a float number of seconds since the epoch.
1950 If SPECIFIED-TIME is given, it is the time to convert to float
1951 instead of the current time. The argument should have the form
1952 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1953 you can use times from `current-time' and from `file-attributes'.
1954 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1955 considered obsolete.
1957 WARNING: Since the result is floating point, it may not be exact.
1958 If precise time stamps are required, use either `current-time',
1959 or (if you need time as a string) `format-time-string'. */)
1960 (Lisp_Object specified_time)
1962 double t;
1963 Lisp_Object high, low, usec, psec;
1964 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1965 && decode_time_components (high, low, usec, psec, 0, &t)))
1966 invalid_time ();
1967 return make_float (t);
1970 /* Write information into buffer S of size MAXSIZE, according to the
1971 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1972 Use the time zone specified by TZ.
1973 Use NS as the number of nanoseconds in the %N directive.
1974 Return the number of bytes written, not including the terminating
1975 '\0'. If S is NULL, nothing will be written anywhere; so to
1976 determine how many bytes would be written, use NULL for S and
1977 ((size_t) -1) for MAXSIZE.
1979 This function behaves like nstrftime, except it allows null
1980 bytes in FORMAT and it does not support nanoseconds. */
1981 static size_t
1982 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1983 size_t format_len, const struct tm *tp, timezone_t tz, int ns)
1985 size_t total = 0;
1987 /* Loop through all the null-terminated strings in the format
1988 argument. Normally there's just one null-terminated string, but
1989 there can be arbitrarily many, concatenated together, if the
1990 format contains '\0' bytes. nstrftime stops at the first
1991 '\0' byte so we must invoke it separately for each such string. */
1992 for (;;)
1994 size_t len;
1995 size_t result;
1997 if (s)
1998 s[0] = '\1';
2000 result = nstrftime (s, maxsize, format, tp, tz, ns);
2002 if (s)
2004 if (result == 0 && s[0] != '\0')
2005 return 0;
2006 s += result + 1;
2009 maxsize -= result + 1;
2010 total += result;
2011 len = strlen (format);
2012 if (len == format_len)
2013 return total;
2014 total++;
2015 format += len + 1;
2016 format_len -= len + 1;
2020 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
2021 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted or nil.
2022 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2023 `current-time' or `file-attributes'. It can also be a single integer
2024 number of seconds since the epoch. The obsolete form (HIGH . LOW) is
2025 also still accepted.
2027 The optional ZONE is omitted or nil for Emacs local time, t for
2028 Universal Time, `wall' for system wall clock time, or a string as in
2029 the TZ environment variable. It can also be a list (as from
2030 `current-time-zone') or an integer (as from `decode-time') applied
2031 without consideration for daylight saving time.
2033 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2034 by text that describes the specified date and time in TIME:
2036 %Y is the year, %y within the century, %C the century.
2037 %G is the year corresponding to the ISO week, %g within the century.
2038 %m is the numeric month.
2039 %b and %h are the locale's abbreviated month name, %B the full name.
2040 (%h is not supported on MS-Windows.)
2041 %d is the day of the month, zero-padded, %e is blank-padded.
2042 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2043 %a is the locale's abbreviated name of the day of week, %A the full name.
2044 %U is the week number starting on Sunday, %W starting on Monday,
2045 %V according to ISO 8601.
2046 %j is the day of the year.
2048 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2049 only blank-padded, %l is like %I blank-padded.
2050 %p is the locale's equivalent of either AM or PM.
2051 %q is the calendar quarter (1–4).
2052 %M is the minute (00-59).
2053 %S is the second (00-59; 00-60 on platforms with leap seconds)
2054 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2055 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2056 %Z is the time zone abbreviation, %z is the numeric form.
2058 %c is the locale's date and time format.
2059 %x is the locale's "preferred" date format.
2060 %D is like "%m/%d/%y".
2061 %F is the ISO 8601 date format (like "%Y-%m-%d").
2063 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2064 %X is the locale's "preferred" time format.
2066 Finally, %n is a newline, %t is a tab, %% is a literal %, and
2067 unrecognized %-sequences stand for themselves.
2069 Certain flags and modifiers are available with some format controls.
2070 The flags are `_', `-', `^' and `#'. For certain characters X,
2071 %_X is like %X, but padded with blanks; %-X is like %X,
2072 but without padding. %^X is like %X, but with all textual
2073 characters up-cased; %#X is like %X, but with letter-case of
2074 all textual characters reversed.
2075 %NX (where N stands for an integer) is like %X,
2076 but takes up at least N (a number) positions.
2077 The modifiers are `E' and `O'. For certain characters X,
2078 %EX is a locale's alternative version of %X;
2079 %OX is like %X, but uses the locale's number symbols.
2081 For example, to produce full ISO 8601 format, use "%FT%T%z".
2083 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2084 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object zone)
2086 struct timespec t = lisp_time_argument (timeval);
2087 struct tm tm;
2089 CHECK_STRING (format_string);
2090 format_string = code_convert_string_norecord (format_string,
2091 Vlocale_coding_system, 1);
2092 return format_time_string (SSDATA (format_string), SBYTES (format_string),
2093 t, zone, &tm);
2096 static Lisp_Object
2097 format_time_string (char const *format, ptrdiff_t formatlen,
2098 struct timespec t, Lisp_Object zone, struct tm *tmp)
2100 char buffer[4000];
2101 char *buf = buffer;
2102 ptrdiff_t size = sizeof buffer;
2103 size_t len;
2104 int ns = t.tv_nsec;
2105 USE_SAFE_ALLOCA;
2107 timezone_t tz = tzlookup (zone, false);
2108 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2109 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2110 expects a pointer to time_t value. */
2111 time_t tsec = t.tv_sec;
2112 tmp = emacs_localtime_rz (tz, &tsec, tmp);
2113 if (! tmp)
2115 xtzfree (tz);
2116 time_overflow ();
2118 synchronize_system_time_locale ();
2120 while (true)
2122 buf[0] = '\1';
2123 len = emacs_nmemftime (buf, size, format, formatlen, tmp, tz, ns);
2124 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
2125 break;
2127 /* Buffer was too small, so make it bigger and try again. */
2128 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, tz, ns);
2129 if (STRING_BYTES_BOUND <= len)
2131 xtzfree (tz);
2132 string_overflow ();
2134 size = len + 1;
2135 buf = SAFE_ALLOCA (size);
2138 xtzfree (tz);
2139 AUTO_STRING_WITH_LEN (bufstring, buf, len);
2140 Lisp_Object result = code_convert_string_norecord (bufstring,
2141 Vlocale_coding_system, 0);
2142 SAFE_FREE ();
2143 return result;
2146 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 2, 0,
2147 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2148 The optional TIME should be a list of (HIGH LOW . IGNORED),
2149 as from `current-time' and `file-attributes', or nil to use the
2150 current time. It can also be a single integer number of seconds since
2151 the epoch. The obsolete form (HIGH . LOW) is also still accepted.
2153 The optional ZONE is omitted or nil for Emacs local time, t for
2154 Universal Time, `wall' for system wall clock time, or a string as in
2155 the TZ environment variable. It can also be a list (as from
2156 `current-time-zone') or an integer (the UTC offset in seconds) applied
2157 without consideration for daylight saving time.
2159 The list has the following nine members: SEC is an integer between 0
2160 and 60; SEC is 60 for a leap second, which only some operating systems
2161 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2162 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2163 integer between 1 and 12. YEAR is an integer indicating the
2164 four-digit year. DOW is the day of week, an integer between 0 and 6,
2165 where 0 is Sunday. DST is t if daylight saving time is in effect,
2166 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2167 seconds, i.e., the number of seconds east of Greenwich. (Note that
2168 Common Lisp has different meanings for DOW and UTCOFF.)
2170 usage: (decode-time &optional TIME ZONE) */)
2171 (Lisp_Object specified_time, Lisp_Object zone)
2173 time_t time_spec = lisp_seconds_argument (specified_time);
2174 struct tm local_tm, gmt_tm;
2175 timezone_t tz = tzlookup (zone, false);
2176 struct tm *tm = emacs_localtime_rz (tz, &time_spec, &local_tm);
2177 xtzfree (tz);
2179 if (! (tm
2180 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2181 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2182 time_overflow ();
2184 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2185 EMACS_INT tm_year_base = TM_YEAR_BASE;
2187 return CALLN (Flist,
2188 make_number (local_tm.tm_sec),
2189 make_number (local_tm.tm_min),
2190 make_number (local_tm.tm_hour),
2191 make_number (local_tm.tm_mday),
2192 make_number (local_tm.tm_mon + 1),
2193 make_number (local_tm.tm_year + tm_year_base),
2194 make_number (local_tm.tm_wday),
2195 local_tm.tm_isdst ? Qt : Qnil,
2196 (HAVE_TM_GMTOFF
2197 ? make_number (tm_gmtoff (&local_tm))
2198 : gmtime_r (&time_spec, &gmt_tm)
2199 ? make_number (tm_diff (&local_tm, &gmt_tm))
2200 : Qnil));
2203 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2204 the result is representable as an int. */
2205 static int
2206 check_tm_member (Lisp_Object obj, int offset)
2208 CHECK_NUMBER (obj);
2209 EMACS_INT n = XINT (obj);
2210 int result;
2211 if (INT_SUBTRACT_WRAPV (n, offset, &result))
2212 time_overflow ();
2213 return result;
2216 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2217 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2218 This is the reverse operation of `decode-time', which see.
2220 The optional ZONE is omitted or nil for Emacs local time, t for
2221 Universal Time, `wall' for system wall clock time, or a string as in
2222 the TZ environment variable. It can also be a list (as from
2223 `current-time-zone') or an integer (as from `decode-time') applied
2224 without consideration for daylight saving time.
2226 You can pass more than 7 arguments; then the first six arguments
2227 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2228 The intervening arguments are ignored.
2229 This feature lets (apply \\='encode-time (decode-time ...)) work.
2231 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2232 for example, a DAY of 0 means the day preceding the given month.
2233 Year numbers less than 100 are treated just like other year numbers.
2234 If you want them to stand for years in this century, you must do that yourself.
2236 Years before 1970 are not guaranteed to work. On some systems,
2237 year values as low as 1901 do work.
2239 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2240 (ptrdiff_t nargs, Lisp_Object *args)
2242 time_t value;
2243 struct tm tm;
2244 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2246 tm.tm_sec = check_tm_member (args[0], 0);
2247 tm.tm_min = check_tm_member (args[1], 0);
2248 tm.tm_hour = check_tm_member (args[2], 0);
2249 tm.tm_mday = check_tm_member (args[3], 0);
2250 tm.tm_mon = check_tm_member (args[4], 1);
2251 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2252 tm.tm_isdst = -1;
2254 timezone_t tz = tzlookup (zone, false);
2255 value = emacs_mktime_z (tz, &tm);
2256 xtzfree (tz);
2258 if (value == (time_t) -1)
2259 time_overflow ();
2261 return list2i (hi_time (value), lo_time (value));
2264 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string,
2265 0, 2, 0,
2266 doc: /* Return the current local time, as a human-readable string.
2267 Programs can use this function to decode a time,
2268 since the number of columns in each field is fixed
2269 if the year is in the range 1000-9999.
2270 The format is `Sun Sep 16 01:03:52 1973'.
2271 However, see also the functions `decode-time' and `format-time-string'
2272 which provide a much more powerful and general facility.
2274 If SPECIFIED-TIME is given, it is a time to format instead of the
2275 current time. The argument should have the form (HIGH LOW . IGNORED).
2276 Thus, you can use times obtained from `current-time' and from
2277 `file-attributes'. SPECIFIED-TIME can also be a single integer number
2278 of seconds since the epoch. The obsolete form (HIGH . LOW) is also
2279 still accepted.
2281 The optional ZONE is omitted or nil for Emacs local time, t for
2282 Universal Time, `wall' for system wall clock time, or a string as in
2283 the TZ environment variable. It can also be a list (as from
2284 `current-time-zone') or an integer (as from `decode-time') applied
2285 without consideration for daylight saving time. */)
2286 (Lisp_Object specified_time, Lisp_Object zone)
2288 time_t value = lisp_seconds_argument (specified_time);
2289 timezone_t tz = tzlookup (zone, false);
2291 /* Convert to a string in ctime format, except without the trailing
2292 newline, and without the 4-digit year limit. Don't use asctime
2293 or ctime, as they might dump core if the year is outside the
2294 range -999 .. 9999. */
2295 struct tm tm;
2296 struct tm *tmp = emacs_localtime_rz (tz, &value, &tm);
2297 xtzfree (tz);
2298 if (! tmp)
2299 time_overflow ();
2301 static char const wday_name[][4] =
2302 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2303 static char const mon_name[][4] =
2304 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2305 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2306 printmax_t year_base = TM_YEAR_BASE;
2307 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2308 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2309 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2310 tm.tm_hour, tm.tm_min, tm.tm_sec,
2311 tm.tm_year + year_base);
2313 return make_unibyte_string (buf, len);
2316 /* Yield A - B, measured in seconds.
2317 This function is copied from the GNU C Library. */
2318 static int
2319 tm_diff (struct tm *a, struct tm *b)
2321 /* Compute intervening leap days correctly even if year is negative.
2322 Take care to avoid int overflow in leap day calculations,
2323 but it's OK to assume that A and B are close to each other. */
2324 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2325 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2326 int a100 = a4 / 25 - (a4 % 25 < 0);
2327 int b100 = b4 / 25 - (b4 % 25 < 0);
2328 int a400 = a100 >> 2;
2329 int b400 = b100 >> 2;
2330 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2331 int years = a->tm_year - b->tm_year;
2332 int days = (365 * years + intervening_leap_days
2333 + (a->tm_yday - b->tm_yday));
2334 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2335 + (a->tm_min - b->tm_min))
2336 + (a->tm_sec - b->tm_sec));
2339 /* Yield A's UTC offset, or an unspecified value if unknown. */
2340 static long int
2341 tm_gmtoff (struct tm *a)
2343 #if HAVE_TM_GMTOFF
2344 return a->tm_gmtoff;
2345 #else
2346 return 0;
2347 #endif
2350 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 2, 0,
2351 doc: /* Return the offset and name for the local time zone.
2352 This returns a list of the form (OFFSET NAME).
2353 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2354 A negative value means west of Greenwich.
2355 NAME is a string giving the name of the time zone.
2356 If SPECIFIED-TIME is given, the time zone offset is determined from it
2357 instead of using the current time. The argument should have the form
2358 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2359 `current-time' and from `file-attributes'. SPECIFIED-TIME can also be
2360 a single integer number of seconds since the epoch. The obsolete form
2361 (HIGH . LOW) is also still accepted.
2363 The optional ZONE is omitted or nil for Emacs local time, t for
2364 Universal Time, `wall' for system wall clock time, or a string as in
2365 the TZ environment variable. It can also be a list (as from
2366 `current-time-zone') or an integer (as from `decode-time') applied
2367 without consideration for daylight saving time.
2369 Some operating systems cannot provide all this information to Emacs;
2370 in this case, `current-time-zone' returns a list containing nil for
2371 the data it can't find. */)
2372 (Lisp_Object specified_time, Lisp_Object zone)
2374 struct timespec value;
2375 struct tm local_tm, gmt_tm;
2376 Lisp_Object zone_offset, zone_name;
2378 zone_offset = Qnil;
2379 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2380 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value,
2381 zone, &local_tm);
2383 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2384 timespec on some systems (MinGW) is a 64-bit field. */
2385 time_t tsec = value.tv_sec;
2386 if (HAVE_TM_GMTOFF || gmtime_r (&tsec, &gmt_tm))
2388 long int offset = (HAVE_TM_GMTOFF
2389 ? tm_gmtoff (&local_tm)
2390 : tm_diff (&local_tm, &gmt_tm));
2391 zone_offset = make_number (offset);
2392 if (SCHARS (zone_name) == 0)
2394 /* No local time zone name is available; use numeric zone instead. */
2395 long int hour = offset / 3600;
2396 int min_sec = offset % 3600;
2397 int amin_sec = min_sec < 0 ? - min_sec : min_sec;
2398 int min = amin_sec / 60;
2399 int sec = amin_sec % 60;
2400 int min_prec = min_sec ? 2 : 0;
2401 int sec_prec = sec ? 2 : 0;
2402 char buf[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2403 zone_name = make_formatted_string (buf, "%c%.2ld%.*d%.*d",
2404 (offset < 0 ? '-' : '+'),
2405 hour, min_prec, min, sec_prec, sec);
2409 return list2 (zone_offset, zone_name);
2412 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2413 doc: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2414 If TZ is nil or `wall', use system wall clock time; this differs from
2415 the usual Emacs convention where nil means current local time. If TZ
2416 is t, use Universal Time. If TZ is a list (as from
2417 `current-time-zone') or an integer (as from `decode-time'), use the
2418 specified time zone without consideration for daylight saving time.
2420 Instead of calling this function, you typically want something else.
2421 To temporarily use a different time zone rule for just one invocation
2422 of `decode-time', `encode-time', or `format-time-string', pass the
2423 function a ZONE argument. To change local time consistently
2424 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2425 environment of the Emacs process and the variable
2426 `process-environment', whereas `set-time-zone-rule' affects only the
2427 former. */)
2428 (Lisp_Object tz)
2430 tzlookup (NILP (tz) ? Qwall : tz, true);
2431 return Qnil;
2434 /* A buffer holding a string of the form "TZ=value", intended
2435 to be part of the environment. If TZ is supposed to be unset,
2436 the buffer string is "tZ=". */
2437 static char *tzvalbuf;
2439 /* Get the local time zone rule. */
2440 char *
2441 emacs_getenv_TZ (void)
2443 return tzvalbuf[0] == 'T' ? tzvalbuf + tzeqlen : 0;
2446 /* Set the local time zone rule to TZSTRING, which can be null to
2447 denote wall clock time. Do not record the setting in LOCAL_TZ.
2449 This function is not thread-safe, in theory because putenv is not,
2450 but mostly because of the static storage it updates. Other threads
2451 that invoke localtime etc. may be adversely affected while this
2452 function is executing. */
2455 emacs_setenv_TZ (const char *tzstring)
2457 static ptrdiff_t tzvalbufsize;
2458 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2459 char *tzval = tzvalbuf;
2460 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2462 if (new_tzvalbuf)
2464 /* Do not attempt to free the old tzvalbuf, since another thread
2465 may be using it. In practice, the first allocation is large
2466 enough and memory does not leak. */
2467 tzval = xpalloc (NULL, &tzvalbufsize,
2468 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2469 tzvalbuf = tzval;
2470 tzval[1] = 'Z';
2471 tzval[2] = '=';
2474 if (tzstring)
2476 /* Modify TZVAL in place. Although this is dicey in a
2477 multithreaded environment, we know of no portable alternative.
2478 Calling putenv or setenv could crash some other thread. */
2479 tzval[0] = 'T';
2480 strcpy (tzval + tzeqlen, tzstring);
2482 else
2484 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2485 Although this is also dicey, calling unsetenv here can crash Emacs.
2486 See Bug#8705. */
2487 tzval[0] = 't';
2488 tzval[tzeqlen] = 0;
2492 #ifndef WINDOWSNT
2493 /* Modifying *TZVAL merely requires calling tzset (which is the
2494 caller's responsibility). However, modifying TZVAL requires
2495 calling putenv; although this is not thread-safe, in practice this
2496 runs only on startup when there is only one thread. */
2497 bool need_putenv = new_tzvalbuf;
2498 #else
2499 /* MS-Windows 'putenv' copies the argument string into a block it
2500 allocates, so modifying *TZVAL will not change the environment.
2501 However, the other threads run by Emacs on MS-Windows never call
2502 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2503 dicey in-place modification technique doesn't exist there in the
2504 first place. */
2505 bool need_putenv = true;
2506 #endif
2507 if (need_putenv)
2508 xputenv (tzval);
2510 return 0;
2513 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2514 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2515 type of object is Lisp_String). INHERIT is passed to
2516 INSERT_FROM_STRING_FUNC as the last argument. */
2518 static void
2519 general_insert_function (void (*insert_func)
2520 (const char *, ptrdiff_t),
2521 void (*insert_from_string_func)
2522 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2523 ptrdiff_t, ptrdiff_t, bool),
2524 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2526 ptrdiff_t argnum;
2527 Lisp_Object val;
2529 for (argnum = 0; argnum < nargs; argnum++)
2531 val = args[argnum];
2532 if (CHARACTERP (val))
2534 int c = XFASTINT (val);
2535 unsigned char str[MAX_MULTIBYTE_LENGTH];
2536 int len;
2538 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2539 len = CHAR_STRING (c, str);
2540 else
2542 str[0] = CHAR_TO_BYTE8 (c);
2543 len = 1;
2545 (*insert_func) ((char *) str, len);
2547 else if (STRINGP (val))
2549 (*insert_from_string_func) (val, 0, 0,
2550 SCHARS (val),
2551 SBYTES (val),
2552 inherit);
2554 else
2555 wrong_type_argument (Qchar_or_string_p, val);
2559 void
2560 insert1 (Lisp_Object arg)
2562 Finsert (1, &arg);
2566 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2567 doc: /* Insert the arguments, either strings or characters, at point.
2568 Point and after-insertion markers move forward to end up
2569 after the inserted text.
2570 Any other markers at the point of insertion remain before the text.
2572 If the current buffer is multibyte, unibyte strings are converted
2573 to multibyte for insertion (see `string-make-multibyte').
2574 If the current buffer is unibyte, multibyte strings are converted
2575 to unibyte for insertion (see `string-make-unibyte').
2577 When operating on binary data, it may be necessary to preserve the
2578 original bytes of a unibyte string when inserting it into a multibyte
2579 buffer; to accomplish this, apply `string-as-multibyte' to the string
2580 and insert the result.
2582 usage: (insert &rest ARGS) */)
2583 (ptrdiff_t nargs, Lisp_Object *args)
2585 general_insert_function (insert, insert_from_string, 0, nargs, args);
2586 return Qnil;
2589 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2590 0, MANY, 0,
2591 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2592 Point and after-insertion markers move forward to end up
2593 after the inserted text.
2594 Any other markers at the point of insertion remain before the text.
2596 If the current buffer is multibyte, unibyte strings are converted
2597 to multibyte for insertion (see `unibyte-char-to-multibyte').
2598 If the current buffer is unibyte, multibyte strings are converted
2599 to unibyte for insertion.
2601 usage: (insert-and-inherit &rest ARGS) */)
2602 (ptrdiff_t nargs, Lisp_Object *args)
2604 general_insert_function (insert_and_inherit, insert_from_string, 1,
2605 nargs, args);
2606 return Qnil;
2609 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2610 doc: /* Insert strings or characters at point, relocating markers after the text.
2611 Point and markers move forward to end up after the inserted text.
2613 If the current buffer is multibyte, unibyte strings are converted
2614 to multibyte for insertion (see `unibyte-char-to-multibyte').
2615 If the current buffer is unibyte, multibyte strings are converted
2616 to unibyte for insertion.
2618 If an overlay begins at the insertion point, the inserted text falls
2619 outside the overlay; if a nonempty overlay ends at the insertion
2620 point, the inserted text falls inside that overlay.
2622 usage: (insert-before-markers &rest ARGS) */)
2623 (ptrdiff_t nargs, Lisp_Object *args)
2625 general_insert_function (insert_before_markers,
2626 insert_from_string_before_markers, 0,
2627 nargs, args);
2628 return Qnil;
2631 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2632 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2633 doc: /* Insert text at point, relocating markers and inheriting properties.
2634 Point and markers move forward to end up after the inserted text.
2636 If the current buffer is multibyte, unibyte strings are converted
2637 to multibyte for insertion (see `unibyte-char-to-multibyte').
2638 If the current buffer is unibyte, multibyte strings are converted
2639 to unibyte for insertion.
2641 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2642 (ptrdiff_t nargs, Lisp_Object *args)
2644 general_insert_function (insert_before_markers_and_inherit,
2645 insert_from_string_before_markers, 1,
2646 nargs, args);
2647 return Qnil;
2650 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2651 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2652 (prefix-numeric-value current-prefix-arg)\
2653 t))",
2654 doc: /* Insert COUNT copies of CHARACTER.
2655 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2656 of these ways:
2658 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2659 Completion is available; if you type a substring of the name
2660 preceded by an asterisk `*', Emacs shows all names which include
2661 that substring, not necessarily at the beginning of the name.
2663 - As a hexadecimal code point, e.g. 263A. Note that code points in
2664 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2665 the Unicode code space).
2667 - As a code point with a radix specified with #, e.g. #o21430
2668 (octal), #x2318 (hex), or #10r8984 (decimal).
2670 If called interactively, COUNT is given by the prefix argument. If
2671 omitted or nil, it defaults to 1.
2673 Inserting the character(s) relocates point and before-insertion
2674 markers in the same ways as the function `insert'.
2676 The optional third argument INHERIT, if non-nil, says to inherit text
2677 properties from adjoining text, if those properties are sticky. If
2678 called interactively, INHERIT is t. */)
2679 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2681 int i, stringlen;
2682 register ptrdiff_t n;
2683 int c, len;
2684 unsigned char str[MAX_MULTIBYTE_LENGTH];
2685 char string[4000];
2687 CHECK_CHARACTER (character);
2688 if (NILP (count))
2689 XSETFASTINT (count, 1);
2690 CHECK_NUMBER (count);
2691 c = XFASTINT (character);
2693 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2694 len = CHAR_STRING (c, str);
2695 else
2696 str[0] = c, len = 1;
2697 if (XINT (count) <= 0)
2698 return Qnil;
2699 if (BUF_BYTES_MAX / len < XINT (count))
2700 buffer_overflow ();
2701 n = XINT (count) * len;
2702 stringlen = min (n, sizeof string - sizeof string % len);
2703 for (i = 0; i < stringlen; i++)
2704 string[i] = str[i % len];
2705 while (n > stringlen)
2707 maybe_quit ();
2708 if (!NILP (inherit))
2709 insert_and_inherit (string, stringlen);
2710 else
2711 insert (string, stringlen);
2712 n -= stringlen;
2714 if (!NILP (inherit))
2715 insert_and_inherit (string, n);
2716 else
2717 insert (string, n);
2718 return Qnil;
2721 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2722 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2723 Both arguments are required.
2724 BYTE is a number of the range 0..255.
2726 If BYTE is 128..255 and the current buffer is multibyte, the
2727 corresponding eight-bit character is inserted.
2729 Point, and before-insertion markers, are relocated as in the function `insert'.
2730 The optional third arg INHERIT, if non-nil, says to inherit text properties
2731 from adjoining text, if those properties are sticky. */)
2732 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2734 CHECK_NUMBER (byte);
2735 if (XINT (byte) < 0 || XINT (byte) > 255)
2736 args_out_of_range_3 (byte, make_number (0), make_number (255));
2737 if (XINT (byte) >= 128
2738 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2739 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2740 return Finsert_char (byte, count, inherit);
2744 /* Making strings from buffer contents. */
2746 /* Return a Lisp_String containing the text of the current buffer from
2747 START to END. If text properties are in use and the current buffer
2748 has properties in the range specified, the resulting string will also
2749 have them, if PROPS is true.
2751 We don't want to use plain old make_string here, because it calls
2752 make_uninit_string, which can cause the buffer arena to be
2753 compacted. make_string has no way of knowing that the data has
2754 been moved, and thus copies the wrong data into the string. This
2755 doesn't effect most of the other users of make_string, so it should
2756 be left as is. But we should use this function when conjuring
2757 buffer substrings. */
2759 Lisp_Object
2760 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2762 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2763 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2765 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2768 /* Return a Lisp_String containing the text of the current buffer from
2769 START / START_BYTE to END / END_BYTE.
2771 If text properties are in use and the current buffer
2772 has properties in the range specified, the resulting string will also
2773 have them, if PROPS is true.
2775 We don't want to use plain old make_string here, because it calls
2776 make_uninit_string, which can cause the buffer arena to be
2777 compacted. make_string has no way of knowing that the data has
2778 been moved, and thus copies the wrong data into the string. This
2779 doesn't effect most of the other users of make_string, so it should
2780 be left as is. But we should use this function when conjuring
2781 buffer substrings. */
2783 Lisp_Object
2784 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2785 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2787 Lisp_Object result, tem, tem1;
2788 ptrdiff_t beg0, end0, beg1, end1, size;
2790 if (start_byte < GPT_BYTE && GPT_BYTE < end_byte)
2792 /* Two regions, before and after the gap. */
2793 beg0 = start_byte;
2794 end0 = GPT_BYTE;
2795 beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
2796 end1 = end_byte + GAP_SIZE - BEG_BYTE;
2798 else
2800 /* The only region. */
2801 beg0 = start_byte;
2802 end0 = end_byte;
2803 beg1 = -1;
2804 end1 = -1;
2807 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2808 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2809 else
2810 result = make_uninit_string (end - start);
2812 size = end0 - beg0;
2813 memcpy (SDATA (result), BYTE_POS_ADDR (beg0), size);
2814 if (beg1 != -1)
2815 memcpy (SDATA (result) + size, BEG_ADDR + beg1, end1 - beg1);
2817 /* If desired, update and copy the text properties. */
2818 if (props)
2820 update_buffer_properties (start, end);
2822 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2823 tem1 = Ftext_properties_at (make_number (start), Qnil);
2825 if (XINT (tem) != end || !NILP (tem1))
2826 copy_intervals_to_string (result, current_buffer, start,
2827 end - start);
2830 return result;
2833 /* Call Vbuffer_access_fontify_functions for the range START ... END
2834 in the current buffer, if necessary. */
2836 static void
2837 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2839 /* If this buffer has some access functions,
2840 call them, specifying the range of the buffer being accessed. */
2841 if (!NILP (Vbuffer_access_fontify_functions))
2843 /* But don't call them if we can tell that the work
2844 has already been done. */
2845 if (!NILP (Vbuffer_access_fontified_property))
2847 Lisp_Object tem
2848 = Ftext_property_any (make_number (start), make_number (end),
2849 Vbuffer_access_fontified_property,
2850 Qnil, Qnil);
2851 if (NILP (tem))
2852 return;
2855 CALLN (Frun_hook_with_args, Qbuffer_access_fontify_functions,
2856 make_number (start), make_number (end));
2860 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2861 doc: /* Return the contents of part of the current buffer as a string.
2862 The two arguments START and END are character positions;
2863 they can be in either order.
2864 The string returned is multibyte if the buffer is multibyte.
2866 This function copies the text properties of that part of the buffer
2867 into the result string; if you don't want the text properties,
2868 use `buffer-substring-no-properties' instead. */)
2869 (Lisp_Object start, Lisp_Object end)
2871 register ptrdiff_t b, e;
2873 validate_region (&start, &end);
2874 b = XINT (start);
2875 e = XINT (end);
2877 return make_buffer_string (b, e, 1);
2880 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2881 Sbuffer_substring_no_properties, 2, 2, 0,
2882 doc: /* Return the characters of part of the buffer, without the text properties.
2883 The two arguments START and END are character positions;
2884 they can be in either order. */)
2885 (Lisp_Object start, Lisp_Object end)
2887 register ptrdiff_t b, e;
2889 validate_region (&start, &end);
2890 b = XINT (start);
2891 e = XINT (end);
2893 return make_buffer_string (b, e, 0);
2896 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2897 doc: /* Return the contents of the current buffer as a string.
2898 If narrowing is in effect, this function returns only the visible part
2899 of the buffer. */)
2900 (void)
2902 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2905 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2906 1, 3, 0,
2907 doc: /* Insert before point a substring of the contents of BUFFER.
2908 BUFFER may be a buffer or a buffer name.
2909 Arguments START and END are character positions specifying the substring.
2910 They default to the values of (point-min) and (point-max) in BUFFER.
2912 Point and before-insertion markers move forward to end up after the
2913 inserted text.
2914 Any other markers at the point of insertion remain before the text.
2916 If the current buffer is multibyte and BUFFER is unibyte, or vice
2917 versa, strings are converted from unibyte to multibyte or vice versa
2918 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2919 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2921 register EMACS_INT b, e, temp;
2922 register struct buffer *bp, *obuf;
2923 Lisp_Object buf;
2925 buf = Fget_buffer (buffer);
2926 if (NILP (buf))
2927 nsberror (buffer);
2928 bp = XBUFFER (buf);
2929 if (!BUFFER_LIVE_P (bp))
2930 error ("Selecting deleted buffer");
2932 if (NILP (start))
2933 b = BUF_BEGV (bp);
2934 else
2936 CHECK_NUMBER_COERCE_MARKER (start);
2937 b = XINT (start);
2939 if (NILP (end))
2940 e = BUF_ZV (bp);
2941 else
2943 CHECK_NUMBER_COERCE_MARKER (end);
2944 e = XINT (end);
2947 if (b > e)
2948 temp = b, b = e, e = temp;
2950 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2951 args_out_of_range (start, end);
2953 obuf = current_buffer;
2954 set_buffer_internal_1 (bp);
2955 update_buffer_properties (b, e);
2956 set_buffer_internal_1 (obuf);
2958 insert_from_buffer (bp, b, e - b, 0);
2959 return Qnil;
2962 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2963 6, 6, 0,
2964 doc: /* Compare two substrings of two buffers; return result as number.
2965 Return -N if first string is less after N-1 chars, +N if first string is
2966 greater after N-1 chars, or 0 if strings match.
2967 The first substring is in BUFFER1 from START1 to END1 and the second
2968 is in BUFFER2 from START2 to END2.
2969 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2970 buffer is used. If START1 or START2 is nil, the value of `point-min'
2971 in the respective buffers is used. If END1 or END2 is nil, the value
2972 of `point-max' in the respective buffers is used.
2973 The value of `case-fold-search' in the current buffer
2974 determines whether case is significant or ignored. */)
2975 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2977 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2978 register struct buffer *bp1, *bp2;
2979 register Lisp_Object trt
2980 = (!NILP (BVAR (current_buffer, case_fold_search))
2981 ? BVAR (current_buffer, case_canon_table) : Qnil);
2982 ptrdiff_t chars = 0;
2983 ptrdiff_t i1, i2, i1_byte, i2_byte;
2985 /* Find the first buffer and its substring. */
2987 if (NILP (buffer1))
2988 bp1 = current_buffer;
2989 else
2991 Lisp_Object buf1;
2992 buf1 = Fget_buffer (buffer1);
2993 if (NILP (buf1))
2994 nsberror (buffer1);
2995 bp1 = XBUFFER (buf1);
2996 if (!BUFFER_LIVE_P (bp1))
2997 error ("Selecting deleted buffer");
3000 if (NILP (start1))
3001 begp1 = BUF_BEGV (bp1);
3002 else
3004 CHECK_NUMBER_COERCE_MARKER (start1);
3005 begp1 = XINT (start1);
3007 if (NILP (end1))
3008 endp1 = BUF_ZV (bp1);
3009 else
3011 CHECK_NUMBER_COERCE_MARKER (end1);
3012 endp1 = XINT (end1);
3015 if (begp1 > endp1)
3016 temp = begp1, begp1 = endp1, endp1 = temp;
3018 if (!(BUF_BEGV (bp1) <= begp1
3019 && begp1 <= endp1
3020 && endp1 <= BUF_ZV (bp1)))
3021 args_out_of_range (start1, end1);
3023 /* Likewise for second substring. */
3025 if (NILP (buffer2))
3026 bp2 = current_buffer;
3027 else
3029 Lisp_Object buf2;
3030 buf2 = Fget_buffer (buffer2);
3031 if (NILP (buf2))
3032 nsberror (buffer2);
3033 bp2 = XBUFFER (buf2);
3034 if (!BUFFER_LIVE_P (bp2))
3035 error ("Selecting deleted buffer");
3038 if (NILP (start2))
3039 begp2 = BUF_BEGV (bp2);
3040 else
3042 CHECK_NUMBER_COERCE_MARKER (start2);
3043 begp2 = XINT (start2);
3045 if (NILP (end2))
3046 endp2 = BUF_ZV (bp2);
3047 else
3049 CHECK_NUMBER_COERCE_MARKER (end2);
3050 endp2 = XINT (end2);
3053 if (begp2 > endp2)
3054 temp = begp2, begp2 = endp2, endp2 = temp;
3056 if (!(BUF_BEGV (bp2) <= begp2
3057 && begp2 <= endp2
3058 && endp2 <= BUF_ZV (bp2)))
3059 args_out_of_range (start2, end2);
3061 i1 = begp1;
3062 i2 = begp2;
3063 i1_byte = buf_charpos_to_bytepos (bp1, i1);
3064 i2_byte = buf_charpos_to_bytepos (bp2, i2);
3066 while (i1 < endp1 && i2 < endp2)
3068 /* When we find a mismatch, we must compare the
3069 characters, not just the bytes. */
3070 int c1, c2;
3072 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
3074 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
3075 BUF_INC_POS (bp1, i1_byte);
3076 i1++;
3078 else
3080 c1 = BUF_FETCH_BYTE (bp1, i1);
3081 MAKE_CHAR_MULTIBYTE (c1);
3082 i1++;
3085 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
3087 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
3088 BUF_INC_POS (bp2, i2_byte);
3089 i2++;
3091 else
3093 c2 = BUF_FETCH_BYTE (bp2, i2);
3094 MAKE_CHAR_MULTIBYTE (c2);
3095 i2++;
3098 if (!NILP (trt))
3100 c1 = char_table_translate (trt, c1);
3101 c2 = char_table_translate (trt, c2);
3104 if (c1 != c2)
3105 return make_number (c1 < c2 ? -1 - chars : chars + 1);
3107 chars++;
3108 rarely_quit (chars);
3111 /* The strings match as far as they go.
3112 If one is shorter, that one is less. */
3113 if (chars < endp1 - begp1)
3114 return make_number (chars + 1);
3115 else if (chars < endp2 - begp2)
3116 return make_number (- chars - 1);
3118 /* Same length too => they are equal. */
3119 return make_number (0);
3123 /* Set up necessary definitions for diffseq.h; see comments in
3124 diffseq.h for explanation. */
3126 #undef ELEMENT
3127 #undef EQUAL
3129 #define XVECREF_YVECREF_EQUAL(ctx, xoff, yoff) \
3130 buffer_chars_equal ((ctx), (xoff), (yoff))
3132 #define OFFSET ptrdiff_t
3134 #define EXTRA_CONTEXT_FIELDS \
3135 /* Buffers to compare. */ \
3136 struct buffer *buffer_a; \
3137 struct buffer *buffer_b; \
3138 /* Bit vectors recording for each character whether it was deleted
3139 or inserted. */ \
3140 unsigned char *deletions; \
3141 unsigned char *insertions;
3143 #define NOTE_DELETE(ctx, xoff) set_bit ((ctx)->deletions, (xoff))
3144 #define NOTE_INSERT(ctx, yoff) set_bit ((ctx)->insertions, (yoff))
3146 struct context;
3147 static void set_bit (unsigned char *, OFFSET);
3148 static bool bit_is_set (const unsigned char *, OFFSET);
3149 static bool buffer_chars_equal (struct context *, OFFSET, OFFSET);
3151 #include "minmax.h"
3152 #include "diffseq.h"
3154 DEFUN ("replace-buffer-contents", Freplace_buffer_contents,
3155 Sreplace_buffer_contents, 1, 1, "bSource buffer: ",
3156 doc: /* Replace accessible portion of current buffer with that of SOURCE.
3157 SOURCE can be a buffer or a string that names a buffer.
3158 Interactively, prompt for SOURCE.
3159 As far as possible the replacement is non-destructive, i.e. existing
3160 buffer contents, markers, properties, and overlays in the current
3161 buffer stay intact.
3162 Warning: this function can be slow if there's a large number of small
3163 differences between the two buffers. */)
3164 (Lisp_Object source)
3166 struct buffer *a = current_buffer;
3167 Lisp_Object source_buffer = Fget_buffer (source);
3168 if (NILP (source_buffer))
3169 nsberror (source);
3170 struct buffer *b = XBUFFER (source_buffer);
3171 if (! BUFFER_LIVE_P (b))
3172 error ("Selecting deleted buffer");
3173 if (a == b)
3174 error ("Cannot replace a buffer with itself");
3176 ptrdiff_t min_a = BEGV;
3177 ptrdiff_t min_b = BUF_BEGV (b);
3178 ptrdiff_t size_a = ZV - min_a;
3179 ptrdiff_t size_b = BUF_ZV (b) - min_b;
3180 eassume (size_a >= 0);
3181 eassume (size_b >= 0);
3182 bool a_empty = size_a == 0;
3183 bool b_empty = size_b == 0;
3185 /* Handle trivial cases where at least one accessible portion is
3186 empty. */
3188 if (a_empty && b_empty)
3189 return Qnil;
3191 if (a_empty)
3192 return Finsert_buffer_substring (source, Qnil, Qnil);
3194 if (b_empty)
3196 del_range_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, true);
3197 return Qnil;
3200 /* FIXME: It is not documented how to initialize the contents of the
3201 context structure. This code cargo-cults from the existing
3202 caller in src/analyze.c of GNU Diffutils, which appears to
3203 work. */
3205 ptrdiff_t diags = size_a + size_b + 3;
3206 ptrdiff_t *buffer;
3207 USE_SAFE_ALLOCA;
3208 SAFE_NALLOCA (buffer, 2, diags);
3209 /* Micro-optimization: Casting to size_t generates much better
3210 code. */
3211 ptrdiff_t del_bytes = (size_t) size_a / CHAR_BIT + 1;
3212 ptrdiff_t ins_bytes = (size_t) size_b / CHAR_BIT + 1;
3213 struct context ctx = {
3214 .buffer_a = a,
3215 .buffer_b = b,
3216 .deletions = SAFE_ALLOCA (del_bytes),
3217 .insertions = SAFE_ALLOCA (ins_bytes),
3218 .fdiag = buffer + size_b + 1,
3219 .bdiag = buffer + diags + size_b + 1,
3220 /* FIXME: Find a good number for .too_expensive. */
3221 .too_expensive = 1000000,
3223 memclear (ctx.deletions, del_bytes);
3224 memclear (ctx.insertions, ins_bytes);
3225 /* compareseq requires indices to be zero-based. We add BEGV back
3226 later. */
3227 bool early_abort = compareseq (0, size_a, 0, size_b, false, &ctx);
3228 /* Since we didn’t define EARLY_ABORT, we should never abort
3229 early. */
3230 eassert (! early_abort);
3232 Fundo_boundary ();
3233 ptrdiff_t count = SPECPDL_INDEX ();
3234 record_unwind_protect_excursion ();
3236 ptrdiff_t i = size_a;
3237 ptrdiff_t j = size_b;
3238 /* Walk backwards through the lists of changes. This was also
3239 cargo-culted from src/analyze.c in GNU Diffutils. Because we
3240 walk backwards, we don’t have to keep the positions in sync. */
3241 while (i >= 0 || j >= 0)
3243 /* Allow the user to quit if this gets too slow. */
3244 maybe_quit ();
3246 /* Check whether there is a change (insertion or deletion)
3247 before the current position. */
3248 if ((i > 0 && bit_is_set (ctx.deletions, i - 1)) ||
3249 (j > 0 && bit_is_set (ctx.insertions, j - 1)))
3251 maybe_quit ();
3253 ptrdiff_t end_a = min_a + i;
3254 ptrdiff_t end_b = min_b + j;
3255 /* Find the beginning of the current change run. */
3256 while (i > 0 && bit_is_set (ctx.deletions, i - 1))
3257 --i;
3258 while (j > 0 && bit_is_set (ctx.insertions, j - 1))
3259 --j;
3260 ptrdiff_t beg_a = min_a + i;
3261 ptrdiff_t beg_b = min_b + j;
3262 eassert (beg_a >= BEGV);
3263 eassert (beg_b >= BUF_BEGV (b));
3264 eassert (beg_a <= end_a);
3265 eassert (beg_b <= end_b);
3266 eassert (end_a <= ZV);
3267 eassert (end_b <= BUF_ZV (b));
3268 eassert (beg_a < end_a || beg_b < end_b);
3269 if (beg_a < end_a)
3270 del_range (beg_a, end_a);
3271 if (beg_b < end_b)
3273 SET_PT (beg_a);
3274 Finsert_buffer_substring (source, make_natnum (beg_b),
3275 make_natnum (end_b));
3278 --i;
3279 --j;
3281 unbind_to (count, Qnil);
3282 SAFE_FREE ();
3284 return Qnil;
3287 static void
3288 set_bit (unsigned char *a, ptrdiff_t i)
3290 eassert (i >= 0);
3291 /* Micro-optimization: Casting to size_t generates much better
3292 code. */
3293 size_t j = i;
3294 a[j / CHAR_BIT] |= (1 << (j % CHAR_BIT));
3297 static bool
3298 bit_is_set (const unsigned char *a, ptrdiff_t i)
3300 eassert (i >= 0);
3301 /* Micro-optimization: Casting to size_t generates much better
3302 code. */
3303 size_t j = i;
3304 return a[j / CHAR_BIT] & (1 << (j % CHAR_BIT));
3307 /* Return true if the characters at position POS_A of buffer
3308 CTX->buffer_a and at position POS_B of buffer CTX->buffer_b are
3309 equal. POS_A and POS_B are zero-based. Text properties are
3310 ignored. */
3312 static bool
3313 buffer_chars_equal (struct context *ctx,
3314 ptrdiff_t pos_a, ptrdiff_t pos_b)
3316 eassert (pos_a >= 0);
3317 pos_a += BUF_BEGV (ctx->buffer_a);
3318 eassert (pos_a >= BUF_BEGV (ctx->buffer_a));
3319 eassert (pos_a < BUF_ZV (ctx->buffer_a));
3321 eassert (pos_b >= 0);
3322 pos_b += BUF_BEGV (ctx->buffer_b);
3323 eassert (pos_b >= BUF_BEGV (ctx->buffer_b));
3324 eassert (pos_b < BUF_ZV (ctx->buffer_b));
3326 bool a_unibyte = BUF_ZV (ctx->buffer_a) == BUF_ZV_BYTE (ctx->buffer_a);
3327 bool b_unibyte = BUF_ZV (ctx->buffer_b) == BUF_ZV_BYTE (ctx->buffer_b);
3329 /* Allow the user to escape out of a slow compareseq call. */
3330 maybe_quit ();
3332 ptrdiff_t bpos_a =
3333 a_unibyte ? pos_a : buf_charpos_to_bytepos (ctx->buffer_a, pos_a);
3334 ptrdiff_t bpos_b =
3335 b_unibyte ? pos_b : buf_charpos_to_bytepos (ctx->buffer_b, pos_b);
3337 if (a_unibyte && b_unibyte)
3338 return BUF_FETCH_BYTE (ctx->buffer_a, bpos_a)
3339 == BUF_FETCH_BYTE (ctx->buffer_b, bpos_b);
3341 return BUF_FETCH_CHAR_AS_MULTIBYTE (ctx->buffer_a, bpos_a)
3342 == BUF_FETCH_CHAR_AS_MULTIBYTE (ctx->buffer_b, bpos_b);
3346 static void
3347 subst_char_in_region_unwind (Lisp_Object arg)
3349 bset_undo_list (current_buffer, arg);
3352 static void
3353 subst_char_in_region_unwind_1 (Lisp_Object arg)
3355 bset_filename (current_buffer, arg);
3358 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
3359 Ssubst_char_in_region, 4, 5, 0,
3360 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3361 If optional arg NOUNDO is non-nil, don't record this change for undo
3362 and don't mark the buffer as really changed.
3363 Both characters must have the same length of multi-byte form. */)
3364 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
3366 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
3367 /* Keep track of the first change in the buffer:
3368 if 0 we haven't found it yet.
3369 if < 0 we've found it and we've run the before-change-function.
3370 if > 0 we've actually performed it and the value is its position. */
3371 ptrdiff_t changed = 0;
3372 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
3373 unsigned char *p;
3374 ptrdiff_t count = SPECPDL_INDEX ();
3375 #define COMBINING_NO 0
3376 #define COMBINING_BEFORE 1
3377 #define COMBINING_AFTER 2
3378 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3379 int maybe_byte_combining = COMBINING_NO;
3380 ptrdiff_t last_changed = 0;
3381 bool multibyte_p
3382 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3383 int fromc, toc;
3385 restart:
3387 validate_region (&start, &end);
3388 CHECK_CHARACTER (fromchar);
3389 CHECK_CHARACTER (tochar);
3390 fromc = XFASTINT (fromchar);
3391 toc = XFASTINT (tochar);
3393 if (multibyte_p)
3395 len = CHAR_STRING (fromc, fromstr);
3396 if (CHAR_STRING (toc, tostr) != len)
3397 error ("Characters in `subst-char-in-region' have different byte-lengths");
3398 if (!ASCII_CHAR_P (*tostr))
3400 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3401 complete multibyte character, it may be combined with the
3402 after bytes. If it is in the range 0xA0..0xFF, it may be
3403 combined with the before and after bytes. */
3404 if (!CHAR_HEAD_P (*tostr))
3405 maybe_byte_combining = COMBINING_BOTH;
3406 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3407 maybe_byte_combining = COMBINING_AFTER;
3410 else
3412 len = 1;
3413 fromstr[0] = fromc;
3414 tostr[0] = toc;
3417 pos = XINT (start);
3418 pos_byte = CHAR_TO_BYTE (pos);
3419 stop = CHAR_TO_BYTE (XINT (end));
3420 end_byte = stop;
3422 /* If we don't want undo, turn off putting stuff on the list.
3423 That's faster than getting rid of things,
3424 and it prevents even the entry for a first change.
3425 Also inhibit locking the file. */
3426 if (!changed && !NILP (noundo))
3428 record_unwind_protect (subst_char_in_region_unwind,
3429 BVAR (current_buffer, undo_list));
3430 bset_undo_list (current_buffer, Qt);
3431 /* Don't do file-locking. */
3432 record_unwind_protect (subst_char_in_region_unwind_1,
3433 BVAR (current_buffer, filename));
3434 bset_filename (current_buffer, Qnil);
3437 if (pos_byte < GPT_BYTE)
3438 stop = min (stop, GPT_BYTE);
3439 while (1)
3441 ptrdiff_t pos_byte_next = pos_byte;
3443 if (pos_byte >= stop)
3445 if (pos_byte >= end_byte) break;
3446 stop = end_byte;
3448 p = BYTE_POS_ADDR (pos_byte);
3449 if (multibyte_p)
3450 INC_POS (pos_byte_next);
3451 else
3452 ++pos_byte_next;
3453 if (pos_byte_next - pos_byte == len
3454 && p[0] == fromstr[0]
3455 && (len == 1
3456 || (p[1] == fromstr[1]
3457 && (len == 2 || (p[2] == fromstr[2]
3458 && (len == 3 || p[3] == fromstr[3]))))))
3460 if (changed < 0)
3461 /* We've already seen this and run the before-change-function;
3462 this time we only need to record the actual position. */
3463 changed = pos;
3464 else if (!changed)
3466 changed = -1;
3467 modify_text (pos, XINT (end));
3469 if (! NILP (noundo))
3471 if (MODIFF - 1 == SAVE_MODIFF)
3472 SAVE_MODIFF++;
3473 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3474 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3477 /* The before-change-function may have moved the gap
3478 or even modified the buffer so we should start over. */
3479 goto restart;
3482 /* Take care of the case where the new character
3483 combines with neighboring bytes. */
3484 if (maybe_byte_combining
3485 && (maybe_byte_combining == COMBINING_AFTER
3486 ? (pos_byte_next < Z_BYTE
3487 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3488 : ((pos_byte_next < Z_BYTE
3489 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3490 || (pos_byte > BEG_BYTE
3491 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3493 Lisp_Object tem, string;
3495 tem = BVAR (current_buffer, undo_list);
3497 /* Make a multibyte string containing this single character. */
3498 string = make_multibyte_string ((char *) tostr, 1, len);
3499 /* replace_range is less efficient, because it moves the gap,
3500 but it handles combining correctly. */
3501 replace_range (pos, pos + 1, string,
3502 0, 0, 1, 0);
3503 pos_byte_next = CHAR_TO_BYTE (pos);
3504 if (pos_byte_next > pos_byte)
3505 /* Before combining happened. We should not increment
3506 POS. So, to cancel the later increment of POS,
3507 decrease it now. */
3508 pos--;
3509 else
3510 INC_POS (pos_byte_next);
3512 if (! NILP (noundo))
3513 bset_undo_list (current_buffer, tem);
3515 else
3517 if (NILP (noundo))
3518 record_change (pos, 1);
3519 for (i = 0; i < len; i++) *p++ = tostr[i];
3521 last_changed = pos + 1;
3523 pos_byte = pos_byte_next;
3524 pos++;
3527 if (changed > 0)
3529 signal_after_change (changed,
3530 last_changed - changed, last_changed - changed);
3531 update_compositions (changed, last_changed, CHECK_ALL);
3534 unbind_to (count, Qnil);
3535 return Qnil;
3539 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3540 Lisp_Object);
3542 /* Helper function for Ftranslate_region_internal.
3544 Check if a character sequence at POS (POS_BYTE) matches an element
3545 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3546 element is found, return it. Otherwise return Qnil. */
3548 static Lisp_Object
3549 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3550 Lisp_Object val)
3552 int initial_buf[16];
3553 int *buf = initial_buf;
3554 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3555 int *bufalloc = 0;
3556 ptrdiff_t buf_used = 0;
3557 Lisp_Object result = Qnil;
3559 for (; CONSP (val); val = XCDR (val))
3561 Lisp_Object elt;
3562 ptrdiff_t len, i;
3564 elt = XCAR (val);
3565 if (! CONSP (elt))
3566 continue;
3567 elt = XCAR (elt);
3568 if (! VECTORP (elt))
3569 continue;
3570 len = ASIZE (elt);
3571 if (len <= end - pos)
3573 for (i = 0; i < len; i++)
3575 if (buf_used <= i)
3577 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3578 int len1;
3580 if (buf_used == buf_size)
3582 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3583 sizeof *bufalloc);
3584 if (buf == initial_buf)
3585 memcpy (bufalloc, buf, sizeof initial_buf);
3586 buf = bufalloc;
3588 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3589 pos_byte += len1;
3591 if (XINT (AREF (elt, i)) != buf[i])
3592 break;
3594 if (i == len)
3596 result = XCAR (val);
3597 break;
3602 xfree (bufalloc);
3603 return result;
3607 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3608 Stranslate_region_internal, 3, 3, 0,
3609 doc: /* Internal use only.
3610 From START to END, translate characters according to TABLE.
3611 TABLE is a string or a char-table; the Nth character in it is the
3612 mapping for the character with code N.
3613 It returns the number of characters changed. */)
3614 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3616 register unsigned char *tt; /* Trans table. */
3617 register int nc; /* New character. */
3618 int cnt; /* Number of changes made. */
3619 ptrdiff_t size; /* Size of translate table. */
3620 ptrdiff_t pos, pos_byte, end_pos;
3621 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3622 bool string_multibyte UNINIT;
3624 validate_region (&start, &end);
3625 if (CHAR_TABLE_P (table))
3627 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3628 error ("Not a translation table");
3629 size = MAX_CHAR;
3630 tt = NULL;
3632 else
3634 CHECK_STRING (table);
3636 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3637 table = string_make_unibyte (table);
3638 string_multibyte = SCHARS (table) < SBYTES (table);
3639 size = SBYTES (table);
3640 tt = SDATA (table);
3643 pos = XINT (start);
3644 pos_byte = CHAR_TO_BYTE (pos);
3645 end_pos = XINT (end);
3646 modify_text (pos, end_pos);
3648 cnt = 0;
3649 for (; pos < end_pos; )
3651 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3652 unsigned char *str UNINIT;
3653 unsigned char buf[MAX_MULTIBYTE_LENGTH];
3654 int len, str_len;
3655 int oc;
3656 Lisp_Object val;
3658 if (multibyte)
3659 oc = STRING_CHAR_AND_LENGTH (p, len);
3660 else
3661 oc = *p, len = 1;
3662 if (oc < size)
3664 if (tt)
3666 /* Reload as signal_after_change in last iteration may GC. */
3667 tt = SDATA (table);
3668 if (string_multibyte)
3670 str = tt + string_char_to_byte (table, oc);
3671 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3673 else
3675 nc = tt[oc];
3676 if (! ASCII_CHAR_P (nc) && multibyte)
3678 str_len = BYTE8_STRING (nc, buf);
3679 str = buf;
3681 else
3683 str_len = 1;
3684 str = tt + oc;
3688 else
3690 nc = oc;
3691 val = CHAR_TABLE_REF (table, oc);
3692 if (CHARACTERP (val))
3694 nc = XFASTINT (val);
3695 str_len = CHAR_STRING (nc, buf);
3696 str = buf;
3698 else if (VECTORP (val) || (CONSP (val)))
3700 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3701 where TO is TO-CHAR or [TO-CHAR ...]. */
3702 nc = -1;
3706 if (nc != oc && nc >= 0)
3708 /* Simple one char to one char translation. */
3709 if (len != str_len)
3711 Lisp_Object string;
3713 /* This is less efficient, because it moves the gap,
3714 but it should handle multibyte characters correctly. */
3715 string = make_multibyte_string ((char *) str, 1, str_len);
3716 replace_range (pos, pos + 1, string, 1, 0, 1, 0);
3717 len = str_len;
3719 else
3721 record_change (pos, 1);
3722 while (str_len-- > 0)
3723 *p++ = *str++;
3724 signal_after_change (pos, 1, 1);
3725 update_compositions (pos, pos + 1, CHECK_BORDER);
3727 ++cnt;
3729 else if (nc < 0)
3731 Lisp_Object string;
3733 if (CONSP (val))
3735 val = check_translation (pos, pos_byte, end_pos, val);
3736 if (NILP (val))
3738 pos_byte += len;
3739 pos++;
3740 continue;
3742 /* VAL is ([FROM-CHAR ...] . TO). */
3743 len = ASIZE (XCAR (val));
3744 val = XCDR (val);
3746 else
3747 len = 1;
3749 if (VECTORP (val))
3751 string = Fconcat (1, &val);
3753 else
3755 string = Fmake_string (make_number (1), val, Qnil);
3757 replace_range (pos, pos + len, string, 1, 0, 1, 0);
3758 pos_byte += SBYTES (string);
3759 pos += SCHARS (string);
3760 cnt += SCHARS (string);
3761 end_pos += SCHARS (string) - len;
3762 continue;
3765 pos_byte += len;
3766 pos++;
3769 return make_number (cnt);
3772 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3773 doc: /* Delete the text between START and END.
3774 If called interactively, delete the region between point and mark.
3775 This command deletes buffer text without modifying the kill ring. */)
3776 (Lisp_Object start, Lisp_Object end)
3778 validate_region (&start, &end);
3779 del_range (XINT (start), XINT (end));
3780 return Qnil;
3783 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3784 Sdelete_and_extract_region, 2, 2, 0,
3785 doc: /* Delete the text between START and END and return it. */)
3786 (Lisp_Object start, Lisp_Object end)
3788 validate_region (&start, &end);
3789 if (XINT (start) == XINT (end))
3790 return empty_unibyte_string;
3791 return del_range_1 (XINT (start), XINT (end), 1, 1);
3794 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3795 doc: /* Remove restrictions (narrowing) from current buffer.
3796 This allows the buffer's full text to be seen and edited. */)
3797 (void)
3799 if (BEG != BEGV || Z != ZV)
3800 current_buffer->clip_changed = 1;
3801 BEGV = BEG;
3802 BEGV_BYTE = BEG_BYTE;
3803 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3804 /* Changing the buffer bounds invalidates any recorded current column. */
3805 invalidate_current_column ();
3806 return Qnil;
3809 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3810 doc: /* Restrict editing in this buffer to the current region.
3811 The rest of the text becomes temporarily invisible and untouchable
3812 but is not deleted; if you save the buffer in a file, the invisible
3813 text is included in the file. \\[widen] makes all visible again.
3814 See also `save-restriction'.
3816 When calling from a program, pass two arguments; positions (integers
3817 or markers) bounding the text that should remain visible. */)
3818 (register Lisp_Object start, Lisp_Object end)
3820 CHECK_NUMBER_COERCE_MARKER (start);
3821 CHECK_NUMBER_COERCE_MARKER (end);
3823 if (XINT (start) > XINT (end))
3825 Lisp_Object tem;
3826 tem = start; start = end; end = tem;
3829 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3830 args_out_of_range (start, end);
3832 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3833 current_buffer->clip_changed = 1;
3835 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3836 SET_BUF_ZV (current_buffer, XFASTINT (end));
3837 if (PT < XFASTINT (start))
3838 SET_PT (XFASTINT (start));
3839 if (PT > XFASTINT (end))
3840 SET_PT (XFASTINT (end));
3841 /* Changing the buffer bounds invalidates any recorded current column. */
3842 invalidate_current_column ();
3843 return Qnil;
3846 Lisp_Object
3847 save_restriction_save (void)
3849 if (BEGV == BEG && ZV == Z)
3850 /* The common case that the buffer isn't narrowed.
3851 We return just the buffer object, which save_restriction_restore
3852 recognizes as meaning `no restriction'. */
3853 return Fcurrent_buffer ();
3854 else
3855 /* We have to save a restriction, so return a pair of markers, one
3856 for the beginning and one for the end. */
3858 Lisp_Object beg, end;
3860 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3861 end = build_marker (current_buffer, ZV, ZV_BYTE);
3863 /* END must move forward if text is inserted at its exact location. */
3864 XMARKER (end)->insertion_type = 1;
3866 return Fcons (beg, end);
3870 void
3871 save_restriction_restore (Lisp_Object data)
3873 struct buffer *cur = NULL;
3874 struct buffer *buf = (CONSP (data)
3875 ? XMARKER (XCAR (data))->buffer
3876 : XBUFFER (data));
3878 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3879 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3880 is the case if it is or has an indirect buffer), then make
3881 sure it is current before we update BEGV, so
3882 set_buffer_internal takes care of managing those markers. */
3883 cur = current_buffer;
3884 set_buffer_internal (buf);
3887 if (CONSP (data))
3888 /* A pair of marks bounding a saved restriction. */
3890 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3891 struct Lisp_Marker *end = XMARKER (XCDR (data));
3892 eassert (buf == end->buffer);
3894 if (buf /* Verify marker still points to a buffer. */
3895 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3896 /* The restriction has changed from the saved one, so restore
3897 the saved restriction. */
3899 ptrdiff_t pt = BUF_PT (buf);
3901 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3902 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3904 if (pt < beg->charpos || pt > end->charpos)
3905 /* The point is outside the new visible range, move it inside. */
3906 SET_BUF_PT_BOTH (buf,
3907 clip_to_bounds (beg->charpos, pt, end->charpos),
3908 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3909 end->bytepos));
3911 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3913 /* Detach the markers, and free the cons instead of waiting for GC. */
3914 detach_marker (XCAR (data));
3915 detach_marker (XCDR (data));
3916 free_cons (XCONS (data));
3918 else
3919 /* A buffer, which means that there was no old restriction. */
3921 if (buf /* Verify marker still points to a buffer. */
3922 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3923 /* The buffer has been narrowed, get rid of the narrowing. */
3925 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3926 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3928 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3932 /* Changing the buffer bounds invalidates any recorded current column. */
3933 invalidate_current_column ();
3935 if (cur)
3936 set_buffer_internal (cur);
3939 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3940 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3941 The buffer's restrictions make parts of the beginning and end invisible.
3942 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3943 This special form, `save-restriction', saves the current buffer's restrictions
3944 when it is entered, and restores them when it is exited.
3945 So any `narrow-to-region' within BODY lasts only until the end of the form.
3946 The old restrictions settings are restored
3947 even in case of abnormal exit (throw or error).
3949 The value returned is the value of the last form in BODY.
3951 Note: if you are using both `save-excursion' and `save-restriction',
3952 use `save-excursion' outermost:
3953 (save-excursion (save-restriction ...))
3955 usage: (save-restriction &rest BODY) */)
3956 (Lisp_Object body)
3958 register Lisp_Object val;
3959 ptrdiff_t count = SPECPDL_INDEX ();
3961 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3962 val = Fprogn (body);
3963 return unbind_to (count, val);
3966 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3967 doc: /* Display a message at the bottom of the screen.
3968 The message also goes into the `*Messages*' buffer, if `message-log-max'
3969 is non-nil. (In keyboard macros, that's all it does.)
3970 Return the message.
3972 In batch mode, the message is printed to the standard error stream,
3973 followed by a newline.
3975 The first argument is a format control string, and the rest are data
3976 to be formatted under control of the string. Percent sign (%), grave
3977 accent (\\=`) and apostrophe (\\=') are special in the format; see
3978 `format-message' for details. To display STRING without special
3979 treatment, use (message "%s" STRING).
3981 If the first argument is nil or the empty string, the function clears
3982 any existing message; this lets the minibuffer contents show. See
3983 also `current-message'.
3985 usage: (message FORMAT-STRING &rest ARGS) */)
3986 (ptrdiff_t nargs, Lisp_Object *args)
3988 if (NILP (args[0])
3989 || (STRINGP (args[0])
3990 && SBYTES (args[0]) == 0))
3992 message1 (0);
3993 return args[0];
3995 else
3997 Lisp_Object val = Fformat_message (nargs, args);
3998 message3 (val);
3999 return val;
4003 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
4004 doc: /* Display a message, in a dialog box if possible.
4005 If a dialog box is not available, use the echo area.
4006 The first argument is a format control string, and the rest are data
4007 to be formatted under control of the string. See `format-message' for
4008 details.
4010 If the first argument is nil or the empty string, clear any existing
4011 message; let the minibuffer contents show.
4013 usage: (message-box FORMAT-STRING &rest ARGS) */)
4014 (ptrdiff_t nargs, Lisp_Object *args)
4016 if (NILP (args[0]))
4018 message1 (0);
4019 return Qnil;
4021 else
4023 Lisp_Object val = Fformat_message (nargs, args);
4024 Lisp_Object pane, menu;
4026 pane = list1 (Fcons (build_string ("OK"), Qt));
4027 menu = Fcons (val, pane);
4028 Fx_popup_dialog (Qt, menu, Qt);
4029 return val;
4033 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
4034 doc: /* Display a message in a dialog box or in the echo area.
4035 If this command was invoked with the mouse, use a dialog box if
4036 `use-dialog-box' is non-nil.
4037 Otherwise, use the echo area.
4038 The first argument is a format control string, and the rest are data
4039 to be formatted under control of the string. See `format-message' for
4040 details.
4042 If the first argument is nil or the empty string, clear any existing
4043 message; let the minibuffer contents show.
4045 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
4046 (ptrdiff_t nargs, Lisp_Object *args)
4048 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
4049 && use_dialog_box)
4050 return Fmessage_box (nargs, args);
4051 return Fmessage (nargs, args);
4054 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
4055 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
4056 (void)
4058 return current_message ();
4062 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
4063 doc: /* Return a copy of STRING with text properties added.
4064 First argument is the string to copy.
4065 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4066 properties to add to the result.
4067 usage: (propertize STRING &rest PROPERTIES) */)
4068 (ptrdiff_t nargs, Lisp_Object *args)
4070 Lisp_Object properties, string;
4071 ptrdiff_t i;
4073 /* Number of args must be odd. */
4074 if ((nargs & 1) == 0)
4075 error ("Wrong number of arguments");
4077 properties = string = Qnil;
4079 /* First argument must be a string. */
4080 CHECK_STRING (args[0]);
4081 string = Fcopy_sequence (args[0]);
4083 for (i = 1; i < nargs; i += 2)
4084 properties = Fcons (args[i], Fcons (args[i + 1], properties));
4086 Fadd_text_properties (make_number (0),
4087 make_number (SCHARS (string)),
4088 properties, string);
4089 return string;
4092 /* Convert the prefix of STR from ASCII decimal digits to a number.
4093 Set *STR_END to the address of the first non-digit. Return the
4094 number, or PTRDIFF_MAX on overflow. Return 0 if there is no number.
4095 This is like strtol for ptrdiff_t and base 10 and C locale,
4096 except without negative numbers or errno. */
4098 static ptrdiff_t
4099 str2num (char *str, char **str_end)
4101 ptrdiff_t n = 0;
4102 for (; c_isdigit (*str); str++)
4103 if (INT_MULTIPLY_WRAPV (n, 10, &n) || INT_ADD_WRAPV (n, *str - '0', &n))
4104 n = PTRDIFF_MAX;
4105 *str_end = str;
4106 return n;
4109 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
4110 doc: /* Format a string out of a format-string and arguments.
4111 The first argument is a format control string.
4112 The other arguments are substituted into it to make the result, a string.
4114 The format control string may contain %-sequences meaning to substitute
4115 the next available argument, or the argument explicitly specified:
4117 %s means print a string argument. Actually, prints any object, with `princ'.
4118 %d means print as signed number in decimal.
4119 %o means print as unsigned number in octal.
4120 %x means print as unsigned number in hex.
4121 %X is like %x, but uses upper case.
4122 %e means print a number in exponential notation.
4123 %f means print a number in decimal-point notation.
4124 %g means print a number in exponential notation if the exponent would be
4125 less than -4 or greater than or equal to the precision (default: 6);
4126 otherwise it prints in decimal-point notation.
4127 %c means print a number as a single character.
4128 %S means print any object as an s-expression (using `prin1').
4130 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4131 Use %% to put a single % into the output.
4133 A %-sequence other than %% may contain optional field number, flag,
4134 width, and precision specifiers, as follows:
4136 %<field><flags><width><precision>character
4138 where field is [0-9]+ followed by a literal dollar "$", flags is
4139 [+ #-0]+, width is [0-9]+, and precision is a literal period "."
4140 followed by [0-9]+.
4142 If a %-sequence is numbered with a field with positive value N, the
4143 Nth argument is substituted instead of the next one. A format can
4144 contain either numbered or unnumbered %-sequences but not both, except
4145 that %% can be mixed with numbered %-sequences.
4147 The + flag character inserts a + before any positive number, while a
4148 space inserts a space before any positive number; these flags only
4149 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
4150 The - and 0 flags affect the width specifier, as described below.
4152 The # flag means to use an alternate display form for %o, %x, %X, %e,
4153 %f, and %g sequences: for %o, it ensures that the result begins with
4154 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
4155 for %e and %f, it causes a decimal point to be included even if the
4156 precision is zero; for %g, it causes a decimal point to be
4157 included even if the precision is zero, and also forces trailing
4158 zeros after the decimal point to be left in place.
4160 The width specifier supplies a lower limit for the length of the
4161 printed representation. The padding, if any, normally goes on the
4162 left, but it goes on the right if the - flag is present. The padding
4163 character is normally a space, but it is 0 if the 0 flag is present.
4164 The 0 flag is ignored if the - flag is present, or the format sequence
4165 is something other than %d, %e, %f, and %g.
4167 For %e and %f sequences, the number after the "." in the precision
4168 specifier says how many decimal places to show; if zero, the decimal
4169 point itself is omitted. For %g, the precision specifies how many
4170 significant digits to print; zero or omitted are treated as 1.
4171 For %s and %S, the precision specifier truncates the string to the
4172 given width.
4174 Text properties, if any, are copied from the format-string to the
4175 produced text.
4177 usage: (format STRING &rest OBJECTS) */)
4178 (ptrdiff_t nargs, Lisp_Object *args)
4180 return styled_format (nargs, args, false);
4183 DEFUN ("format-message", Fformat_message, Sformat_message, 1, MANY, 0,
4184 doc: /* Format a string out of a format-string and arguments.
4185 The first argument is a format control string.
4186 The other arguments are substituted into it to make the result, a string.
4188 This acts like `format', except it also replaces each grave accent (\\=`)
4189 by a left quote, and each apostrophe (\\=') by a right quote. The left
4190 and right quote replacement characters are specified by
4191 `text-quoting-style'.
4193 usage: (format-message STRING &rest OBJECTS) */)
4194 (ptrdiff_t nargs, Lisp_Object *args)
4196 return styled_format (nargs, args, true);
4199 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise. */
4201 static Lisp_Object
4202 styled_format (ptrdiff_t nargs, Lisp_Object *args, bool message)
4204 ptrdiff_t n; /* The number of the next arg to substitute. */
4205 char initial_buffer[4000];
4206 char *buf = initial_buffer;
4207 ptrdiff_t bufsize = sizeof initial_buffer;
4208 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
4209 char *p;
4210 ptrdiff_t buf_save_value_index UNINIT;
4211 char *format, *end;
4212 ptrdiff_t nchars;
4213 /* When we make a multibyte string, we must pay attention to the
4214 byte combining problem, i.e., a byte may be combined with a
4215 multibyte character of the previous string. This flag tells if we
4216 must consider such a situation or not. */
4217 bool maybe_combine_byte;
4218 Lisp_Object val;
4219 bool arg_intervals = false;
4220 USE_SAFE_ALLOCA;
4221 sa_avail -= sizeof initial_buffer;
4223 /* Information recorded for each format spec. */
4224 struct info
4226 /* The corresponding argument, converted to string if conversion
4227 was needed. */
4228 Lisp_Object argument;
4230 /* The start and end bytepos in the output string. */
4231 ptrdiff_t start, end;
4233 /* Whether the argument is a string with intervals. */
4234 bool_bf intervals : 1;
4235 } *info;
4237 CHECK_STRING (args[0]);
4238 char *format_start = SSDATA (args[0]);
4239 bool multibyte_format = STRING_MULTIBYTE (args[0]);
4240 ptrdiff_t formatlen = SBYTES (args[0]);
4242 /* Upper bound on number of format specs. Each uses at least 2 chars. */
4243 ptrdiff_t nspec_bound = SCHARS (args[0]) >> 1;
4245 /* Allocate the info and discarded tables. */
4246 ptrdiff_t info_size, alloca_size;
4247 if (INT_MULTIPLY_WRAPV (nspec_bound, sizeof *info, &info_size)
4248 || INT_ADD_WRAPV (formatlen, info_size, &alloca_size)
4249 || SIZE_MAX < alloca_size)
4250 memory_full (SIZE_MAX);
4251 info = SAFE_ALLOCA (alloca_size);
4252 /* discarded[I] is 1 if byte I of the format
4253 string was not copied into the output.
4254 It is 2 if byte I was not the first byte of its character. */
4255 char *discarded = (char *) &info[nspec_bound];
4256 info = ptr_bounds_clip (info, info_size);
4257 discarded = ptr_bounds_clip (discarded, formatlen);
4258 memset (discarded, 0, formatlen);
4260 /* Try to determine whether the result should be multibyte.
4261 This is not always right; sometimes the result needs to be multibyte
4262 because of an object that we will pass through prin1.
4263 or because a grave accent or apostrophe is requoted,
4264 and in that case, we won't know it here. */
4266 /* True if the output should be a multibyte string,
4267 which is true if any of the inputs is one. */
4268 bool multibyte = multibyte_format;
4269 for (ptrdiff_t i = 1; !multibyte && i < nargs; i++)
4270 if (STRINGP (args[i]) && STRING_MULTIBYTE (args[i]))
4271 multibyte = true;
4273 int quoting_style = message ? text_quoting_style () : -1;
4275 ptrdiff_t ispec;
4276 ptrdiff_t nspec = 0;
4278 /* True if a string needs to be allocated to hold the result. */
4279 bool new_result = false;
4281 /* If we start out planning a unibyte result,
4282 then discover it has to be multibyte, we jump back to retry. */
4283 retry:
4285 p = buf;
4286 nchars = 0;
4288 /* N is the argument index, ISPEC is the specification index. */
4289 n = 0;
4290 ispec = 0;
4292 /* Scan the format and store result in BUF. */
4293 format = format_start;
4294 end = format + formatlen;
4295 maybe_combine_byte = false;
4297 while (format != end)
4299 /* The values of N, ISPEC, and FORMAT when the loop body is
4300 entered. */
4301 ptrdiff_t n0 = n;
4302 ptrdiff_t ispec0 = ispec;
4303 char *format0 = format;
4304 char const *convsrc = format;
4305 unsigned char format_char = *format++;
4307 /* Bytes needed to represent the output of this conversion. */
4308 ptrdiff_t convbytes = 1;
4310 if (format_char == '%')
4312 /* General format specifications look like
4314 '%' [field-number] [flags] [field-width] [precision] format
4316 where
4318 field-number ::= [0-9]+ '$'
4319 flags ::= [-+0# ]+
4320 field-width ::= [0-9]+
4321 precision ::= '.' [0-9]*
4323 If present, a field-number specifies the argument number
4324 to substitute. Otherwise, the next argument is taken.
4326 If a field-width is specified, it specifies to which width
4327 the output should be padded with blanks, if the output
4328 string is shorter than field-width.
4330 If precision is specified, it specifies the number of
4331 digits to print after the '.' for floats, or the max.
4332 number of chars to print from a string. */
4334 ptrdiff_t num;
4335 char *num_end;
4336 if (c_isdigit (*format))
4338 num = str2num (format, &num_end);
4339 if (*num_end == '$')
4341 n = num - 1;
4342 format = num_end + 1;
4346 bool minus_flag = false;
4347 bool plus_flag = false;
4348 bool space_flag = false;
4349 bool sharp_flag = false;
4350 bool zero_flag = false;
4352 for (; ; format++)
4354 switch (*format)
4356 case '-': minus_flag = true; continue;
4357 case '+': plus_flag = true; continue;
4358 case ' ': space_flag = true; continue;
4359 case '#': sharp_flag = true; continue;
4360 case '0': zero_flag = true; continue;
4362 break;
4365 /* Ignore flags when sprintf ignores them. */
4366 space_flag &= ! plus_flag;
4367 zero_flag &= ! minus_flag;
4369 num = str2num (format, &num_end);
4370 if (max_bufsize <= num)
4371 string_overflow ();
4372 ptrdiff_t field_width = num;
4374 bool precision_given = *num_end == '.';
4375 ptrdiff_t precision = (precision_given
4376 ? str2num (num_end + 1, &num_end)
4377 : PTRDIFF_MAX);
4378 format = num_end;
4380 if (format == end)
4381 error ("Format string ends in middle of format specifier");
4383 char conversion = *format++;
4384 memset (&discarded[format0 - format_start], 1,
4385 format - format0 - (conversion == '%'));
4386 if (conversion == '%')
4388 new_result = true;
4389 goto copy_char;
4392 ++n;
4393 if (! (n < nargs))
4394 error ("Not enough arguments for format string");
4396 struct info *spec = &info[ispec++];
4397 if (nspec < ispec)
4399 spec->argument = args[n];
4400 spec->intervals = false;
4401 nspec = ispec;
4403 Lisp_Object arg = spec->argument;
4405 /* For 'S', prin1 the argument, and then treat like 's'.
4406 For 's', princ any argument that is not a string or
4407 symbol. But don't do this conversion twice, which might
4408 happen after retrying. */
4409 if ((conversion == 'S'
4410 || (conversion == 's'
4411 && ! STRINGP (arg) && ! SYMBOLP (arg))))
4413 if (EQ (arg, args[n]))
4415 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
4416 spec->argument = arg = Fprin1_to_string (arg, noescape);
4417 if (STRING_MULTIBYTE (arg) && ! multibyte)
4419 multibyte = true;
4420 goto retry;
4423 conversion = 's';
4425 else if (conversion == 'c')
4427 if (INTEGERP (arg) && ! ASCII_CHAR_P (XINT (arg)))
4429 if (!multibyte)
4431 multibyte = true;
4432 goto retry;
4434 spec->argument = arg = Fchar_to_string (arg);
4437 if (!EQ (arg, args[n]))
4438 conversion = 's';
4439 zero_flag = false;
4442 if (SYMBOLP (arg))
4444 spec->argument = arg = SYMBOL_NAME (arg);
4445 if (STRING_MULTIBYTE (arg) && ! multibyte)
4447 multibyte = true;
4448 goto retry;
4452 bool float_conversion
4453 = conversion == 'e' || conversion == 'f' || conversion == 'g';
4455 if (conversion == 's')
4457 if (format == end && format - format_start == 2
4458 && ! string_intervals (args[0]))
4460 val = arg;
4461 goto return_val;
4464 /* handle case (precision[n] >= 0) */
4466 ptrdiff_t prec = -1;
4467 if (precision_given)
4468 prec = precision;
4470 /* lisp_string_width ignores a precision of 0, but GNU
4471 libc functions print 0 characters when the precision
4472 is 0. Imitate libc behavior here. Changing
4473 lisp_string_width is the right thing, and will be
4474 done, but meanwhile we work with it. */
4476 ptrdiff_t width, nbytes;
4477 ptrdiff_t nchars_string;
4478 if (prec == 0)
4479 width = nchars_string = nbytes = 0;
4480 else
4482 ptrdiff_t nch, nby;
4483 width = lisp_string_width (arg, prec, &nch, &nby);
4484 if (prec < 0)
4486 nchars_string = SCHARS (arg);
4487 nbytes = SBYTES (arg);
4489 else
4491 nchars_string = nch;
4492 nbytes = nby;
4496 convbytes = nbytes;
4497 if (convbytes && multibyte && ! STRING_MULTIBYTE (arg))
4498 convbytes = count_size_as_multibyte (SDATA (arg), nbytes);
4500 ptrdiff_t padding
4501 = width < field_width ? field_width - width : 0;
4503 if (max_bufsize - padding <= convbytes)
4504 string_overflow ();
4505 convbytes += padding;
4506 if (convbytes <= buf + bufsize - p)
4508 if (! minus_flag)
4510 memset (p, ' ', padding);
4511 p += padding;
4512 nchars += padding;
4514 spec->start = nchars;
4516 if (p > buf
4517 && multibyte
4518 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4519 && STRING_MULTIBYTE (arg)
4520 && !CHAR_HEAD_P (SREF (arg, 0)))
4521 maybe_combine_byte = true;
4523 p += copy_text (SDATA (arg), (unsigned char *) p,
4524 nbytes,
4525 STRING_MULTIBYTE (arg), multibyte);
4527 nchars += nchars_string;
4529 if (minus_flag)
4531 memset (p, ' ', padding);
4532 p += padding;
4533 nchars += padding;
4535 spec->end = nchars;
4537 /* If this argument has text properties, record where
4538 in the result string it appears. */
4539 if (string_intervals (arg))
4540 spec->intervals = arg_intervals = true;
4542 new_result = true;
4543 continue;
4546 else if (! (conversion == 'c' || conversion == 'd'
4547 || float_conversion || conversion == 'i'
4548 || conversion == 'o' || conversion == 'x'
4549 || conversion == 'X'))
4550 error ("Invalid format operation %%%c",
4551 STRING_CHAR ((unsigned char *) format - 1));
4552 else if (! (INTEGERP (arg) || (FLOATP (arg) && conversion != 'c')))
4553 error ("Format specifier doesn't match argument type");
4554 else
4556 enum
4558 /* Lower bound on the number of bits per
4559 base-FLT_RADIX digit. */
4560 DIG_BITS_LBOUND = FLT_RADIX < 16 ? 1 : 4,
4562 /* 1 if integers should be formatted as long doubles,
4563 because they may be so large that there is a rounding
4564 error when converting them to double, and long doubles
4565 are wider than doubles. */
4566 INT_AS_LDBL = (DIG_BITS_LBOUND * DBL_MANT_DIG < FIXNUM_BITS - 1
4567 && DBL_MANT_DIG < LDBL_MANT_DIG),
4569 /* Maximum precision for a %f conversion such that the
4570 trailing output digit might be nonzero. Any precision
4571 larger than this will not yield useful information. */
4572 USEFUL_PRECISION_MAX =
4573 ((1 - LDBL_MIN_EXP)
4574 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4575 : FLT_RADIX == 16 ? 4
4576 : -1)),
4578 /* Maximum number of bytes generated by any format, if
4579 precision is no more than USEFUL_PRECISION_MAX.
4580 On all practical hosts, %f is the worst case. */
4581 SPRINTF_BUFSIZE =
4582 sizeof "-." + (LDBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4584 /* Length of pM (that is, of pMd without the
4585 trailing "d"). */
4586 pMlen = sizeof pMd - 2
4588 verify (USEFUL_PRECISION_MAX > 0);
4590 /* Avoid undefined behavior in underlying sprintf. */
4591 if (conversion == 'd' || conversion == 'i')
4592 sharp_flag = false;
4594 /* Create the copy of the conversion specification, with
4595 any width and precision removed, with ".*" inserted,
4596 with "L" possibly inserted for floating-point formats,
4597 and with pM inserted for integer formats.
4598 At most two flags F can be specified at once. */
4599 char convspec[sizeof "%FF.*d" + max (INT_AS_LDBL, pMlen)];
4600 char *f = convspec;
4601 *f++ = '%';
4602 /* MINUS_FLAG and ZERO_FLAG are dealt with later. */
4603 *f = '+'; f += plus_flag;
4604 *f = ' '; f += space_flag;
4605 *f = '#'; f += sharp_flag;
4606 *f++ = '.';
4607 *f++ = '*';
4608 if (float_conversion)
4610 if (INT_AS_LDBL)
4612 *f = 'L';
4613 f += INTEGERP (arg);
4616 else if (conversion != 'c')
4618 memcpy (f, pMd, pMlen);
4619 f += pMlen;
4620 zero_flag &= ! precision_given;
4622 *f++ = conversion;
4623 *f = '\0';
4625 int prec = -1;
4626 if (precision_given)
4627 prec = min (precision, USEFUL_PRECISION_MAX);
4629 /* Use sprintf to format this number into sprintf_buf. Omit
4630 padding and excess precision, though, because sprintf limits
4631 output length to INT_MAX.
4633 There are four types of conversion: double, unsigned
4634 char (passed as int), wide signed int, and wide
4635 unsigned int. Treat them separately because the
4636 sprintf ABI is sensitive to which type is passed. Be
4637 careful about integer overflow, NaNs, infinities, and
4638 conversions; for example, the min and max macros are
4639 not suitable here. */
4640 char sprintf_buf[SPRINTF_BUFSIZE];
4641 ptrdiff_t sprintf_bytes;
4642 if (float_conversion)
4644 if (INT_AS_LDBL && INTEGERP (arg))
4646 /* Although long double may have a rounding error if
4647 DIG_BITS_LBOUND * LDBL_MANT_DIG < FIXNUM_BITS - 1,
4648 it is more accurate than plain 'double'. */
4649 long double x = XINT (arg);
4650 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4652 else
4653 sprintf_bytes = sprintf (sprintf_buf, convspec, prec,
4654 XFLOATINT (arg));
4656 else if (conversion == 'c')
4658 /* Don't use sprintf here, as it might mishandle prec. */
4659 sprintf_buf[0] = XINT (arg);
4660 sprintf_bytes = prec != 0;
4661 sprintf_buf[sprintf_bytes] = '\0';
4663 else if (conversion == 'd' || conversion == 'i')
4665 if (INTEGERP (arg))
4667 printmax_t x = XINT (arg);
4668 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4670 else
4672 strcpy (f - pMlen - 1, "f");
4673 double x = XFLOAT_DATA (arg);
4674 sprintf_bytes = sprintf (sprintf_buf, convspec, 0, x);
4675 char c0 = sprintf_buf[0];
4676 bool signedp = ! ('0' <= c0 && c0 <= '9');
4677 prec = min (precision, sprintf_bytes - signedp);
4680 else
4682 /* Don't sign-extend for octal or hex printing. */
4683 uprintmax_t x;
4684 if (INTEGERP (arg))
4685 x = XUINT (arg);
4686 else
4688 double d = XFLOAT_DATA (arg);
4689 double uprintmax = TYPE_MAXIMUM (uprintmax_t);
4690 if (! (0 <= d && d < uprintmax + 1))
4691 xsignal1 (Qoverflow_error, arg);
4692 x = d;
4694 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4697 /* Now the length of the formatted item is known, except it omits
4698 padding and excess precision. Deal with excess precision
4699 first. This happens when the format specifies ridiculously
4700 large precision, or when %d or %i formats a float that would
4701 ordinarily need fewer digits than a specified precision. */
4702 ptrdiff_t excess_precision
4703 = precision_given ? precision - prec : 0;
4704 ptrdiff_t leading_zeros = 0, trailing_zeros = 0;
4705 if (excess_precision)
4707 if (float_conversion)
4709 if ((conversion == 'g' && ! sharp_flag)
4710 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4711 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4712 excess_precision = 0;
4713 else
4715 if (conversion == 'g')
4717 char *dot = strchr (sprintf_buf, '.');
4718 if (!dot)
4719 excess_precision = 0;
4722 trailing_zeros = excess_precision;
4724 else
4725 leading_zeros = excess_precision;
4728 /* Compute the total bytes needed for this item, including
4729 excess precision and padding. */
4730 ptrdiff_t numwidth;
4731 if (INT_ADD_WRAPV (sprintf_bytes, excess_precision, &numwidth))
4732 numwidth = PTRDIFF_MAX;
4733 ptrdiff_t padding
4734 = numwidth < field_width ? field_width - numwidth : 0;
4735 if (max_bufsize - sprintf_bytes <= excess_precision
4736 || max_bufsize - padding <= numwidth)
4737 string_overflow ();
4738 convbytes = numwidth + padding;
4740 if (convbytes <= buf + bufsize - p)
4742 /* Copy the formatted item from sprintf_buf into buf,
4743 inserting padding and excess-precision zeros. */
4745 char *src = sprintf_buf;
4746 char src0 = src[0];
4747 int exponent_bytes = 0;
4748 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4749 int prefix_bytes = (signedp
4750 + ((src[signedp] == '0'
4751 && (src[signedp + 1] == 'x'
4752 || src[signedp + 1] == 'X'))
4753 ? 2 : 0));
4754 if (zero_flag)
4756 unsigned char after_prefix = src[prefix_bytes];
4757 if (0 <= char_hexdigit (after_prefix))
4759 leading_zeros += padding;
4760 padding = 0;
4764 if (excess_precision
4765 && (conversion == 'e' || conversion == 'g'))
4767 char *e = strchr (src, 'e');
4768 if (e)
4769 exponent_bytes = src + sprintf_bytes - e;
4772 spec->start = nchars;
4773 if (! minus_flag)
4775 memset (p, ' ', padding);
4776 p += padding;
4777 nchars += padding;
4780 memcpy (p, src, prefix_bytes);
4781 p += prefix_bytes;
4782 src += prefix_bytes;
4783 memset (p, '0', leading_zeros);
4784 p += leading_zeros;
4785 int significand_bytes
4786 = sprintf_bytes - prefix_bytes - exponent_bytes;
4787 memcpy (p, src, significand_bytes);
4788 p += significand_bytes;
4789 src += significand_bytes;
4790 memset (p, '0', trailing_zeros);
4791 p += trailing_zeros;
4792 memcpy (p, src, exponent_bytes);
4793 p += exponent_bytes;
4795 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4797 if (minus_flag)
4799 memset (p, ' ', padding);
4800 p += padding;
4801 nchars += padding;
4803 spec->end = nchars;
4805 new_result = true;
4806 continue;
4810 else
4812 unsigned char str[MAX_MULTIBYTE_LENGTH];
4814 if ((format_char == '`' || format_char == '\'')
4815 && quoting_style == CURVE_QUOTING_STYLE)
4817 if (! multibyte)
4819 multibyte = true;
4820 goto retry;
4822 convsrc = format_char == '`' ? uLSQM : uRSQM;
4823 convbytes = 3;
4824 new_result = true;
4826 else if (format_char == '`' && quoting_style == STRAIGHT_QUOTING_STYLE)
4828 convsrc = "'";
4829 new_result = true;
4831 else
4833 /* Copy a single character from format to buf. */
4834 if (multibyte_format)
4836 /* Copy a whole multibyte character. */
4837 if (p > buf
4838 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4839 && !CHAR_HEAD_P (format_char))
4840 maybe_combine_byte = true;
4842 while (! CHAR_HEAD_P (*format))
4843 format++;
4845 convbytes = format - format0;
4846 memset (&discarded[format0 + 1 - format_start], 2,
4847 convbytes - 1);
4849 else if (multibyte && !ASCII_CHAR_P (format_char))
4851 int c = BYTE8_TO_CHAR (format_char);
4852 convbytes = CHAR_STRING (c, str);
4853 convsrc = (char *) str;
4854 new_result = true;
4858 copy_char:
4859 if (convbytes <= buf + bufsize - p)
4861 memcpy (p, convsrc, convbytes);
4862 p += convbytes;
4863 nchars++;
4864 continue;
4868 /* There wasn't enough room to store this conversion or single
4869 character. CONVBYTES says how much room is needed. Allocate
4870 enough room (and then some) and do it again. */
4872 ptrdiff_t used = p - buf;
4873 if (max_bufsize - used < convbytes)
4874 string_overflow ();
4875 bufsize = used + convbytes;
4876 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4878 if (buf == initial_buffer)
4880 buf = xmalloc (bufsize);
4881 sa_must_free = true;
4882 buf_save_value_index = SPECPDL_INDEX ();
4883 record_unwind_protect_ptr (xfree, buf);
4884 memcpy (buf, initial_buffer, used);
4886 else
4888 buf = xrealloc (buf, bufsize);
4889 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4892 p = buf + used;
4893 format = format0;
4894 n = n0;
4895 ispec = ispec0;
4898 if (bufsize < p - buf)
4899 emacs_abort ();
4901 if (! new_result)
4903 val = args[0];
4904 goto return_val;
4907 if (maybe_combine_byte)
4908 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4909 val = make_specified_string (buf, nchars, p - buf, multibyte);
4911 /* If the format string has text properties, or any of the string
4912 arguments has text properties, set up text properties of the
4913 result string. */
4915 if (string_intervals (args[0]) || arg_intervals)
4917 /* Add text properties from the format string. */
4918 Lisp_Object len = make_number (SCHARS (args[0]));
4919 Lisp_Object props = text_property_list (args[0], make_number (0),
4920 len, Qnil);
4921 if (CONSP (props))
4923 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4924 ptrdiff_t fieldn = 0;
4926 /* Adjust the bounds of each text property
4927 to the proper start and end in the output string. */
4929 /* Put the positions in PROPS in increasing order, so that
4930 we can do (effectively) one scan through the position
4931 space of the format string. */
4932 props = Fnreverse (props);
4934 /* BYTEPOS is the byte position in the format string,
4935 POSITION is the untranslated char position in it,
4936 TRANSLATED is the translated char position in BUF,
4937 and ARGN is the number of the next arg we will come to. */
4938 for (Lisp_Object list = props; CONSP (list); list = XCDR (list))
4940 Lisp_Object item = XCAR (list);
4942 /* First adjust the property start position. */
4943 ptrdiff_t pos = XINT (XCAR (item));
4945 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4946 up to this position. */
4947 for (; position < pos; bytepos++)
4949 if (! discarded[bytepos])
4950 position++, translated++;
4951 else if (discarded[bytepos] == 1)
4953 position++;
4954 if (fieldn < nspec && translated == info[fieldn].start)
4956 translated += info[fieldn].end - info[fieldn].start;
4957 fieldn++;
4962 XSETCAR (item, make_number (translated));
4964 /* Likewise adjust the property end position. */
4965 pos = XINT (XCAR (XCDR (item)));
4967 for (; position < pos; bytepos++)
4969 if (! discarded[bytepos])
4970 position++, translated++;
4971 else if (discarded[bytepos] == 1)
4973 position++;
4974 if (fieldn < nspec && translated == info[fieldn].start)
4976 translated += info[fieldn].end - info[fieldn].start;
4977 fieldn++;
4982 XSETCAR (XCDR (item), make_number (translated));
4985 add_text_properties_from_list (val, props, make_number (0));
4988 /* Add text properties from arguments. */
4989 if (arg_intervals)
4990 for (ptrdiff_t i = 0; i < nspec; i++)
4991 if (info[i].intervals)
4993 len = make_number (SCHARS (info[i].argument));
4994 Lisp_Object new_len = make_number (info[i].end - info[i].start);
4995 props = text_property_list (info[i].argument,
4996 make_number (0), len, Qnil);
4997 props = extend_property_ranges (props, len, new_len);
4998 /* If successive arguments have properties, be sure that
4999 the value of `composition' property be the copy. */
5000 if (1 < i && info[i - 1].end)
5001 make_composition_value_copy (props);
5002 add_text_properties_from_list (val, props,
5003 make_number (info[i].start));
5007 return_val:
5008 /* If we allocated BUF or INFO with malloc, free it too. */
5009 SAFE_FREE ();
5011 return val;
5014 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
5015 doc: /* Return t if two characters match, optionally ignoring case.
5016 Both arguments must be characters (i.e. integers).
5017 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
5018 (register Lisp_Object c1, Lisp_Object c2)
5020 int i1, i2;
5021 /* Check they're chars, not just integers, otherwise we could get array
5022 bounds violations in downcase. */
5023 CHECK_CHARACTER (c1);
5024 CHECK_CHARACTER (c2);
5026 if (XINT (c1) == XINT (c2))
5027 return Qt;
5028 if (NILP (BVAR (current_buffer, case_fold_search)))
5029 return Qnil;
5031 i1 = XFASTINT (c1);
5032 i2 = XFASTINT (c2);
5034 /* FIXME: It is possible to compare multibyte characters even when
5035 the current buffer is unibyte. Unfortunately this is ambiguous
5036 for characters between 128 and 255, as they could be either
5037 eight-bit raw bytes or Latin-1 characters. Assume the former for
5038 now. See Bug#17011, and also see casefiddle.c's casify_object,
5039 which has a similar problem. */
5040 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
5042 if (SINGLE_BYTE_CHAR_P (i1))
5043 i1 = UNIBYTE_TO_CHAR (i1);
5044 if (SINGLE_BYTE_CHAR_P (i2))
5045 i2 = UNIBYTE_TO_CHAR (i2);
5048 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
5051 /* Transpose the markers in two regions of the current buffer, and
5052 adjust the ones between them if necessary (i.e.: if the regions
5053 differ in size).
5055 START1, END1 are the character positions of the first region.
5056 START1_BYTE, END1_BYTE are the byte positions.
5057 START2, END2 are the character positions of the second region.
5058 START2_BYTE, END2_BYTE are the byte positions.
5060 Traverses the entire marker list of the buffer to do so, adding an
5061 appropriate amount to some, subtracting from some, and leaving the
5062 rest untouched. Most of this is copied from adjust_markers in insdel.c.
5064 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
5066 static void
5067 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
5068 ptrdiff_t start2, ptrdiff_t end2,
5069 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
5070 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
5072 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
5073 register struct Lisp_Marker *marker;
5075 /* Update point as if it were a marker. */
5076 if (PT < start1)
5078 else if (PT < end1)
5079 TEMP_SET_PT_BOTH (PT + (end2 - end1),
5080 PT_BYTE + (end2_byte - end1_byte));
5081 else if (PT < start2)
5082 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
5083 (PT_BYTE + (end2_byte - start2_byte)
5084 - (end1_byte - start1_byte)));
5085 else if (PT < end2)
5086 TEMP_SET_PT_BOTH (PT - (start2 - start1),
5087 PT_BYTE - (start2_byte - start1_byte));
5089 /* We used to adjust the endpoints here to account for the gap, but that
5090 isn't good enough. Even if we assume the caller has tried to move the
5091 gap out of our way, it might still be at start1 exactly, for example;
5092 and that places it `inside' the interval, for our purposes. The amount
5093 of adjustment is nontrivial if there's a `denormalized' marker whose
5094 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
5095 the dirty work to Fmarker_position, below. */
5097 /* The difference between the region's lengths */
5098 diff = (end2 - start2) - (end1 - start1);
5099 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
5101 /* For shifting each marker in a region by the length of the other
5102 region plus the distance between the regions. */
5103 amt1 = (end2 - start2) + (start2 - end1);
5104 amt2 = (end1 - start1) + (start2 - end1);
5105 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
5106 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
5108 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
5110 mpos = marker->bytepos;
5111 if (mpos >= start1_byte && mpos < end2_byte)
5113 if (mpos < end1_byte)
5114 mpos += amt1_byte;
5115 else if (mpos < start2_byte)
5116 mpos += diff_byte;
5117 else
5118 mpos -= amt2_byte;
5119 marker->bytepos = mpos;
5121 mpos = marker->charpos;
5122 if (mpos >= start1 && mpos < end2)
5124 if (mpos < end1)
5125 mpos += amt1;
5126 else if (mpos < start2)
5127 mpos += diff;
5128 else
5129 mpos -= amt2;
5131 marker->charpos = mpos;
5135 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5,
5136 "(if (< (length mark-ring) 2)\
5137 (error \"Other region must be marked before transposing two regions\")\
5138 (let* ((num (if current-prefix-arg\
5139 (prefix-numeric-value current-prefix-arg)\
5140 0))\
5141 (ring-length (length mark-ring))\
5142 (eltnum (mod num ring-length))\
5143 (eltnum2 (mod (1+ num) ring-length)))\
5144 (list (point) (mark) (elt mark-ring eltnum) (elt mark-ring eltnum2))))",
5145 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
5146 The regions should not be overlapping, because the size of the buffer is
5147 never changed in a transposition.
5149 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
5150 any markers that happen to be located in the regions.
5152 Transposing beyond buffer boundaries is an error.
5154 Interactively, STARTR1 and ENDR1 are point and mark; STARTR2 and ENDR2
5155 are the last two marks pushed to the mark ring; LEAVE-MARKERS is nil.
5156 If a prefix argument N is given, STARTR2 and ENDR2 are the two
5157 successive marks N entries back in the mark ring. A negative prefix
5158 argument instead counts forward from the oldest mark in the mark
5159 ring. */)
5160 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
5162 register ptrdiff_t start1, end1, start2, end2;
5163 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
5164 ptrdiff_t gap, len1, len_mid, len2;
5165 unsigned char *start1_addr, *start2_addr, *temp;
5167 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
5168 Lisp_Object buf;
5170 XSETBUFFER (buf, current_buffer);
5171 cur_intv = buffer_intervals (current_buffer);
5173 validate_region (&startr1, &endr1);
5174 validate_region (&startr2, &endr2);
5176 start1 = XFASTINT (startr1);
5177 end1 = XFASTINT (endr1);
5178 start2 = XFASTINT (startr2);
5179 end2 = XFASTINT (endr2);
5180 gap = GPT;
5182 /* Swap the regions if they're reversed. */
5183 if (start2 < end1)
5185 register ptrdiff_t glumph = start1;
5186 start1 = start2;
5187 start2 = glumph;
5188 glumph = end1;
5189 end1 = end2;
5190 end2 = glumph;
5193 len1 = end1 - start1;
5194 len2 = end2 - start2;
5196 if (start2 < end1)
5197 error ("Transposed regions overlap");
5198 /* Nothing to change for adjacent regions with one being empty */
5199 else if ((start1 == end1 || start2 == end2) && end1 == start2)
5200 return Qnil;
5202 /* The possibilities are:
5203 1. Adjacent (contiguous) regions, or separate but equal regions
5204 (no, really equal, in this case!), or
5205 2. Separate regions of unequal size.
5207 The worst case is usually No. 2. It means that (aside from
5208 potential need for getting the gap out of the way), there also
5209 needs to be a shifting of the text between the two regions. So
5210 if they are spread far apart, we are that much slower... sigh. */
5212 /* It must be pointed out that the really studly thing to do would
5213 be not to move the gap at all, but to leave it in place and work
5214 around it if necessary. This would be extremely efficient,
5215 especially considering that people are likely to do
5216 transpositions near where they are working interactively, which
5217 is exactly where the gap would be found. However, such code
5218 would be much harder to write and to read. So, if you are
5219 reading this comment and are feeling squirrely, by all means have
5220 a go! I just didn't feel like doing it, so I will simply move
5221 the gap the minimum distance to get it out of the way, and then
5222 deal with an unbroken array. */
5224 start1_byte = CHAR_TO_BYTE (start1);
5225 end2_byte = CHAR_TO_BYTE (end2);
5227 /* Make sure the gap won't interfere, by moving it out of the text
5228 we will operate on. */
5229 if (start1 < gap && gap < end2)
5231 if (gap - start1 < end2 - gap)
5232 move_gap_both (start1, start1_byte);
5233 else
5234 move_gap_both (end2, end2_byte);
5237 start2_byte = CHAR_TO_BYTE (start2);
5238 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
5239 len2_byte = end2_byte - start2_byte;
5241 #ifdef BYTE_COMBINING_DEBUG
5242 if (end1 == start2)
5244 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
5245 len2_byte, start1, start1_byte)
5246 || count_combining_before (BYTE_POS_ADDR (start1_byte),
5247 len1_byte, end2, start2_byte + len2_byte)
5248 || count_combining_after (BYTE_POS_ADDR (start1_byte),
5249 len1_byte, end2, start2_byte + len2_byte))
5250 emacs_abort ();
5252 else
5254 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
5255 len2_byte, start1, start1_byte)
5256 || count_combining_before (BYTE_POS_ADDR (start1_byte),
5257 len1_byte, start2, start2_byte)
5258 || count_combining_after (BYTE_POS_ADDR (start2_byte),
5259 len2_byte, end1, start1_byte + len1_byte)
5260 || count_combining_after (BYTE_POS_ADDR (start1_byte),
5261 len1_byte, end2, start2_byte + len2_byte))
5262 emacs_abort ();
5264 #endif
5266 /* Hmmm... how about checking to see if the gap is large
5267 enough to use as the temporary storage? That would avoid an
5268 allocation... interesting. Later, don't fool with it now. */
5270 /* Working without memmove, for portability (sigh), so must be
5271 careful of overlapping subsections of the array... */
5273 if (end1 == start2) /* adjacent regions */
5275 modify_text (start1, end2);
5276 record_change (start1, len1 + len2);
5278 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5279 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5280 /* Don't use Fset_text_properties: that can cause GC, which can
5281 clobber objects stored in the tmp_intervals. */
5282 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5283 if (tmp_interval3)
5284 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5286 USE_SAFE_ALLOCA;
5288 /* First region smaller than second. */
5289 if (len1_byte < len2_byte)
5291 temp = SAFE_ALLOCA (len2_byte);
5293 /* Don't precompute these addresses. We have to compute them
5294 at the last minute, because the relocating allocator might
5295 have moved the buffer around during the xmalloc. */
5296 start1_addr = BYTE_POS_ADDR (start1_byte);
5297 start2_addr = BYTE_POS_ADDR (start2_byte);
5299 memcpy (temp, start2_addr, len2_byte);
5300 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
5301 memcpy (start1_addr, temp, len2_byte);
5303 else
5304 /* First region not smaller than second. */
5306 temp = SAFE_ALLOCA (len1_byte);
5307 start1_addr = BYTE_POS_ADDR (start1_byte);
5308 start2_addr = BYTE_POS_ADDR (start2_byte);
5309 memcpy (temp, start1_addr, len1_byte);
5310 memcpy (start1_addr, start2_addr, len2_byte);
5311 memcpy (start1_addr + len2_byte, temp, len1_byte);
5314 SAFE_FREE ();
5315 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
5316 len1, current_buffer, 0);
5317 graft_intervals_into_buffer (tmp_interval2, start1,
5318 len2, current_buffer, 0);
5319 update_compositions (start1, start1 + len2, CHECK_BORDER);
5320 update_compositions (start1 + len2, end2, CHECK_TAIL);
5322 /* Non-adjacent regions, because end1 != start2, bleagh... */
5323 else
5325 len_mid = start2_byte - (start1_byte + len1_byte);
5327 if (len1_byte == len2_byte)
5328 /* Regions are same size, though, how nice. */
5330 USE_SAFE_ALLOCA;
5332 modify_text (start1, end2);
5333 record_change (start1, len1);
5334 record_change (start2, len2);
5335 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5336 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5338 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
5339 if (tmp_interval3)
5340 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
5342 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
5343 if (tmp_interval3)
5344 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
5346 temp = SAFE_ALLOCA (len1_byte);
5347 start1_addr = BYTE_POS_ADDR (start1_byte);
5348 start2_addr = BYTE_POS_ADDR (start2_byte);
5349 memcpy (temp, start1_addr, len1_byte);
5350 memcpy (start1_addr, start2_addr, len2_byte);
5351 memcpy (start2_addr, temp, len1_byte);
5352 SAFE_FREE ();
5354 graft_intervals_into_buffer (tmp_interval1, start2,
5355 len1, current_buffer, 0);
5356 graft_intervals_into_buffer (tmp_interval2, start1,
5357 len2, current_buffer, 0);
5360 else if (len1_byte < len2_byte) /* Second region larger than first */
5361 /* Non-adjacent & unequal size, area between must also be shifted. */
5363 USE_SAFE_ALLOCA;
5365 modify_text (start1, end2);
5366 record_change (start1, (end2 - start1));
5367 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5368 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5369 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5371 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5372 if (tmp_interval3)
5373 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5375 /* holds region 2 */
5376 temp = SAFE_ALLOCA (len2_byte);
5377 start1_addr = BYTE_POS_ADDR (start1_byte);
5378 start2_addr = BYTE_POS_ADDR (start2_byte);
5379 memcpy (temp, start2_addr, len2_byte);
5380 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
5381 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5382 memcpy (start1_addr, temp, len2_byte);
5383 SAFE_FREE ();
5385 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5386 len1, current_buffer, 0);
5387 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5388 len_mid, current_buffer, 0);
5389 graft_intervals_into_buffer (tmp_interval2, start1,
5390 len2, current_buffer, 0);
5392 else
5393 /* Second region smaller than first. */
5395 USE_SAFE_ALLOCA;
5397 record_change (start1, (end2 - start1));
5398 modify_text (start1, end2);
5400 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5401 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5402 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5404 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5405 if (tmp_interval3)
5406 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5408 /* holds region 1 */
5409 temp = SAFE_ALLOCA (len1_byte);
5410 start1_addr = BYTE_POS_ADDR (start1_byte);
5411 start2_addr = BYTE_POS_ADDR (start2_byte);
5412 memcpy (temp, start1_addr, len1_byte);
5413 memcpy (start1_addr, start2_addr, len2_byte);
5414 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5415 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
5416 SAFE_FREE ();
5418 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5419 len1, current_buffer, 0);
5420 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5421 len_mid, current_buffer, 0);
5422 graft_intervals_into_buffer (tmp_interval2, start1,
5423 len2, current_buffer, 0);
5426 update_compositions (start1, start1 + len2, CHECK_BORDER);
5427 update_compositions (end2 - len1, end2, CHECK_BORDER);
5430 /* When doing multiple transpositions, it might be nice
5431 to optimize this. Perhaps the markers in any one buffer
5432 should be organized in some sorted data tree. */
5433 if (NILP (leave_markers))
5435 transpose_markers (start1, end1, start2, end2,
5436 start1_byte, start1_byte + len1_byte,
5437 start2_byte, start2_byte + len2_byte);
5438 fix_start_end_in_overlays (start1, end2);
5440 else
5442 /* The character positions of the markers remain intact, but we
5443 still need to update their byte positions, because the
5444 transposed regions might include multibyte sequences which
5445 make some original byte positions of the markers invalid. */
5446 adjust_markers_bytepos (start1, start1_byte, end2, end2_byte, 0);
5449 signal_after_change (start1, end2 - start1, end2 - start1);
5450 return Qnil;
5454 void
5455 syms_of_editfns (void)
5457 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
5458 DEFSYM (Qwall, "wall");
5460 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
5461 doc: /* Non-nil means text motion commands don't notice fields. */);
5462 Vinhibit_field_text_motion = Qnil;
5464 DEFVAR_LISP ("buffer-access-fontify-functions",
5465 Vbuffer_access_fontify_functions,
5466 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
5467 Each function is called with two arguments which specify the range
5468 of the buffer being accessed. */);
5469 Vbuffer_access_fontify_functions = Qnil;
5472 Lisp_Object obuf;
5473 obuf = Fcurrent_buffer ();
5474 /* Do this here, because init_buffer_once is too early--it won't work. */
5475 Fset_buffer (Vprin1_to_string_buffer);
5476 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5477 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions), Qnil);
5478 Fset_buffer (obuf);
5481 DEFVAR_LISP ("buffer-access-fontified-property",
5482 Vbuffer_access_fontified_property,
5483 doc: /* Property which (if non-nil) indicates text has been fontified.
5484 `buffer-substring' need not call the `buffer-access-fontify-functions'
5485 functions if all the text being accessed has this property. */);
5486 Vbuffer_access_fontified_property = Qnil;
5488 DEFVAR_LISP ("system-name", Vsystem_name,
5489 doc: /* The host name of the machine Emacs is running on. */);
5490 Vsystem_name = cached_system_name = Qnil;
5492 DEFVAR_LISP ("user-full-name", Vuser_full_name,
5493 doc: /* The full name of the user logged in. */);
5495 DEFVAR_LISP ("user-login-name", Vuser_login_name,
5496 doc: /* The user's name, taken from environment variables if possible. */);
5497 Vuser_login_name = Qnil;
5499 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
5500 doc: /* The user's name, based upon the real uid only. */);
5502 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
5503 doc: /* The release of the operating system Emacs is running on. */);
5505 defsubr (&Spropertize);
5506 defsubr (&Schar_equal);
5507 defsubr (&Sgoto_char);
5508 defsubr (&Sstring_to_char);
5509 defsubr (&Schar_to_string);
5510 defsubr (&Sbyte_to_string);
5511 defsubr (&Sbuffer_substring);
5512 defsubr (&Sbuffer_substring_no_properties);
5513 defsubr (&Sbuffer_string);
5514 defsubr (&Sget_pos_property);
5516 defsubr (&Spoint_marker);
5517 defsubr (&Smark_marker);
5518 defsubr (&Spoint);
5519 defsubr (&Sregion_beginning);
5520 defsubr (&Sregion_end);
5522 /* Symbol for the text property used to mark fields. */
5523 DEFSYM (Qfield, "field");
5525 /* A special value for Qfield properties. */
5526 DEFSYM (Qboundary, "boundary");
5528 defsubr (&Sfield_beginning);
5529 defsubr (&Sfield_end);
5530 defsubr (&Sfield_string);
5531 defsubr (&Sfield_string_no_properties);
5532 defsubr (&Sdelete_field);
5533 defsubr (&Sconstrain_to_field);
5535 defsubr (&Sline_beginning_position);
5536 defsubr (&Sline_end_position);
5538 defsubr (&Ssave_excursion);
5539 defsubr (&Ssave_current_buffer);
5541 defsubr (&Sbuffer_size);
5542 defsubr (&Spoint_max);
5543 defsubr (&Spoint_min);
5544 defsubr (&Spoint_min_marker);
5545 defsubr (&Spoint_max_marker);
5546 defsubr (&Sgap_position);
5547 defsubr (&Sgap_size);
5548 defsubr (&Sposition_bytes);
5549 defsubr (&Sbyte_to_position);
5551 defsubr (&Sbobp);
5552 defsubr (&Seobp);
5553 defsubr (&Sbolp);
5554 defsubr (&Seolp);
5555 defsubr (&Sfollowing_char);
5556 defsubr (&Sprevious_char);
5557 defsubr (&Schar_after);
5558 defsubr (&Schar_before);
5559 defsubr (&Sinsert);
5560 defsubr (&Sinsert_before_markers);
5561 defsubr (&Sinsert_and_inherit);
5562 defsubr (&Sinsert_and_inherit_before_markers);
5563 defsubr (&Sinsert_char);
5564 defsubr (&Sinsert_byte);
5566 defsubr (&Suser_login_name);
5567 defsubr (&Suser_real_login_name);
5568 defsubr (&Suser_uid);
5569 defsubr (&Suser_real_uid);
5570 defsubr (&Sgroup_gid);
5571 defsubr (&Sgroup_real_gid);
5572 defsubr (&Suser_full_name);
5573 defsubr (&Semacs_pid);
5574 defsubr (&Scurrent_time);
5575 defsubr (&Stime_add);
5576 defsubr (&Stime_subtract);
5577 defsubr (&Stime_less_p);
5578 defsubr (&Sget_internal_run_time);
5579 defsubr (&Sformat_time_string);
5580 defsubr (&Sfloat_time);
5581 defsubr (&Sdecode_time);
5582 defsubr (&Sencode_time);
5583 defsubr (&Scurrent_time_string);
5584 defsubr (&Scurrent_time_zone);
5585 defsubr (&Sset_time_zone_rule);
5586 defsubr (&Ssystem_name);
5587 defsubr (&Smessage);
5588 defsubr (&Smessage_box);
5589 defsubr (&Smessage_or_box);
5590 defsubr (&Scurrent_message);
5591 defsubr (&Sformat);
5592 defsubr (&Sformat_message);
5594 defsubr (&Sinsert_buffer_substring);
5595 defsubr (&Scompare_buffer_substrings);
5596 defsubr (&Sreplace_buffer_contents);
5597 defsubr (&Ssubst_char_in_region);
5598 defsubr (&Stranslate_region_internal);
5599 defsubr (&Sdelete_region);
5600 defsubr (&Sdelete_and_extract_region);
5601 defsubr (&Swiden);
5602 defsubr (&Snarrow_to_region);
5603 defsubr (&Ssave_restriction);
5604 defsubr (&Stranspose_regions);