Improve module function terminology
[emacs.git] / src / editfns.c
blob75eb75a729317e83e7d76a42774154a396a28f58
1 /* Lisp functions pertaining to editing. -*- coding: utf-8 -*-
3 Copyright (C) 1985-1987, 1989, 1993-2017 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 <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
25 #ifdef HAVE_PWD_H
26 #include <pwd.h>
27 #include <grp.h>
28 #endif
30 #include <unistd.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
34 #endif
36 #include "lisp.h"
38 /* systime.h includes <sys/time.h> which, on some systems, is required
39 for <sys/resource.h>; thus systime.h must be included before
40 <sys/resource.h> */
41 #include "systime.h"
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
47 #include <errno.h>
48 #include <float.h>
49 #include <limits.h>
51 #include <intprops.h>
52 #include <stdlib.h>
53 #include <strftime.h>
54 #include <verify.h>
56 #include "composite.h"
57 #include "intervals.h"
58 #include "character.h"
59 #include "buffer.h"
60 #include "coding.h"
61 #include "window.h"
62 #include "blockinput.h"
64 #define TM_YEAR_BASE 1900
66 #ifdef WINDOWSNT
67 extern Lisp_Object w32_get_internal_run_time (void);
68 #endif
70 static struct lisp_time lisp_time_struct (Lisp_Object, int *);
71 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
72 Lisp_Object, struct tm *);
73 static long int tm_gmtoff (struct tm *);
74 static int tm_diff (struct tm *, struct tm *);
75 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
76 static Lisp_Object styled_format (ptrdiff_t, Lisp_Object *, bool);
78 #ifndef HAVE_TM_GMTOFF
79 # define HAVE_TM_GMTOFF false
80 #endif
82 enum { tzeqlen = sizeof "TZ=" - 1 };
84 /* Time zones equivalent to current local time and to UTC, respectively. */
85 static timezone_t local_tz;
86 static timezone_t const utc_tz = 0;
88 /* The cached value of Vsystem_name. This is used only to compare it
89 to Vsystem_name, so it need not be visible to the GC. */
90 static Lisp_Object cached_system_name;
92 static void
93 init_and_cache_system_name (void)
95 init_system_name ();
96 cached_system_name = Vsystem_name;
99 static struct tm *
100 emacs_localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
102 tm = localtime_rz (tz, t, tm);
103 if (!tm && errno == ENOMEM)
104 memory_full (SIZE_MAX);
105 return tm;
108 static time_t
109 emacs_mktime_z (timezone_t tz, struct tm *tm)
111 errno = 0;
112 time_t t = mktime_z (tz, tm);
113 if (t == (time_t) -1 && errno == ENOMEM)
114 memory_full (SIZE_MAX);
115 return t;
118 /* Allocate a timezone, signaling on failure. */
119 static timezone_t
120 xtzalloc (char const *name)
122 timezone_t tz = tzalloc (name);
123 if (!tz)
124 memory_full (SIZE_MAX);
125 return tz;
128 /* Free a timezone, except do not free the time zone for local time.
129 Freeing utc_tz is also a no-op. */
130 static void
131 xtzfree (timezone_t tz)
133 if (tz != local_tz)
134 tzfree (tz);
137 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
138 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
139 If SETTZ, set Emacs local time to the time zone rule; otherwise,
140 the caller should eventually pass the returned value to xtzfree. */
141 static timezone_t
142 tzlookup (Lisp_Object zone, bool settz)
144 static char const tzbuf_format[] = "<%+.*"pI"d>%s%"pI"d:%02d:%02d";
145 char const *trailing_tzbuf_format = tzbuf_format + sizeof "<%+.*"pI"d" - 1;
146 char tzbuf[sizeof tzbuf_format + 2 * INT_STRLEN_BOUND (EMACS_INT)];
147 char const *zone_string;
148 timezone_t new_tz;
150 if (NILP (zone))
151 return local_tz;
152 else if (EQ (zone, Qt))
154 zone_string = "UTC0";
155 new_tz = utc_tz;
157 else
159 bool plain_integer = INTEGERP (zone);
161 if (EQ (zone, Qwall))
162 zone_string = 0;
163 else if (STRINGP (zone))
164 zone_string = SSDATA (ENCODE_SYSTEM (zone));
165 else if (plain_integer || (CONSP (zone) && INTEGERP (XCAR (zone))
166 && CONSP (XCDR (zone))))
168 Lisp_Object abbr;
169 if (!plain_integer)
171 abbr = XCAR (XCDR (zone));
172 zone = XCAR (zone);
175 EMACS_INT abszone = eabs (XINT (zone)), hour = abszone / (60 * 60);
176 int hour_remainder = abszone % (60 * 60);
177 int min = hour_remainder / 60, sec = hour_remainder % 60;
179 if (plain_integer)
181 int prec = 2;
182 EMACS_INT numzone = hour;
183 if (hour_remainder != 0)
185 prec += 2, numzone = 100 * numzone + min;
186 if (sec != 0)
187 prec += 2, numzone = 100 * numzone + sec;
189 sprintf (tzbuf, tzbuf_format, prec, numzone,
190 &"-"[XINT (zone) < 0], hour, min, sec);
191 zone_string = tzbuf;
193 else
195 AUTO_STRING (leading, "<");
196 AUTO_STRING_WITH_LEN (trailing, tzbuf,
197 sprintf (tzbuf, trailing_tzbuf_format,
198 &"-"[XINT (zone) < 0],
199 hour, min, sec));
200 zone_string = SSDATA (concat3 (leading, ENCODE_SYSTEM (abbr),
201 trailing));
204 else
205 xsignal2 (Qerror, build_string ("Invalid time zone specification"),
206 zone);
207 new_tz = xtzalloc (zone_string);
210 if (settz)
212 block_input ();
213 emacs_setenv_TZ (zone_string);
214 tzset ();
215 timezone_t old_tz = local_tz;
216 local_tz = new_tz;
217 tzfree (old_tz);
218 unblock_input ();
221 return new_tz;
224 void
225 init_editfns (bool dumping)
227 #if !defined CANNOT_DUMP
228 /* A valid but unlikely setting for the TZ environment variable.
229 It is OK (though a bit slower) if the user chooses this value. */
230 static char dump_tz_string[] = "TZ=UtC0";
231 #endif
233 const char *user_name;
234 register char *p;
235 struct passwd *pw; /* password entry for the current user */
236 Lisp_Object tem;
238 /* Set up system_name even when dumping. */
239 init_and_cache_system_name ();
241 #ifndef CANNOT_DUMP
242 /* When just dumping out, set the time zone to a known unlikely value
243 and skip the rest of this function. */
244 if (dumping)
246 xputenv (dump_tz_string);
247 tzset ();
248 return;
250 #endif
252 char *tz = getenv ("TZ");
254 #if !defined CANNOT_DUMP
255 /* If the execution TZ happens to be the same as the dump TZ,
256 change it to some other value and then change it back,
257 to force the underlying implementation to reload the TZ info.
258 This is needed on implementations that load TZ info from files,
259 since the TZ file contents may differ between dump and execution. */
260 if (tz && strcmp (tz, &dump_tz_string[tzeqlen]) == 0)
262 ++*tz;
263 tzset ();
264 --*tz;
266 #endif
268 /* Set the time zone rule now, so that the call to putenv is done
269 before multiple threads are active. */
270 tzlookup (tz ? build_string (tz) : Qwall, true);
272 pw = getpwuid (getuid ());
273 #ifdef MSDOS
274 /* We let the real user name default to "root" because that's quite
275 accurate on MS-DOS and because it lets Emacs find the init file.
276 (The DVX libraries override the Djgpp libraries here.) */
277 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
278 #else
279 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
280 #endif
282 /* Get the effective user name, by consulting environment variables,
283 or the effective uid if those are unset. */
284 user_name = getenv ("LOGNAME");
285 if (!user_name)
286 #ifdef WINDOWSNT
287 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
288 #else /* WINDOWSNT */
289 user_name = getenv ("USER");
290 #endif /* WINDOWSNT */
291 if (!user_name)
293 pw = getpwuid (geteuid ());
294 user_name = pw ? pw->pw_name : "unknown";
296 Vuser_login_name = build_string (user_name);
298 /* If the user name claimed in the environment vars differs from
299 the real uid, use the claimed name to find the full name. */
300 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
301 if (! NILP (tem))
302 tem = Vuser_login_name;
303 else
305 uid_t euid = geteuid ();
306 tem = make_fixnum_or_float (euid);
308 Vuser_full_name = Fuser_full_name (tem);
310 p = getenv ("NAME");
311 if (p)
312 Vuser_full_name = build_string (p);
313 else if (NILP (Vuser_full_name))
314 Vuser_full_name = build_string ("unknown");
316 #ifdef HAVE_SYS_UTSNAME_H
318 struct utsname uts;
319 uname (&uts);
320 Voperating_system_release = build_string (uts.release);
322 #else
323 Voperating_system_release = Qnil;
324 #endif
327 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
328 doc: /* Convert arg CHAR to a string containing that character.
329 usage: (char-to-string CHAR) */)
330 (Lisp_Object character)
332 int c, len;
333 unsigned char str[MAX_MULTIBYTE_LENGTH];
335 CHECK_CHARACTER (character);
336 c = XFASTINT (character);
338 len = CHAR_STRING (c, str);
339 return make_string_from_bytes ((char *) str, 1, len);
342 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
343 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
344 (Lisp_Object byte)
346 unsigned char b;
347 CHECK_NUMBER (byte);
348 if (XINT (byte) < 0 || XINT (byte) > 255)
349 error ("Invalid byte");
350 b = XINT (byte);
351 return make_string_from_bytes ((char *) &b, 1, 1);
354 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
355 doc: /* Return the first character in STRING. */)
356 (register Lisp_Object string)
358 register Lisp_Object val;
359 CHECK_STRING (string);
360 if (SCHARS (string))
362 if (STRING_MULTIBYTE (string))
363 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
364 else
365 XSETFASTINT (val, SREF (string, 0));
367 else
368 XSETFASTINT (val, 0);
369 return val;
372 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
373 doc: /* Return value of point, as an integer.
374 Beginning of buffer is position (point-min). */)
375 (void)
377 Lisp_Object temp;
378 XSETFASTINT (temp, PT);
379 return temp;
382 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
383 doc: /* Return value of point, as a marker object. */)
384 (void)
386 return build_marker (current_buffer, PT, PT_BYTE);
389 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
390 doc: /* Set point to POSITION, a number or marker.
391 Beginning of buffer is position (point-min), end is (point-max).
393 The return value is POSITION. */)
394 (register Lisp_Object position)
396 if (MARKERP (position))
397 set_point_from_marker (position);
398 else if (INTEGERP (position))
399 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
400 else
401 wrong_type_argument (Qinteger_or_marker_p, position);
402 return position;
406 /* Return the start or end position of the region.
407 BEGINNINGP means return the start.
408 If there is no region active, signal an error. */
410 static Lisp_Object
411 region_limit (bool beginningp)
413 Lisp_Object m;
415 if (!NILP (Vtransient_mark_mode)
416 && NILP (Vmark_even_if_inactive)
417 && NILP (BVAR (current_buffer, mark_active)))
418 xsignal0 (Qmark_inactive);
420 m = Fmarker_position (BVAR (current_buffer, mark));
421 if (NILP (m))
422 error ("The mark is not set now, so there is no region");
424 /* Clip to the current narrowing (bug#11770). */
425 return make_number ((PT < XFASTINT (m)) == beginningp
426 ? PT
427 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
430 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
431 doc: /* Return the integer value of point or mark, whichever is smaller. */)
432 (void)
434 return region_limit (1);
437 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
438 doc: /* Return the integer value of point or mark, whichever is larger. */)
439 (void)
441 return region_limit (0);
444 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
445 doc: /* Return this buffer's mark, as a marker object.
446 Watch out! Moving this marker changes the mark position.
447 If you set the marker not to point anywhere, the buffer will have no mark. */)
448 (void)
450 return BVAR (current_buffer, mark);
454 /* Find all the overlays in the current buffer that touch position POS.
455 Return the number found, and store them in a vector in VEC
456 of length LEN. */
458 static ptrdiff_t
459 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
461 Lisp_Object overlay, start, end;
462 struct Lisp_Overlay *tail;
463 ptrdiff_t startpos, endpos;
464 ptrdiff_t idx = 0;
466 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
468 XSETMISC (overlay, tail);
470 end = OVERLAY_END (overlay);
471 endpos = OVERLAY_POSITION (end);
472 if (endpos < pos)
473 break;
474 start = OVERLAY_START (overlay);
475 startpos = OVERLAY_POSITION (start);
476 if (startpos <= pos)
478 if (idx < len)
479 vec[idx] = overlay;
480 /* Keep counting overlays even if we can't return them all. */
481 idx++;
485 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
487 XSETMISC (overlay, tail);
489 start = OVERLAY_START (overlay);
490 startpos = OVERLAY_POSITION (start);
491 if (pos < startpos)
492 break;
493 end = OVERLAY_END (overlay);
494 endpos = OVERLAY_POSITION (end);
495 if (pos <= endpos)
497 if (idx < len)
498 vec[idx] = overlay;
499 idx++;
503 return idx;
506 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
507 doc: /* Return the value of POSITION's property PROP, in OBJECT.
508 Almost identical to `get-char-property' except for the following difference:
509 Whereas `get-char-property' returns the property of the char at (i.e. right
510 after) POSITION, this pays attention to properties's stickiness and overlays's
511 advancement settings, in order to find the property of POSITION itself,
512 i.e. the property that a char would inherit if it were inserted
513 at POSITION. */)
514 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
516 CHECK_NUMBER_COERCE_MARKER (position);
518 if (NILP (object))
519 XSETBUFFER (object, current_buffer);
520 else if (WINDOWP (object))
521 object = XWINDOW (object)->contents;
523 if (!BUFFERP (object))
524 /* pos-property only makes sense in buffers right now, since strings
525 have no overlays and no notion of insertion for which stickiness
526 could be obeyed. */
527 return Fget_text_property (position, prop, object);
528 else
530 EMACS_INT posn = XINT (position);
531 ptrdiff_t noverlays;
532 Lisp_Object *overlay_vec, tem;
533 struct buffer *obuf = current_buffer;
534 USE_SAFE_ALLOCA;
536 set_buffer_temp (XBUFFER (object));
538 /* First try with room for 40 overlays. */
539 Lisp_Object overlay_vecbuf[40];
540 noverlays = ARRAYELTS (overlay_vecbuf);
541 overlay_vec = overlay_vecbuf;
542 noverlays = overlays_around (posn, overlay_vec, noverlays);
544 /* If there are more than 40,
545 make enough space for all, and try again. */
546 if (ARRAYELTS (overlay_vecbuf) < noverlays)
548 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
549 noverlays = overlays_around (posn, overlay_vec, noverlays);
551 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
553 set_buffer_temp (obuf);
555 /* Now check the overlays in order of decreasing priority. */
556 while (--noverlays >= 0)
558 Lisp_Object ol = overlay_vec[noverlays];
559 tem = Foverlay_get (ol, prop);
560 if (!NILP (tem))
562 /* Check the overlay is indeed active at point. */
563 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
564 if ((OVERLAY_POSITION (start) == posn
565 && XMARKER (start)->insertion_type == 1)
566 || (OVERLAY_POSITION (finish) == posn
567 && XMARKER (finish)->insertion_type == 0))
568 ; /* The overlay will not cover a char inserted at point. */
569 else
571 SAFE_FREE ();
572 return tem;
576 SAFE_FREE ();
578 { /* Now check the text properties. */
579 int stickiness = text_property_stickiness (prop, position, object);
580 if (stickiness > 0)
581 return Fget_text_property (position, prop, object);
582 else if (stickiness < 0
583 && XINT (position) > BUF_BEGV (XBUFFER (object)))
584 return Fget_text_property (make_number (XINT (position) - 1),
585 prop, object);
586 else
587 return Qnil;
592 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
593 the value of point is used instead. If BEG or END is null,
594 means don't store the beginning or end of the field.
596 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
597 results; they do not effect boundary behavior.
599 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
600 position of a field, then the beginning of the previous field is
601 returned instead of the beginning of POS's field (since the end of a
602 field is actually also the beginning of the next input field, this
603 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
604 non-nil case, if two fields are separated by a field with the special
605 value `boundary', and POS lies within it, then the two separated
606 fields are considered to be adjacent, and POS between them, when
607 finding the beginning and ending of the "merged" field.
609 Either BEG or END may be 0, in which case the corresponding value
610 is not stored. */
612 static void
613 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
614 Lisp_Object beg_limit,
615 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
617 /* Fields right before and after the point. */
618 Lisp_Object before_field, after_field;
619 /* True if POS counts as the start of a field. */
620 bool at_field_start = 0;
621 /* True if POS counts as the end of a field. */
622 bool at_field_end = 0;
624 if (NILP (pos))
625 XSETFASTINT (pos, PT);
626 else
627 CHECK_NUMBER_COERCE_MARKER (pos);
629 after_field
630 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
631 before_field
632 = (XFASTINT (pos) > BEGV
633 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
634 Qfield, Qnil, NULL)
635 /* Using nil here would be a more obvious choice, but it would
636 fail when the buffer starts with a non-sticky field. */
637 : after_field);
639 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
640 and POS is at beginning of a field, which can also be interpreted
641 as the end of the previous field. Note that the case where if
642 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
643 more natural one; then we avoid treating the beginning of a field
644 specially. */
645 if (NILP (merge_at_boundary))
647 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
648 if (!EQ (field, after_field))
649 at_field_end = 1;
650 if (!EQ (field, before_field))
651 at_field_start = 1;
652 if (NILP (field) && at_field_start && at_field_end)
653 /* If an inserted char would have a nil field while the surrounding
654 text is non-nil, we're probably not looking at a
655 zero-length field, but instead at a non-nil field that's
656 not intended for editing (such as comint's prompts). */
657 at_field_end = at_field_start = 0;
660 /* Note about special `boundary' fields:
662 Consider the case where the point (`.') is between the fields `x' and `y':
664 xxxx.yyyy
666 In this situation, if merge_at_boundary is non-nil, consider the
667 `x' and `y' fields as forming one big merged field, and so the end
668 of the field is the end of `y'.
670 However, if `x' and `y' are separated by a special `boundary' field
671 (a field with a `field' char-property of 'boundary), then ignore
672 this special field when merging adjacent fields. Here's the same
673 situation, but with a `boundary' field between the `x' and `y' fields:
675 xxx.BBBByyyy
677 Here, if point is at the end of `x', the beginning of `y', or
678 anywhere in-between (within the `boundary' field), merge all
679 three fields and consider the beginning as being the beginning of
680 the `x' field, and the end as being the end of the `y' field. */
682 if (beg)
684 if (at_field_start)
685 /* POS is at the edge of a field, and we should consider it as
686 the beginning of the following field. */
687 *beg = XFASTINT (pos);
688 else
689 /* Find the previous field boundary. */
691 Lisp_Object p = pos;
692 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
693 /* Skip a `boundary' field. */
694 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
695 beg_limit);
697 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
698 beg_limit);
699 *beg = NILP (p) ? BEGV : XFASTINT (p);
703 if (end)
705 if (at_field_end)
706 /* POS is at the edge of a field, and we should consider it as
707 the end of the previous field. */
708 *end = XFASTINT (pos);
709 else
710 /* Find the next field boundary. */
712 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
713 /* Skip a `boundary' field. */
714 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
715 end_limit);
717 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
718 end_limit);
719 *end = NILP (pos) ? ZV : XFASTINT (pos);
725 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
726 doc: /* Delete the field surrounding POS.
727 A field is a region of text with the same `field' property.
728 If POS is nil, the value of point is used for POS. */)
729 (Lisp_Object pos)
731 ptrdiff_t beg, end;
732 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
733 if (beg != end)
734 del_range (beg, end);
735 return Qnil;
738 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
739 doc: /* Return the contents of the field surrounding POS as a string.
740 A field is a region of text with the same `field' property.
741 If POS is nil, the value of point is used for POS. */)
742 (Lisp_Object pos)
744 ptrdiff_t beg, end;
745 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
746 return make_buffer_string (beg, end, 1);
749 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
750 doc: /* Return the contents of the field around POS, without text properties.
751 A field is a region of text with the same `field' property.
752 If POS is nil, the value of point is used for POS. */)
753 (Lisp_Object pos)
755 ptrdiff_t beg, end;
756 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
757 return make_buffer_string (beg, end, 0);
760 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
761 doc: /* Return the beginning of the field surrounding POS.
762 A field is a region of text with the same `field' property.
763 If POS is nil, the value of point is used for POS.
764 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
765 field, then the beginning of the *previous* field is returned.
766 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
767 is before LIMIT, then LIMIT will be returned instead. */)
768 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
770 ptrdiff_t beg;
771 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
772 return make_number (beg);
775 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
776 doc: /* Return the end of the field surrounding POS.
777 A field is a region of text with the same `field' property.
778 If POS is nil, the value of point is used for POS.
779 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
780 then the end of the *following* field is returned.
781 If LIMIT is non-nil, it is a buffer position; if the end of the field
782 is after LIMIT, then LIMIT will be returned instead. */)
783 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
785 ptrdiff_t end;
786 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
787 return make_number (end);
790 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
791 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
792 A field is a region of text with the same `field' property.
794 If NEW-POS is nil, then use the current point instead, and move point
795 to the resulting constrained position, in addition to returning that
796 position.
798 If OLD-POS is at the boundary of two fields, then the allowable
799 positions for NEW-POS depends on the value of the optional argument
800 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
801 constrained to the field that has the same `field' char-property
802 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
803 is non-nil, NEW-POS is constrained to the union of the two adjacent
804 fields. Additionally, if two fields are separated by another field with
805 the special value `boundary', then any point within this special field is
806 also considered to be `on the boundary'.
808 If the optional argument ONLY-IN-LINE is non-nil and constraining
809 NEW-POS would move it to a different line, NEW-POS is returned
810 unconstrained. This is useful for commands that move by line, like
811 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
812 only in the case where they can still move to the right line.
814 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
815 a non-nil property of that name, then any field boundaries are ignored.
817 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
818 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
819 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
821 /* If non-zero, then the original point, before re-positioning. */
822 ptrdiff_t orig_point = 0;
823 bool fwd;
824 Lisp_Object prev_old, prev_new;
826 if (NILP (new_pos))
827 /* Use the current point, and afterwards, set it. */
829 orig_point = PT;
830 XSETFASTINT (new_pos, PT);
833 CHECK_NUMBER_COERCE_MARKER (new_pos);
834 CHECK_NUMBER_COERCE_MARKER (old_pos);
836 fwd = (XINT (new_pos) > XINT (old_pos));
838 prev_old = make_number (XINT (old_pos) - 1);
839 prev_new = make_number (XINT (new_pos) - 1);
841 if (NILP (Vinhibit_field_text_motion)
842 && !EQ (new_pos, old_pos)
843 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
844 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
845 /* To recognize field boundaries, we must also look at the
846 previous positions; we could use `Fget_pos_property'
847 instead, but in itself that would fail inside non-sticky
848 fields (like comint prompts). */
849 || (XFASTINT (new_pos) > BEGV
850 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
851 || (XFASTINT (old_pos) > BEGV
852 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
853 && (NILP (inhibit_capture_property)
854 /* Field boundaries are again a problem; but now we must
855 decide the case exactly, so we need to call
856 `get_pos_property' as well. */
857 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
858 && (XFASTINT (old_pos) <= BEGV
859 || NILP (Fget_char_property
860 (old_pos, inhibit_capture_property, Qnil))
861 || NILP (Fget_char_property
862 (prev_old, inhibit_capture_property, Qnil))))))
863 /* It is possible that NEW_POS is not within the same field as
864 OLD_POS; try to move NEW_POS so that it is. */
866 ptrdiff_t shortage;
867 Lisp_Object field_bound;
869 if (fwd)
870 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
871 else
872 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
874 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
875 other side of NEW_POS, which would mean that NEW_POS is
876 already acceptable, and it's not necessary to constrain it
877 to FIELD_BOUND. */
878 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
879 /* NEW_POS should be constrained, but only if either
880 ONLY_IN_LINE is nil (in which case any constraint is OK),
881 or NEW_POS and FIELD_BOUND are on the same line (in which
882 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
883 && (NILP (only_in_line)
884 /* This is the ONLY_IN_LINE case, check that NEW_POS and
885 FIELD_BOUND are on the same line by seeing whether
886 there's an intervening newline or not. */
887 || (find_newline (XFASTINT (new_pos), -1,
888 XFASTINT (field_bound), -1,
889 fwd ? -1 : 1, &shortage, NULL, 1),
890 shortage != 0)))
891 /* Constrain NEW_POS to FIELD_BOUND. */
892 new_pos = field_bound;
894 if (orig_point && XFASTINT (new_pos) != orig_point)
895 /* The NEW_POS argument was originally nil, so automatically set PT. */
896 SET_PT (XFASTINT (new_pos));
899 return new_pos;
903 DEFUN ("line-beginning-position",
904 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
905 doc: /* Return the character position of the first character on the current line.
906 With optional argument N, scan forward N - 1 lines first.
907 If the scan reaches the end of the buffer, return that position.
909 This function ignores text display directionality; it returns the
910 position of the first character in logical order, i.e. the smallest
911 character position on the line.
913 This function constrains the returned position to the current field
914 unless that position would be on a different line than the original,
915 unconstrained result. If N is nil or 1, and a front-sticky field
916 starts at point, the scan stops as soon as it starts. To ignore field
917 boundaries, bind `inhibit-field-text-motion' to t.
919 This function does not move point. */)
920 (Lisp_Object n)
922 ptrdiff_t charpos, bytepos;
924 if (NILP (n))
925 XSETFASTINT (n, 1);
926 else
927 CHECK_NUMBER (n);
929 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
931 /* Return END constrained to the current input field. */
932 return Fconstrain_to_field (make_number (charpos), make_number (PT),
933 XINT (n) != 1 ? Qt : Qnil,
934 Qt, Qnil);
937 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
938 doc: /* Return the character position of the last character on the current line.
939 With argument N not nil or 1, move forward N - 1 lines first.
940 If scan reaches end of buffer, return that position.
942 This function ignores text display directionality; it returns the
943 position of the last character in logical order, i.e. the largest
944 character position on the line.
946 This function constrains the returned position to the current field
947 unless that would be on a different line than the original,
948 unconstrained result. If N is nil or 1, and a rear-sticky field ends
949 at point, the scan stops as soon as it starts. To ignore field
950 boundaries bind `inhibit-field-text-motion' to t.
952 This function does not move point. */)
953 (Lisp_Object n)
955 ptrdiff_t clipped_n;
956 ptrdiff_t end_pos;
957 ptrdiff_t orig = PT;
959 if (NILP (n))
960 XSETFASTINT (n, 1);
961 else
962 CHECK_NUMBER (n);
964 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
965 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
966 NULL);
968 /* Return END_POS constrained to the current input field. */
969 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
970 Qnil, Qt, Qnil);
973 /* Save current buffer state for `save-excursion' special form.
974 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
975 offload some work from GC. */
977 Lisp_Object
978 save_excursion_save (void)
980 return make_save_obj_obj_obj_obj
981 (Fpoint_marker (),
982 Qnil,
983 /* Selected window if current buffer is shown in it, nil otherwise. */
984 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
985 ? selected_window : Qnil),
986 Qnil);
989 /* Restore saved buffer before leaving `save-excursion' special form. */
991 void
992 save_excursion_restore (Lisp_Object info)
994 Lisp_Object tem, tem1;
996 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
997 /* If we're unwinding to top level, saved buffer may be deleted. This
998 means that all of its markers are unchained and so tem is nil. */
999 if (NILP (tem))
1000 goto out;
1002 Fset_buffer (tem);
1004 /* Point marker. */
1005 tem = XSAVE_OBJECT (info, 0);
1006 Fgoto_char (tem);
1007 unchain_marker (XMARKER (tem));
1009 /* If buffer was visible in a window, and a different window was
1010 selected, and the old selected window is still showing this
1011 buffer, restore point in that window. */
1012 tem = XSAVE_OBJECT (info, 2);
1013 if (WINDOWP (tem)
1014 && !EQ (tem, selected_window)
1015 && (tem1 = XWINDOW (tem)->contents,
1016 (/* Window is live... */
1017 BUFFERP (tem1)
1018 /* ...and it shows the current buffer. */
1019 && XBUFFER (tem1) == current_buffer)))
1020 Fset_window_point (tem, make_number (PT));
1022 out:
1024 free_misc (info);
1027 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
1028 doc: /* Save point, and current buffer; execute BODY; restore those things.
1029 Executes BODY just like `progn'.
1030 The values of point and the current buffer are restored
1031 even in case of abnormal exit (throw or error).
1033 If you only want to save the current buffer but not point,
1034 then just use `save-current-buffer', or even `with-current-buffer'.
1036 Before Emacs 25.1, `save-excursion' used to save the mark state.
1037 To save the marker state as well as the point and buffer, use
1038 `save-mark-and-excursion'.
1040 usage: (save-excursion &rest BODY) */)
1041 (Lisp_Object args)
1043 register Lisp_Object val;
1044 ptrdiff_t count = SPECPDL_INDEX ();
1046 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1048 val = Fprogn (args);
1049 return unbind_to (count, val);
1052 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1053 doc: /* Record which buffer is current; execute BODY; make that buffer current.
1054 BODY is executed just like `progn'.
1055 usage: (save-current-buffer &rest BODY) */)
1056 (Lisp_Object args)
1058 ptrdiff_t count = SPECPDL_INDEX ();
1060 record_unwind_current_buffer ();
1061 return unbind_to (count, Fprogn (args));
1064 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
1065 doc: /* Return the number of characters in the current buffer.
1066 If BUFFER is not nil, return the number of characters in that buffer
1067 instead.
1069 This does not take narrowing into account; to count the number of
1070 characters in the accessible portion of the current buffer, use
1071 `(- (point-max) (point-min))', and to count the number of characters
1072 in some other BUFFER, use
1073 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1074 (Lisp_Object buffer)
1076 if (NILP (buffer))
1077 return make_number (Z - BEG);
1078 else
1080 CHECK_BUFFER (buffer);
1081 return make_number (BUF_Z (XBUFFER (buffer))
1082 - BUF_BEG (XBUFFER (buffer)));
1086 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1087 doc: /* Return the minimum permissible value of point in the current buffer.
1088 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1089 (void)
1091 Lisp_Object temp;
1092 XSETFASTINT (temp, BEGV);
1093 return temp;
1096 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1097 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1098 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1099 (void)
1101 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1104 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1105 doc: /* Return the maximum permissible value of point in the current buffer.
1106 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1107 is in effect, in which case it is less. */)
1108 (void)
1110 Lisp_Object temp;
1111 XSETFASTINT (temp, ZV);
1112 return temp;
1115 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1116 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1117 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1118 is in effect, in which case it is less. */)
1119 (void)
1121 return build_marker (current_buffer, ZV, ZV_BYTE);
1124 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1125 doc: /* Return the position of the gap, in the current buffer.
1126 See also `gap-size'. */)
1127 (void)
1129 Lisp_Object temp;
1130 XSETFASTINT (temp, GPT);
1131 return temp;
1134 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1135 doc: /* Return the size of the current buffer's gap.
1136 See also `gap-position'. */)
1137 (void)
1139 Lisp_Object temp;
1140 XSETFASTINT (temp, GAP_SIZE);
1141 return temp;
1144 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1145 doc: /* Return the byte position for character position POSITION.
1146 If POSITION is out of range, the value is nil. */)
1147 (Lisp_Object position)
1149 CHECK_NUMBER_COERCE_MARKER (position);
1150 if (XINT (position) < BEG || XINT (position) > Z)
1151 return Qnil;
1152 return make_number (CHAR_TO_BYTE (XINT (position)));
1155 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1156 doc: /* Return the character position for byte position BYTEPOS.
1157 If BYTEPOS is out of range, the value is nil. */)
1158 (Lisp_Object bytepos)
1160 ptrdiff_t pos_byte;
1162 CHECK_NUMBER (bytepos);
1163 pos_byte = XINT (bytepos);
1164 if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
1165 return Qnil;
1166 if (Z != Z_BYTE)
1167 /* There are multibyte characters in the buffer.
1168 The argument of BYTE_TO_CHAR must be a byte position at
1169 a character boundary, so search for the start of the current
1170 character. */
1171 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte)))
1172 pos_byte--;
1173 return make_number (BYTE_TO_CHAR (pos_byte));
1176 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1177 doc: /* Return the character following point, as a number.
1178 At the end of the buffer or accessible region, return 0. */)
1179 (void)
1181 Lisp_Object temp;
1182 if (PT >= ZV)
1183 XSETFASTINT (temp, 0);
1184 else
1185 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1186 return temp;
1189 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1190 doc: /* Return the character preceding point, as a number.
1191 At the beginning of the buffer or accessible region, return 0. */)
1192 (void)
1194 Lisp_Object temp;
1195 if (PT <= BEGV)
1196 XSETFASTINT (temp, 0);
1197 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1199 ptrdiff_t pos = PT_BYTE;
1200 DEC_POS (pos);
1201 XSETFASTINT (temp, FETCH_CHAR (pos));
1203 else
1204 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1205 return temp;
1208 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1209 doc: /* Return t if point is at the beginning of the buffer.
1210 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1211 (void)
1213 if (PT == BEGV)
1214 return Qt;
1215 return Qnil;
1218 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1219 doc: /* Return t if point is at the end of the buffer.
1220 If the buffer is narrowed, this means the end of the narrowed part. */)
1221 (void)
1223 if (PT == ZV)
1224 return Qt;
1225 return Qnil;
1228 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1229 doc: /* Return t if point is at the beginning of a line. */)
1230 (void)
1232 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1233 return Qt;
1234 return Qnil;
1237 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1238 doc: /* Return t if point is at the end of a line.
1239 `End of a line' includes point being at the end of the buffer. */)
1240 (void)
1242 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1243 return Qt;
1244 return Qnil;
1247 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1248 doc: /* Return character in current buffer at position POS.
1249 POS is an integer or a marker and defaults to point.
1250 If POS is out of range, the value is nil. */)
1251 (Lisp_Object pos)
1253 register ptrdiff_t pos_byte;
1255 if (NILP (pos))
1257 pos_byte = PT_BYTE;
1258 XSETFASTINT (pos, PT);
1261 if (MARKERP (pos))
1263 pos_byte = marker_byte_position (pos);
1264 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1265 return Qnil;
1267 else
1269 CHECK_NUMBER_COERCE_MARKER (pos);
1270 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1271 return Qnil;
1273 pos_byte = CHAR_TO_BYTE (XINT (pos));
1276 return make_number (FETCH_CHAR (pos_byte));
1279 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1280 doc: /* Return character in current buffer preceding position POS.
1281 POS is an integer or a marker and defaults to point.
1282 If POS is out of range, the value is nil. */)
1283 (Lisp_Object pos)
1285 register Lisp_Object val;
1286 register ptrdiff_t pos_byte;
1288 if (NILP (pos))
1290 pos_byte = PT_BYTE;
1291 XSETFASTINT (pos, PT);
1294 if (MARKERP (pos))
1296 pos_byte = marker_byte_position (pos);
1298 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1299 return Qnil;
1301 else
1303 CHECK_NUMBER_COERCE_MARKER (pos);
1305 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1306 return Qnil;
1308 pos_byte = CHAR_TO_BYTE (XINT (pos));
1311 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1313 DEC_POS (pos_byte);
1314 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1316 else
1318 pos_byte--;
1319 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1321 return val;
1324 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1325 doc: /* Return the name under which the user logged in, as a string.
1326 This is based on the effective uid, not the real uid.
1327 Also, if the environment variables LOGNAME or USER are set,
1328 that determines the value of this function.
1330 If optional argument UID is an integer or a float, return the login name
1331 of the user with that uid, or nil if there is no such user. */)
1332 (Lisp_Object uid)
1334 struct passwd *pw;
1335 uid_t id;
1337 /* Set up the user name info if we didn't do it before.
1338 (That can happen if Emacs is dumpable
1339 but you decide to run `temacs -l loadup' and not dump. */
1340 if (NILP (Vuser_login_name))
1341 init_editfns (false);
1343 if (NILP (uid))
1344 return Vuser_login_name;
1346 CONS_TO_INTEGER (uid, uid_t, id);
1347 block_input ();
1348 pw = getpwuid (id);
1349 unblock_input ();
1350 return (pw ? build_string (pw->pw_name) : Qnil);
1353 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1354 0, 0, 0,
1355 doc: /* Return the name of the user's real uid, as a string.
1356 This ignores the environment variables LOGNAME and USER, so it differs from
1357 `user-login-name' when running under `su'. */)
1358 (void)
1360 /* Set up the user name info if we didn't do it before.
1361 (That can happen if Emacs is dumpable
1362 but you decide to run `temacs -l loadup' and not dump. */
1363 if (NILP (Vuser_login_name))
1364 init_editfns (false);
1365 return Vuser_real_login_name;
1368 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1369 doc: /* Return the effective uid of Emacs.
1370 Value is an integer or a float, depending on the value. */)
1371 (void)
1373 uid_t euid = geteuid ();
1374 return make_fixnum_or_float (euid);
1377 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1378 doc: /* Return the real uid of Emacs.
1379 Value is an integer or a float, depending on the value. */)
1380 (void)
1382 uid_t uid = getuid ();
1383 return make_fixnum_or_float (uid);
1386 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1387 doc: /* Return the effective gid of Emacs.
1388 Value is an integer or a float, depending on the value. */)
1389 (void)
1391 gid_t egid = getegid ();
1392 return make_fixnum_or_float (egid);
1395 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1396 doc: /* Return the real gid of Emacs.
1397 Value is an integer or a float, depending on the value. */)
1398 (void)
1400 gid_t gid = getgid ();
1401 return make_fixnum_or_float (gid);
1404 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1405 doc: /* Return the full name of the user logged in, as a string.
1406 If the full name corresponding to Emacs's userid is not known,
1407 return "unknown".
1409 If optional argument UID is an integer or float, return the full name
1410 of the user with that uid, or nil if there is no such user.
1411 If UID is a string, return the full name of the user with that login
1412 name, or nil if there is no such user. */)
1413 (Lisp_Object uid)
1415 struct passwd *pw;
1416 register char *p, *q;
1417 Lisp_Object full;
1419 if (NILP (uid))
1420 return Vuser_full_name;
1421 else if (NUMBERP (uid))
1423 uid_t u;
1424 CONS_TO_INTEGER (uid, uid_t, u);
1425 block_input ();
1426 pw = getpwuid (u);
1427 unblock_input ();
1429 else if (STRINGP (uid))
1431 block_input ();
1432 pw = getpwnam (SSDATA (uid));
1433 unblock_input ();
1435 else
1436 error ("Invalid UID specification");
1438 if (!pw)
1439 return Qnil;
1441 p = USER_FULL_NAME;
1442 /* Chop off everything after the first comma. */
1443 q = strchr (p, ',');
1444 full = make_string (p, q ? q - p : strlen (p));
1446 #ifdef AMPERSAND_FULL_NAME
1447 p = SSDATA (full);
1448 q = strchr (p, '&');
1449 /* Substitute the login name for the &, upcasing the first character. */
1450 if (q)
1452 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1453 USE_SAFE_ALLOCA;
1454 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1455 memcpy (r, p, q - p);
1456 char *s = lispstpcpy (&r[q - p], login);
1457 r[q - p] = upcase ((unsigned char) r[q - p]);
1458 strcpy (s, q + 1);
1459 full = build_string (r);
1460 SAFE_FREE ();
1462 #endif /* AMPERSAND_FULL_NAME */
1464 return full;
1467 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1468 doc: /* Return the host name of the machine you are running on, as a string. */)
1469 (void)
1471 if (EQ (Vsystem_name, cached_system_name))
1472 init_and_cache_system_name ();
1473 return Vsystem_name;
1476 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1477 doc: /* Return the process ID of Emacs, as a number. */)
1478 (void)
1480 pid_t pid = getpid ();
1481 return make_fixnum_or_float (pid);
1486 #ifndef TIME_T_MIN
1487 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1488 #endif
1489 #ifndef TIME_T_MAX
1490 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1491 #endif
1493 /* Report that a time value is out of range for Emacs. */
1494 void
1495 time_overflow (void)
1497 error ("Specified time is not representable");
1500 static _Noreturn void
1501 invalid_time (void)
1503 error ("Invalid time specification");
1506 /* Check a return value compatible with that of decode_time_components. */
1507 static void
1508 check_time_validity (int validity)
1510 if (validity <= 0)
1512 if (validity < 0)
1513 time_overflow ();
1514 else
1515 invalid_time ();
1519 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1520 static EMACS_INT
1521 hi_time (time_t t)
1523 time_t hi = t >> LO_TIME_BITS;
1524 if (FIXNUM_OVERFLOW_P (hi))
1525 time_overflow ();
1526 return hi;
1529 /* Return the bottom bits of the time T. */
1530 static int
1531 lo_time (time_t t)
1533 return t & ((1 << LO_TIME_BITS) - 1);
1536 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1537 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1538 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1539 HIGH has the most significant bits of the seconds, while LOW has the
1540 least significant 16 bits. USEC and PSEC are the microsecond and
1541 picosecond counts. */)
1542 (void)
1544 return make_lisp_time (current_timespec ());
1547 static struct lisp_time
1548 time_add (struct lisp_time ta, struct lisp_time tb)
1550 EMACS_INT hi = ta.hi + tb.hi;
1551 int lo = ta.lo + tb.lo;
1552 int us = ta.us + tb.us;
1553 int ps = ta.ps + tb.ps;
1554 us += (1000000 <= ps);
1555 ps -= (1000000 <= ps) * 1000000;
1556 lo += (1000000 <= us);
1557 us -= (1000000 <= us) * 1000000;
1558 hi += (1 << LO_TIME_BITS <= lo);
1559 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1560 return (struct lisp_time) { hi, lo, us, ps };
1563 static struct lisp_time
1564 time_subtract (struct lisp_time ta, struct lisp_time tb)
1566 EMACS_INT hi = ta.hi - tb.hi;
1567 int lo = ta.lo - tb.lo;
1568 int us = ta.us - tb.us;
1569 int ps = ta.ps - tb.ps;
1570 us -= (ps < 0);
1571 ps += (ps < 0) * 1000000;
1572 lo -= (us < 0);
1573 us += (us < 0) * 1000000;
1574 hi -= (lo < 0);
1575 lo += (lo < 0) << LO_TIME_BITS;
1576 return (struct lisp_time) { hi, lo, us, ps };
1579 static Lisp_Object
1580 time_arith (Lisp_Object a, Lisp_Object b,
1581 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1583 int alen, blen;
1584 struct lisp_time ta = lisp_time_struct (a, &alen);
1585 struct lisp_time tb = lisp_time_struct (b, &blen);
1586 struct lisp_time t = op (ta, tb);
1587 if (FIXNUM_OVERFLOW_P (t.hi))
1588 time_overflow ();
1589 Lisp_Object val = Qnil;
1591 switch (max (alen, blen))
1593 default:
1594 val = Fcons (make_number (t.ps), val);
1595 FALLTHROUGH;
1596 case 3:
1597 val = Fcons (make_number (t.us), val);
1598 FALLTHROUGH;
1599 case 2:
1600 val = Fcons (make_number (t.lo), val);
1601 val = Fcons (make_number (t.hi), val);
1602 break;
1605 return val;
1608 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1609 doc: /* Return the sum of two time values A and B, as a time value.
1610 A nil value for either argument stands for the current time.
1611 See `current-time-string' for the various forms of a time value. */)
1612 (Lisp_Object a, Lisp_Object b)
1614 return time_arith (a, b, time_add);
1617 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1618 doc: /* Return the difference between two time values A and B, as a time value.
1619 Use `float-time' to convert the difference into elapsed seconds.
1620 A nil value for either argument stands for the current time.
1621 See `current-time-string' for the various forms of a time value. */)
1622 (Lisp_Object a, Lisp_Object b)
1624 return time_arith (a, b, time_subtract);
1627 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1628 doc: /* Return non-nil if time value T1 is earlier than time value T2.
1629 A nil value for either argument stands for the current time.
1630 See `current-time-string' for the various forms of a time value. */)
1631 (Lisp_Object t1, Lisp_Object t2)
1633 int t1len, t2len;
1634 struct lisp_time a = lisp_time_struct (t1, &t1len);
1635 struct lisp_time b = lisp_time_struct (t2, &t2len);
1636 return ((a.hi != b.hi ? a.hi < b.hi
1637 : a.lo != b.lo ? a.lo < b.lo
1638 : a.us != b.us ? a.us < b.us
1639 : a.ps < b.ps)
1640 ? Qt : Qnil);
1644 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1645 0, 0, 0,
1646 doc: /* Return the current run time used by Emacs.
1647 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1648 style as (current-time).
1650 On systems that can't determine the run time, `get-internal-run-time'
1651 does the same thing as `current-time'. */)
1652 (void)
1654 #ifdef HAVE_GETRUSAGE
1655 struct rusage usage;
1656 time_t secs;
1657 int usecs;
1659 if (getrusage (RUSAGE_SELF, &usage) < 0)
1660 /* This shouldn't happen. What action is appropriate? */
1661 xsignal0 (Qerror);
1663 /* Sum up user time and system time. */
1664 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1665 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1666 if (usecs >= 1000000)
1668 usecs -= 1000000;
1669 secs++;
1671 return make_lisp_time (make_timespec (secs, usecs * 1000));
1672 #else /* ! HAVE_GETRUSAGE */
1673 #ifdef WINDOWSNT
1674 return w32_get_internal_run_time ();
1675 #else /* ! WINDOWSNT */
1676 return Fcurrent_time ();
1677 #endif /* WINDOWSNT */
1678 #endif /* HAVE_GETRUSAGE */
1682 /* Make a Lisp list that represents the Emacs time T. T may be an
1683 invalid time, with a slightly negative tv_nsec value such as
1684 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1685 correspondingly negative picosecond count. */
1686 Lisp_Object
1687 make_lisp_time (struct timespec t)
1689 time_t s = t.tv_sec;
1690 int ns = t.tv_nsec;
1691 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1694 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1695 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1696 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1697 if successful, 0 if unsuccessful. */
1698 static int
1699 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1700 Lisp_Object *plow, Lisp_Object *pusec,
1701 Lisp_Object *ppsec)
1703 Lisp_Object high = make_number (0);
1704 Lisp_Object low = specified_time;
1705 Lisp_Object usec = make_number (0);
1706 Lisp_Object psec = make_number (0);
1707 int len = 4;
1709 if (CONSP (specified_time))
1711 high = XCAR (specified_time);
1712 low = XCDR (specified_time);
1713 if (CONSP (low))
1715 Lisp_Object low_tail = XCDR (low);
1716 low = XCAR (low);
1717 if (CONSP (low_tail))
1719 usec = XCAR (low_tail);
1720 low_tail = XCDR (low_tail);
1721 if (CONSP (low_tail))
1722 psec = XCAR (low_tail);
1723 else
1724 len = 3;
1726 else if (!NILP (low_tail))
1728 usec = low_tail;
1729 len = 3;
1731 else
1732 len = 2;
1734 else
1735 len = 2;
1737 /* When combining components, require LOW to be an integer,
1738 as otherwise it would be a pain to add up times. */
1739 if (! INTEGERP (low))
1740 return 0;
1742 else if (INTEGERP (specified_time))
1743 len = 2;
1745 *phigh = high;
1746 *plow = low;
1747 *pusec = usec;
1748 *ppsec = psec;
1749 return len;
1752 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1753 Return true if T is in range, false otherwise. */
1754 static bool
1755 decode_float_time (double t, struct lisp_time *result)
1757 double lo_multiplier = 1 << LO_TIME_BITS;
1758 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1759 if (! (emacs_time_min <= t && t < -emacs_time_min))
1760 return false;
1762 double small_t = t / lo_multiplier;
1763 EMACS_INT hi = small_t;
1764 double t_sans_hi = t - hi * lo_multiplier;
1765 int lo = t_sans_hi;
1766 long double fracps = (t_sans_hi - lo) * 1e12L;
1767 #ifdef INT_FAST64_MAX
1768 int_fast64_t ifracps = fracps;
1769 int us = ifracps / 1000000;
1770 int ps = ifracps % 1000000;
1771 #else
1772 int us = fracps / 1e6L;
1773 int ps = fracps - us * 1e6L;
1774 #endif
1775 us -= (ps < 0);
1776 ps += (ps < 0) * 1000000;
1777 lo -= (us < 0);
1778 us += (us < 0) * 1000000;
1779 hi -= (lo < 0);
1780 lo += (lo < 0) << LO_TIME_BITS;
1781 result->hi = hi;
1782 result->lo = lo;
1783 result->us = us;
1784 result->ps = ps;
1785 return true;
1788 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1789 list, generate the corresponding time value.
1790 If LOW is floating point, the other components should be zero.
1792 If RESULT is not null, store into *RESULT the converted time.
1793 If *DRESULT is not null, store into *DRESULT the number of
1794 seconds since the start of the POSIX Epoch.
1796 Return 1 if successful, 0 if the components are of the
1797 wrong type, and -1 if the time is out of range. */
1799 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1800 Lisp_Object psec,
1801 struct lisp_time *result, double *dresult)
1803 EMACS_INT hi, lo, us, ps;
1804 if (! (INTEGERP (high)
1805 && INTEGERP (usec) && INTEGERP (psec)))
1806 return 0;
1807 if (! INTEGERP (low))
1809 if (FLOATP (low))
1811 double t = XFLOAT_DATA (low);
1812 if (result && ! decode_float_time (t, result))
1813 return -1;
1814 if (dresult)
1815 *dresult = t;
1816 return 1;
1818 else if (NILP (low))
1820 struct timespec now = current_timespec ();
1821 if (result)
1823 result->hi = hi_time (now.tv_sec);
1824 result->lo = lo_time (now.tv_sec);
1825 result->us = now.tv_nsec / 1000;
1826 result->ps = now.tv_nsec % 1000 * 1000;
1828 if (dresult)
1829 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1830 return 1;
1832 else
1833 return 0;
1836 hi = XINT (high);
1837 lo = XINT (low);
1838 us = XINT (usec);
1839 ps = XINT (psec);
1841 /* Normalize out-of-range lower-order components by carrying
1842 each overflow into the next higher-order component. */
1843 us += ps / 1000000 - (ps % 1000000 < 0);
1844 lo += us / 1000000 - (us % 1000000 < 0);
1845 hi += lo >> LO_TIME_BITS;
1846 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1847 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1848 lo &= (1 << LO_TIME_BITS) - 1;
1850 if (result)
1852 if (FIXNUM_OVERFLOW_P (hi))
1853 return -1;
1854 result->hi = hi;
1855 result->lo = lo;
1856 result->us = us;
1857 result->ps = ps;
1860 if (dresult)
1862 double dhi = hi;
1863 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1866 return 1;
1869 struct timespec
1870 lisp_to_timespec (struct lisp_time t)
1872 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1873 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1874 return invalid_timespec ();
1875 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1876 int ns = t.us * 1000 + t.ps / 1000;
1877 return make_timespec (s, ns);
1880 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1881 Store its effective length into *PLEN.
1882 If SPECIFIED_TIME is nil, use the current time.
1883 Signal an error if SPECIFIED_TIME does not represent a time. */
1884 static struct lisp_time
1885 lisp_time_struct (Lisp_Object specified_time, int *plen)
1887 Lisp_Object high, low, usec, psec;
1888 struct lisp_time t;
1889 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1890 if (!len)
1891 invalid_time ();
1892 int val = decode_time_components (high, low, usec, psec, &t, 0);
1893 check_time_validity (val);
1894 *plen = len;
1895 return t;
1898 /* Like lisp_time_struct, except return a struct timespec.
1899 Discard any low-order digits. */
1900 struct timespec
1901 lisp_time_argument (Lisp_Object specified_time)
1903 int len;
1904 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1905 struct timespec t = lisp_to_timespec (lt);
1906 if (! timespec_valid_p (t))
1907 time_overflow ();
1908 return t;
1911 /* Like lisp_time_argument, except decode only the seconds part,
1912 and do not check the subseconds part. */
1913 static time_t
1914 lisp_seconds_argument (Lisp_Object specified_time)
1916 Lisp_Object high, low, usec, psec;
1917 struct lisp_time t;
1919 int val = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1920 if (val != 0)
1922 val = decode_time_components (high, low, make_number (0),
1923 make_number (0), &t, 0);
1924 if (0 < val
1925 && ! ((TYPE_SIGNED (time_t)
1926 ? TIME_T_MIN >> LO_TIME_BITS <= t.hi
1927 : 0 <= t.hi)
1928 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1929 val = -1;
1931 check_time_validity (val);
1932 return (t.hi << LO_TIME_BITS) + t.lo;
1935 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1936 doc: /* Return the current time, as a float number of seconds since the epoch.
1937 If SPECIFIED-TIME is given, it is the time to convert to float
1938 instead of the current time. The argument should have the form
1939 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1940 you can use times from `current-time' and from `file-attributes'.
1941 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1942 considered obsolete.
1944 WARNING: Since the result is floating point, it may not be exact.
1945 If precise time stamps are required, use either `current-time',
1946 or (if you need time as a string) `format-time-string'. */)
1947 (Lisp_Object specified_time)
1949 double t;
1950 Lisp_Object high, low, usec, psec;
1951 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1952 && decode_time_components (high, low, usec, psec, 0, &t)))
1953 invalid_time ();
1954 return make_float (t);
1957 /* Write information into buffer S of size MAXSIZE, according to the
1958 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1959 Use the time zone specified by TZ.
1960 Use NS as the number of nanoseconds in the %N directive.
1961 Return the number of bytes written, not including the terminating
1962 '\0'. If S is NULL, nothing will be written anywhere; so to
1963 determine how many bytes would be written, use NULL for S and
1964 ((size_t) -1) for MAXSIZE.
1966 This function behaves like nstrftime, except it allows null
1967 bytes in FORMAT and it does not support nanoseconds. */
1968 static size_t
1969 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1970 size_t format_len, const struct tm *tp, timezone_t tz, int ns)
1972 size_t total = 0;
1974 /* Loop through all the null-terminated strings in the format
1975 argument. Normally there's just one null-terminated string, but
1976 there can be arbitrarily many, concatenated together, if the
1977 format contains '\0' bytes. nstrftime stops at the first
1978 '\0' byte so we must invoke it separately for each such string. */
1979 for (;;)
1981 size_t len;
1982 size_t result;
1984 if (s)
1985 s[0] = '\1';
1987 result = nstrftime (s, maxsize, format, tp, tz, ns);
1989 if (s)
1991 if (result == 0 && s[0] != '\0')
1992 return 0;
1993 s += result + 1;
1996 maxsize -= result + 1;
1997 total += result;
1998 len = strlen (format);
1999 if (len == format_len)
2000 return total;
2001 total++;
2002 format += len + 1;
2003 format_len -= len + 1;
2007 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
2008 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted or nil.
2009 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2010 `current-time' or `file-attributes'. It can also be a single integer
2011 number of seconds since the epoch. The obsolete form (HIGH . LOW) is
2012 also still accepted.
2014 The optional ZONE is omitted or nil for Emacs local time, t for
2015 Universal Time, `wall' for system wall clock time, or a string as in
2016 the TZ environment variable. It can also be a list (as from
2017 `current-time-zone') or an integer (as from `decode-time') applied
2018 without consideration for daylight saving time.
2020 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2021 by text that describes the specified date and time in TIME:
2023 %Y is the year, %y within the century, %C the century.
2024 %G is the year corresponding to the ISO week, %g within the century.
2025 %m is the numeric month.
2026 %b and %h are the locale's abbreviated month name, %B the full name.
2027 (%h is not supported on MS-Windows.)
2028 %d is the day of the month, zero-padded, %e is blank-padded.
2029 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2030 %a is the locale's abbreviated name of the day of week, %A the full name.
2031 %U is the week number starting on Sunday, %W starting on Monday,
2032 %V according to ISO 8601.
2033 %j is the day of the year.
2035 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2036 only blank-padded, %l is like %I blank-padded.
2037 %p is the locale's equivalent of either AM or PM.
2038 %q is the calendar quarter (1–4).
2039 %M is the minute.
2040 %S is the second.
2041 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2042 %Z is the time zone name, %z is the numeric form.
2043 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2045 %c is the locale's date and time format.
2046 %x is the locale's "preferred" date format.
2047 %D is like "%m/%d/%y".
2048 %F is the ISO 8601 date format (like "%Y-%m-%d").
2050 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2051 %X is the locale's "preferred" time format.
2053 Finally, %n is a newline, %t is a tab, %% is a literal %.
2055 Certain flags and modifiers are available with some format controls.
2056 The flags are `_', `-', `^' and `#'. For certain characters X,
2057 %_X is like %X, but padded with blanks; %-X is like %X,
2058 but without padding. %^X is like %X, but with all textual
2059 characters up-cased; %#X is like %X, but with letter-case of
2060 all textual characters reversed.
2061 %NX (where N stands for an integer) is like %X,
2062 but takes up at least N (a number) positions.
2063 The modifiers are `E' and `O'. For certain characters X,
2064 %EX is a locale's alternative version of %X;
2065 %OX is like %X, but uses the locale's number symbols.
2067 For example, to produce full ISO 8601 format, use "%FT%T%z".
2069 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2070 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object zone)
2072 struct timespec t = lisp_time_argument (timeval);
2073 struct tm tm;
2075 CHECK_STRING (format_string);
2076 format_string = code_convert_string_norecord (format_string,
2077 Vlocale_coding_system, 1);
2078 return format_time_string (SSDATA (format_string), SBYTES (format_string),
2079 t, zone, &tm);
2082 static Lisp_Object
2083 format_time_string (char const *format, ptrdiff_t formatlen,
2084 struct timespec t, Lisp_Object zone, struct tm *tmp)
2086 char buffer[4000];
2087 char *buf = buffer;
2088 ptrdiff_t size = sizeof buffer;
2089 size_t len;
2090 int ns = t.tv_nsec;
2091 USE_SAFE_ALLOCA;
2093 timezone_t tz = tzlookup (zone, false);
2094 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2095 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2096 expects a pointer to time_t value. */
2097 time_t tsec = t.tv_sec;
2098 tmp = emacs_localtime_rz (tz, &tsec, tmp);
2099 if (! tmp)
2101 xtzfree (tz);
2102 time_overflow ();
2104 synchronize_system_time_locale ();
2106 while (true)
2108 buf[0] = '\1';
2109 len = emacs_nmemftime (buf, size, format, formatlen, tmp, tz, ns);
2110 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
2111 break;
2113 /* Buffer was too small, so make it bigger and try again. */
2114 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, tz, ns);
2115 if (STRING_BYTES_BOUND <= len)
2117 xtzfree (tz);
2118 string_overflow ();
2120 size = len + 1;
2121 buf = SAFE_ALLOCA (size);
2124 xtzfree (tz);
2125 AUTO_STRING_WITH_LEN (bufstring, buf, len);
2126 Lisp_Object result = code_convert_string_norecord (bufstring,
2127 Vlocale_coding_system, 0);
2128 SAFE_FREE ();
2129 return result;
2132 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 2, 0,
2133 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2134 The optional TIME should be a list of (HIGH LOW . IGNORED),
2135 as from `current-time' and `file-attributes', or nil to use the
2136 current time. It can also be a single integer number of seconds since
2137 the epoch. The obsolete form (HIGH . LOW) is also still accepted.
2139 The optional ZONE is omitted or nil for Emacs local time, t for
2140 Universal Time, `wall' for system wall clock time, or a string as in
2141 the TZ environment variable. It can also be a list (as from
2142 `current-time-zone') or an integer (as from `decode-time') applied
2143 without consideration for daylight saving time.
2145 The list has the following nine members: SEC is an integer between 0
2146 and 60; SEC is 60 for a leap second, which only some operating systems
2147 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2148 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2149 integer between 1 and 12. YEAR is an integer indicating the
2150 four-digit year. DOW is the day of week, an integer between 0 and 6,
2151 where 0 is Sunday. DST is t if daylight saving time is in effect,
2152 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2153 seconds, i.e., the number of seconds east of Greenwich. (Note that
2154 Common Lisp has different meanings for DOW and UTCOFF.)
2156 usage: (decode-time &optional TIME ZONE) */)
2157 (Lisp_Object specified_time, Lisp_Object zone)
2159 time_t time_spec = lisp_seconds_argument (specified_time);
2160 struct tm local_tm, gmt_tm;
2161 timezone_t tz = tzlookup (zone, false);
2162 struct tm *tm = emacs_localtime_rz (tz, &time_spec, &local_tm);
2163 xtzfree (tz);
2165 if (! (tm
2166 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2167 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2168 time_overflow ();
2170 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2171 EMACS_INT tm_year_base = TM_YEAR_BASE;
2173 return CALLN (Flist,
2174 make_number (local_tm.tm_sec),
2175 make_number (local_tm.tm_min),
2176 make_number (local_tm.tm_hour),
2177 make_number (local_tm.tm_mday),
2178 make_number (local_tm.tm_mon + 1),
2179 make_number (local_tm.tm_year + tm_year_base),
2180 make_number (local_tm.tm_wday),
2181 local_tm.tm_isdst ? Qt : Qnil,
2182 (HAVE_TM_GMTOFF
2183 ? make_number (tm_gmtoff (&local_tm))
2184 : gmtime_r (&time_spec, &gmt_tm)
2185 ? make_number (tm_diff (&local_tm, &gmt_tm))
2186 : Qnil));
2189 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2190 the result is representable as an int. */
2191 static int
2192 check_tm_member (Lisp_Object obj, int offset)
2194 CHECK_NUMBER (obj);
2195 EMACS_INT n = XINT (obj);
2196 int result;
2197 if (INT_SUBTRACT_WRAPV (n, offset, &result))
2198 time_overflow ();
2199 return result;
2202 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2203 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2204 This is the reverse operation of `decode-time', which see.
2206 The optional ZONE is omitted or nil for Emacs local time, t for
2207 Universal Time, `wall' for system wall clock time, or a string as in
2208 the TZ environment variable. It can also be a list (as from
2209 `current-time-zone') or an integer (as from `decode-time') applied
2210 without consideration for daylight saving time.
2212 You can pass more than 7 arguments; then the first six arguments
2213 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2214 The intervening arguments are ignored.
2215 This feature lets (apply \\='encode-time (decode-time ...)) work.
2217 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2218 for example, a DAY of 0 means the day preceding the given month.
2219 Year numbers less than 100 are treated just like other year numbers.
2220 If you want them to stand for years in this century, you must do that yourself.
2222 Years before 1970 are not guaranteed to work. On some systems,
2223 year values as low as 1901 do work.
2225 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2226 (ptrdiff_t nargs, Lisp_Object *args)
2228 time_t value;
2229 struct tm tm;
2230 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2232 tm.tm_sec = check_tm_member (args[0], 0);
2233 tm.tm_min = check_tm_member (args[1], 0);
2234 tm.tm_hour = check_tm_member (args[2], 0);
2235 tm.tm_mday = check_tm_member (args[3], 0);
2236 tm.tm_mon = check_tm_member (args[4], 1);
2237 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2238 tm.tm_isdst = -1;
2240 timezone_t tz = tzlookup (zone, false);
2241 value = emacs_mktime_z (tz, &tm);
2242 xtzfree (tz);
2244 if (value == (time_t) -1)
2245 time_overflow ();
2247 return list2i (hi_time (value), lo_time (value));
2250 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string,
2251 0, 2, 0,
2252 doc: /* Return the current local time, as a human-readable string.
2253 Programs can use this function to decode a time,
2254 since the number of columns in each field is fixed
2255 if the year is in the range 1000-9999.
2256 The format is `Sun Sep 16 01:03:52 1973'.
2257 However, see also the functions `decode-time' and `format-time-string'
2258 which provide a much more powerful and general facility.
2260 If SPECIFIED-TIME is given, it is a time to format instead of the
2261 current time. The argument should have the form (HIGH LOW . IGNORED).
2262 Thus, you can use times obtained from `current-time' and from
2263 `file-attributes'. SPECIFIED-TIME can also be a single integer number
2264 of seconds since the epoch. The obsolete form (HIGH . LOW) is also
2265 still accepted.
2267 The optional ZONE is omitted or nil for Emacs local time, t for
2268 Universal Time, `wall' for system wall clock time, or a string as in
2269 the TZ environment variable. It can also be a list (as from
2270 `current-time-zone') or an integer (as from `decode-time') applied
2271 without consideration for daylight saving time. */)
2272 (Lisp_Object specified_time, Lisp_Object zone)
2274 time_t value = lisp_seconds_argument (specified_time);
2275 timezone_t tz = tzlookup (zone, false);
2277 /* Convert to a string in ctime format, except without the trailing
2278 newline, and without the 4-digit year limit. Don't use asctime
2279 or ctime, as they might dump core if the year is outside the
2280 range -999 .. 9999. */
2281 struct tm tm;
2282 struct tm *tmp = emacs_localtime_rz (tz, &value, &tm);
2283 xtzfree (tz);
2284 if (! tmp)
2285 time_overflow ();
2287 static char const wday_name[][4] =
2288 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2289 static char const mon_name[][4] =
2290 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2291 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2292 printmax_t year_base = TM_YEAR_BASE;
2293 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2294 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2295 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2296 tm.tm_hour, tm.tm_min, tm.tm_sec,
2297 tm.tm_year + year_base);
2299 return make_unibyte_string (buf, len);
2302 /* Yield A - B, measured in seconds.
2303 This function is copied from the GNU C Library. */
2304 static int
2305 tm_diff (struct tm *a, struct tm *b)
2307 /* Compute intervening leap days correctly even if year is negative.
2308 Take care to avoid int overflow in leap day calculations,
2309 but it's OK to assume that A and B are close to each other. */
2310 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2311 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2312 int a100 = a4 / 25 - (a4 % 25 < 0);
2313 int b100 = b4 / 25 - (b4 % 25 < 0);
2314 int a400 = a100 >> 2;
2315 int b400 = b100 >> 2;
2316 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2317 int years = a->tm_year - b->tm_year;
2318 int days = (365 * years + intervening_leap_days
2319 + (a->tm_yday - b->tm_yday));
2320 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2321 + (a->tm_min - b->tm_min))
2322 + (a->tm_sec - b->tm_sec));
2325 /* Yield A's UTC offset, or an unspecified value if unknown. */
2326 static long int
2327 tm_gmtoff (struct tm *a)
2329 #if HAVE_TM_GMTOFF
2330 return a->tm_gmtoff;
2331 #else
2332 return 0;
2333 #endif
2336 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 2, 0,
2337 doc: /* Return the offset and name for the local time zone.
2338 This returns a list of the form (OFFSET NAME).
2339 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2340 A negative value means west of Greenwich.
2341 NAME is a string giving the name of the time zone.
2342 If SPECIFIED-TIME is given, the time zone offset is determined from it
2343 instead of using the current time. The argument should have the form
2344 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2345 `current-time' and from `file-attributes'. SPECIFIED-TIME can also be
2346 a single integer number of seconds since the epoch. The obsolete form
2347 (HIGH . LOW) is also still accepted.
2349 The optional ZONE is omitted or nil for Emacs local time, t for
2350 Universal Time, `wall' for system wall clock time, or a string as in
2351 the TZ environment variable. It can also be a list (as from
2352 `current-time-zone') or an integer (as from `decode-time') applied
2353 without consideration for daylight saving time.
2355 Some operating systems cannot provide all this information to Emacs;
2356 in this case, `current-time-zone' returns a list containing nil for
2357 the data it can't find. */)
2358 (Lisp_Object specified_time, Lisp_Object zone)
2360 struct timespec value;
2361 struct tm local_tm, gmt_tm;
2362 Lisp_Object zone_offset, zone_name;
2364 zone_offset = Qnil;
2365 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2366 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value,
2367 zone, &local_tm);
2369 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2370 timespec on some systems (MinGW) is a 64-bit field. */
2371 time_t tsec = value.tv_sec;
2372 if (HAVE_TM_GMTOFF || gmtime_r (&tsec, &gmt_tm))
2374 long int offset = (HAVE_TM_GMTOFF
2375 ? tm_gmtoff (&local_tm)
2376 : tm_diff (&local_tm, &gmt_tm));
2377 zone_offset = make_number (offset);
2378 if (SCHARS (zone_name) == 0)
2380 /* No local time zone name is available; use numeric zone instead. */
2381 long int hour = offset / 3600;
2382 int min_sec = offset % 3600;
2383 int amin_sec = min_sec < 0 ? - min_sec : min_sec;
2384 int min = amin_sec / 60;
2385 int sec = amin_sec % 60;
2386 int min_prec = min_sec ? 2 : 0;
2387 int sec_prec = sec ? 2 : 0;
2388 char buf[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2389 zone_name = make_formatted_string (buf, "%c%.2ld%.*d%.*d",
2390 (offset < 0 ? '-' : '+'),
2391 hour, min_prec, min, sec_prec, sec);
2395 return list2 (zone_offset, zone_name);
2398 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2399 doc: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2400 If TZ is nil or `wall', use system wall clock time; this differs from
2401 the usual Emacs convention where nil means current local time. If TZ
2402 is t, use Universal Time. If TZ is a list (as from
2403 `current-time-zone') or an integer (as from `decode-time'), use the
2404 specified time zone without consideration for daylight saving time.
2406 Instead of calling this function, you typically want something else.
2407 To temporarily use a different time zone rule for just one invocation
2408 of `decode-time', `encode-time', or `format-time-string', pass the
2409 function a ZONE argument. To change local time consistently
2410 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2411 environment of the Emacs process and the variable
2412 `process-environment', whereas `set-time-zone-rule' affects only the
2413 former. */)
2414 (Lisp_Object tz)
2416 tzlookup (NILP (tz) ? Qwall : tz, true);
2417 return Qnil;
2420 /* A buffer holding a string of the form "TZ=value", intended
2421 to be part of the environment. If TZ is supposed to be unset,
2422 the buffer string is "tZ=". */
2423 static char *tzvalbuf;
2425 /* Get the local time zone rule. */
2426 char *
2427 emacs_getenv_TZ (void)
2429 return tzvalbuf[0] == 'T' ? tzvalbuf + tzeqlen : 0;
2432 /* Set the local time zone rule to TZSTRING, which can be null to
2433 denote wall clock time. Do not record the setting in LOCAL_TZ.
2435 This function is not thread-safe, in theory because putenv is not,
2436 but mostly because of the static storage it updates. Other threads
2437 that invoke localtime etc. may be adversely affected while this
2438 function is executing. */
2441 emacs_setenv_TZ (const char *tzstring)
2443 static ptrdiff_t tzvalbufsize;
2444 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2445 char *tzval = tzvalbuf;
2446 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2448 if (new_tzvalbuf)
2450 /* Do not attempt to free the old tzvalbuf, since another thread
2451 may be using it. In practice, the first allocation is large
2452 enough and memory does not leak. */
2453 tzval = xpalloc (NULL, &tzvalbufsize,
2454 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2455 tzvalbuf = tzval;
2456 tzval[1] = 'Z';
2457 tzval[2] = '=';
2460 if (tzstring)
2462 /* Modify TZVAL in place. Although this is dicey in a
2463 multithreaded environment, we know of no portable alternative.
2464 Calling putenv or setenv could crash some other thread. */
2465 tzval[0] = 'T';
2466 strcpy (tzval + tzeqlen, tzstring);
2468 else
2470 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2471 Although this is also dicey, calling unsetenv here can crash Emacs.
2472 See Bug#8705. */
2473 tzval[0] = 't';
2474 tzval[tzeqlen] = 0;
2478 #ifndef WINDOWSNT
2479 /* Modifying *TZVAL merely requires calling tzset (which is the
2480 caller's responsibility). However, modifying TZVAL requires
2481 calling putenv; although this is not thread-safe, in practice this
2482 runs only on startup when there is only one thread. */
2483 bool need_putenv = new_tzvalbuf;
2484 #else
2485 /* MS-Windows 'putenv' copies the argument string into a block it
2486 allocates, so modifying *TZVAL will not change the environment.
2487 However, the other threads run by Emacs on MS-Windows never call
2488 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2489 dicey in-place modification technique doesn't exist there in the
2490 first place. */
2491 bool need_putenv = true;
2492 #endif
2493 if (need_putenv)
2494 xputenv (tzval);
2496 return 0;
2499 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2500 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2501 type of object is Lisp_String). INHERIT is passed to
2502 INSERT_FROM_STRING_FUNC as the last argument. */
2504 static void
2505 general_insert_function (void (*insert_func)
2506 (const char *, ptrdiff_t),
2507 void (*insert_from_string_func)
2508 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2509 ptrdiff_t, ptrdiff_t, bool),
2510 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2512 ptrdiff_t argnum;
2513 Lisp_Object val;
2515 for (argnum = 0; argnum < nargs; argnum++)
2517 val = args[argnum];
2518 if (CHARACTERP (val))
2520 int c = XFASTINT (val);
2521 unsigned char str[MAX_MULTIBYTE_LENGTH];
2522 int len;
2524 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2525 len = CHAR_STRING (c, str);
2526 else
2528 str[0] = CHAR_TO_BYTE8 (c);
2529 len = 1;
2531 (*insert_func) ((char *) str, len);
2533 else if (STRINGP (val))
2535 (*insert_from_string_func) (val, 0, 0,
2536 SCHARS (val),
2537 SBYTES (val),
2538 inherit);
2540 else
2541 wrong_type_argument (Qchar_or_string_p, val);
2545 void
2546 insert1 (Lisp_Object arg)
2548 Finsert (1, &arg);
2552 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2553 doc: /* Insert the arguments, either strings or characters, at point.
2554 Point and after-insertion markers move forward to end up
2555 after the inserted text.
2556 Any other markers at the point of insertion remain before the text.
2558 If the current buffer is multibyte, unibyte strings are converted
2559 to multibyte for insertion (see `string-make-multibyte').
2560 If the current buffer is unibyte, multibyte strings are converted
2561 to unibyte for insertion (see `string-make-unibyte').
2563 When operating on binary data, it may be necessary to preserve the
2564 original bytes of a unibyte string when inserting it into a multibyte
2565 buffer; to accomplish this, apply `string-as-multibyte' to the string
2566 and insert the result.
2568 usage: (insert &rest ARGS) */)
2569 (ptrdiff_t nargs, Lisp_Object *args)
2571 general_insert_function (insert, insert_from_string, 0, nargs, args);
2572 return Qnil;
2575 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2576 0, MANY, 0,
2577 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2578 Point and after-insertion markers move forward to end up
2579 after the inserted text.
2580 Any other markers at the point of insertion remain before the text.
2582 If the current buffer is multibyte, unibyte strings are converted
2583 to multibyte for insertion (see `unibyte-char-to-multibyte').
2584 If the current buffer is unibyte, multibyte strings are converted
2585 to unibyte for insertion.
2587 usage: (insert-and-inherit &rest ARGS) */)
2588 (ptrdiff_t nargs, Lisp_Object *args)
2590 general_insert_function (insert_and_inherit, insert_from_string, 1,
2591 nargs, args);
2592 return Qnil;
2595 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2596 doc: /* Insert strings or characters at point, relocating markers after the text.
2597 Point and markers move forward to end up after the inserted text.
2599 If the current buffer is multibyte, unibyte strings are converted
2600 to multibyte for insertion (see `unibyte-char-to-multibyte').
2601 If the current buffer is unibyte, multibyte strings are converted
2602 to unibyte for insertion.
2604 If an overlay begins at the insertion point, the inserted text falls
2605 outside the overlay; if a nonempty overlay ends at the insertion
2606 point, the inserted text falls inside that overlay.
2608 usage: (insert-before-markers &rest ARGS) */)
2609 (ptrdiff_t nargs, Lisp_Object *args)
2611 general_insert_function (insert_before_markers,
2612 insert_from_string_before_markers, 0,
2613 nargs, args);
2614 return Qnil;
2617 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2618 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2619 doc: /* Insert text at point, relocating markers and inheriting properties.
2620 Point and markers move forward to end up after the inserted text.
2622 If the current buffer is multibyte, unibyte strings are converted
2623 to multibyte for insertion (see `unibyte-char-to-multibyte').
2624 If the current buffer is unibyte, multibyte strings are converted
2625 to unibyte for insertion.
2627 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2628 (ptrdiff_t nargs, Lisp_Object *args)
2630 general_insert_function (insert_before_markers_and_inherit,
2631 insert_from_string_before_markers, 1,
2632 nargs, args);
2633 return Qnil;
2636 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2637 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2638 (prefix-numeric-value current-prefix-arg)\
2639 t))",
2640 doc: /* Insert COUNT copies of CHARACTER.
2641 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2642 of these ways:
2644 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2645 Completion is available; if you type a substring of the name
2646 preceded by an asterisk `*', Emacs shows all names which include
2647 that substring, not necessarily at the beginning of the name.
2649 - As a hexadecimal code point, e.g. 263A. Note that code points in
2650 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2651 the Unicode code space).
2653 - As a code point with a radix specified with #, e.g. #o21430
2654 (octal), #x2318 (hex), or #10r8984 (decimal).
2656 If called interactively, COUNT is given by the prefix argument. If
2657 omitted or nil, it defaults to 1.
2659 Inserting the character(s) relocates point and before-insertion
2660 markers in the same ways as the function `insert'.
2662 The optional third argument INHERIT, if non-nil, says to inherit text
2663 properties from adjoining text, if those properties are sticky. If
2664 called interactively, INHERIT is t. */)
2665 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2667 int i, stringlen;
2668 register ptrdiff_t n;
2669 int c, len;
2670 unsigned char str[MAX_MULTIBYTE_LENGTH];
2671 char string[4000];
2673 CHECK_CHARACTER (character);
2674 if (NILP (count))
2675 XSETFASTINT (count, 1);
2676 CHECK_NUMBER (count);
2677 c = XFASTINT (character);
2679 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2680 len = CHAR_STRING (c, str);
2681 else
2682 str[0] = c, len = 1;
2683 if (XINT (count) <= 0)
2684 return Qnil;
2685 if (BUF_BYTES_MAX / len < XINT (count))
2686 buffer_overflow ();
2687 n = XINT (count) * len;
2688 stringlen = min (n, sizeof string - sizeof string % len);
2689 for (i = 0; i < stringlen; i++)
2690 string[i] = str[i % len];
2691 while (n > stringlen)
2693 maybe_quit ();
2694 if (!NILP (inherit))
2695 insert_and_inherit (string, stringlen);
2696 else
2697 insert (string, stringlen);
2698 n -= stringlen;
2700 if (!NILP (inherit))
2701 insert_and_inherit (string, n);
2702 else
2703 insert (string, n);
2704 return Qnil;
2707 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2708 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2709 Both arguments are required.
2710 BYTE is a number of the range 0..255.
2712 If BYTE is 128..255 and the current buffer is multibyte, the
2713 corresponding eight-bit character is inserted.
2715 Point, and before-insertion markers, are relocated as in the function `insert'.
2716 The optional third arg INHERIT, if non-nil, says to inherit text properties
2717 from adjoining text, if those properties are sticky. */)
2718 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2720 CHECK_NUMBER (byte);
2721 if (XINT (byte) < 0 || XINT (byte) > 255)
2722 args_out_of_range_3 (byte, make_number (0), make_number (255));
2723 if (XINT (byte) >= 128
2724 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2725 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2726 return Finsert_char (byte, count, inherit);
2730 /* Making strings from buffer contents. */
2732 /* Return a Lisp_String containing the text of the current buffer from
2733 START to END. If text properties are in use and the current buffer
2734 has properties in the range specified, the resulting string will also
2735 have them, if PROPS is true.
2737 We don't want to use plain old make_string here, because it calls
2738 make_uninit_string, which can cause the buffer arena to be
2739 compacted. make_string has no way of knowing that the data has
2740 been moved, and thus copies the wrong data into the string. This
2741 doesn't effect most of the other users of make_string, so it should
2742 be left as is. But we should use this function when conjuring
2743 buffer substrings. */
2745 Lisp_Object
2746 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2748 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2749 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2751 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2754 /* Return a Lisp_String containing the text of the current buffer from
2755 START / START_BYTE to END / END_BYTE.
2757 If text properties are in use and the current buffer
2758 has properties in the range specified, the resulting string will also
2759 have them, if PROPS is true.
2761 We don't want to use plain old make_string here, because it calls
2762 make_uninit_string, which can cause the buffer arena to be
2763 compacted. make_string has no way of knowing that the data has
2764 been moved, and thus copies the wrong data into the string. This
2765 doesn't effect most of the other users of make_string, so it should
2766 be left as is. But we should use this function when conjuring
2767 buffer substrings. */
2769 Lisp_Object
2770 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2771 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2773 Lisp_Object result, tem, tem1;
2774 ptrdiff_t beg0, end0, beg1, end1, size;
2776 if (start_byte < GPT_BYTE && GPT_BYTE < end_byte)
2778 /* Two regions, before and after the gap. */
2779 beg0 = start_byte;
2780 end0 = GPT_BYTE;
2781 beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
2782 end1 = end_byte + GAP_SIZE - BEG_BYTE;
2784 else
2786 /* The only region. */
2787 beg0 = start_byte;
2788 end0 = end_byte;
2789 beg1 = -1;
2790 end1 = -1;
2793 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2794 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2795 else
2796 result = make_uninit_string (end - start);
2798 size = end0 - beg0;
2799 memcpy (SDATA (result), BYTE_POS_ADDR (beg0), size);
2800 if (beg1 != -1)
2801 memcpy (SDATA (result) + size, BEG_ADDR + beg1, end1 - beg1);
2803 /* If desired, update and copy the text properties. */
2804 if (props)
2806 update_buffer_properties (start, end);
2808 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2809 tem1 = Ftext_properties_at (make_number (start), Qnil);
2811 if (XINT (tem) != end || !NILP (tem1))
2812 copy_intervals_to_string (result, current_buffer, start,
2813 end - start);
2816 return result;
2819 /* Call Vbuffer_access_fontify_functions for the range START ... END
2820 in the current buffer, if necessary. */
2822 static void
2823 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2825 /* If this buffer has some access functions,
2826 call them, specifying the range of the buffer being accessed. */
2827 if (!NILP (Vbuffer_access_fontify_functions))
2829 /* But don't call them if we can tell that the work
2830 has already been done. */
2831 if (!NILP (Vbuffer_access_fontified_property))
2833 Lisp_Object tem
2834 = Ftext_property_any (make_number (start), make_number (end),
2835 Vbuffer_access_fontified_property,
2836 Qnil, Qnil);
2837 if (NILP (tem))
2838 return;
2841 CALLN (Frun_hook_with_args, Qbuffer_access_fontify_functions,
2842 make_number (start), make_number (end));
2846 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2847 doc: /* Return the contents of part of the current buffer as a string.
2848 The two arguments START and END are character positions;
2849 they can be in either order.
2850 The string returned is multibyte if the buffer is multibyte.
2852 This function copies the text properties of that part of the buffer
2853 into the result string; if you don't want the text properties,
2854 use `buffer-substring-no-properties' instead. */)
2855 (Lisp_Object start, Lisp_Object end)
2857 register ptrdiff_t b, e;
2859 validate_region (&start, &end);
2860 b = XINT (start);
2861 e = XINT (end);
2863 return make_buffer_string (b, e, 1);
2866 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2867 Sbuffer_substring_no_properties, 2, 2, 0,
2868 doc: /* Return the characters of part of the buffer, without the text properties.
2869 The two arguments START and END are character positions;
2870 they can be in either order. */)
2871 (Lisp_Object start, Lisp_Object end)
2873 register ptrdiff_t b, e;
2875 validate_region (&start, &end);
2876 b = XINT (start);
2877 e = XINT (end);
2879 return make_buffer_string (b, e, 0);
2882 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2883 doc: /* Return the contents of the current buffer as a string.
2884 If narrowing is in effect, this function returns only the visible part
2885 of the buffer. */)
2886 (void)
2888 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2891 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2892 1, 3, 0,
2893 doc: /* Insert before point a substring of the contents of BUFFER.
2894 BUFFER may be a buffer or a buffer name.
2895 Arguments START and END are character positions specifying the substring.
2896 They default to the values of (point-min) and (point-max) in BUFFER.
2898 Point and before-insertion markers move forward to end up after the
2899 inserted text.
2900 Any other markers at the point of insertion remain before the text.
2902 If the current buffer is multibyte and BUFFER is unibyte, or vice
2903 versa, strings are converted from unibyte to multibyte or vice versa
2904 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2905 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2907 register EMACS_INT b, e, temp;
2908 register struct buffer *bp, *obuf;
2909 Lisp_Object buf;
2911 buf = Fget_buffer (buffer);
2912 if (NILP (buf))
2913 nsberror (buffer);
2914 bp = XBUFFER (buf);
2915 if (!BUFFER_LIVE_P (bp))
2916 error ("Selecting deleted buffer");
2918 if (NILP (start))
2919 b = BUF_BEGV (bp);
2920 else
2922 CHECK_NUMBER_COERCE_MARKER (start);
2923 b = XINT (start);
2925 if (NILP (end))
2926 e = BUF_ZV (bp);
2927 else
2929 CHECK_NUMBER_COERCE_MARKER (end);
2930 e = XINT (end);
2933 if (b > e)
2934 temp = b, b = e, e = temp;
2936 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2937 args_out_of_range (start, end);
2939 obuf = current_buffer;
2940 set_buffer_internal_1 (bp);
2941 update_buffer_properties (b, e);
2942 set_buffer_internal_1 (obuf);
2944 insert_from_buffer (bp, b, e - b, 0);
2945 return Qnil;
2948 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2949 6, 6, 0,
2950 doc: /* Compare two substrings of two buffers; return result as number.
2951 Return -N if first string is less after N-1 chars, +N if first string is
2952 greater after N-1 chars, or 0 if strings match.
2953 The first substring is in BUFFER1 from START1 to END1 and the second
2954 is in BUFFER2 from START2 to END2.
2955 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2956 buffer is used. If START1 or START2 is nil, the value of `point-min'
2957 in the respective buffers is used. If END1 or END2 is nil, the value
2958 of `point-max' in the respective buffers is used.
2959 The value of `case-fold-search' in the current buffer
2960 determines whether case is significant or ignored. */)
2961 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2963 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2964 register struct buffer *bp1, *bp2;
2965 register Lisp_Object trt
2966 = (!NILP (BVAR (current_buffer, case_fold_search))
2967 ? BVAR (current_buffer, case_canon_table) : Qnil);
2968 ptrdiff_t chars = 0;
2969 ptrdiff_t i1, i2, i1_byte, i2_byte;
2971 /* Find the first buffer and its substring. */
2973 if (NILP (buffer1))
2974 bp1 = current_buffer;
2975 else
2977 Lisp_Object buf1;
2978 buf1 = Fget_buffer (buffer1);
2979 if (NILP (buf1))
2980 nsberror (buffer1);
2981 bp1 = XBUFFER (buf1);
2982 if (!BUFFER_LIVE_P (bp1))
2983 error ("Selecting deleted buffer");
2986 if (NILP (start1))
2987 begp1 = BUF_BEGV (bp1);
2988 else
2990 CHECK_NUMBER_COERCE_MARKER (start1);
2991 begp1 = XINT (start1);
2993 if (NILP (end1))
2994 endp1 = BUF_ZV (bp1);
2995 else
2997 CHECK_NUMBER_COERCE_MARKER (end1);
2998 endp1 = XINT (end1);
3001 if (begp1 > endp1)
3002 temp = begp1, begp1 = endp1, endp1 = temp;
3004 if (!(BUF_BEGV (bp1) <= begp1
3005 && begp1 <= endp1
3006 && endp1 <= BUF_ZV (bp1)))
3007 args_out_of_range (start1, end1);
3009 /* Likewise for second substring. */
3011 if (NILP (buffer2))
3012 bp2 = current_buffer;
3013 else
3015 Lisp_Object buf2;
3016 buf2 = Fget_buffer (buffer2);
3017 if (NILP (buf2))
3018 nsberror (buffer2);
3019 bp2 = XBUFFER (buf2);
3020 if (!BUFFER_LIVE_P (bp2))
3021 error ("Selecting deleted buffer");
3024 if (NILP (start2))
3025 begp2 = BUF_BEGV (bp2);
3026 else
3028 CHECK_NUMBER_COERCE_MARKER (start2);
3029 begp2 = XINT (start2);
3031 if (NILP (end2))
3032 endp2 = BUF_ZV (bp2);
3033 else
3035 CHECK_NUMBER_COERCE_MARKER (end2);
3036 endp2 = XINT (end2);
3039 if (begp2 > endp2)
3040 temp = begp2, begp2 = endp2, endp2 = temp;
3042 if (!(BUF_BEGV (bp2) <= begp2
3043 && begp2 <= endp2
3044 && endp2 <= BUF_ZV (bp2)))
3045 args_out_of_range (start2, end2);
3047 i1 = begp1;
3048 i2 = begp2;
3049 i1_byte = buf_charpos_to_bytepos (bp1, i1);
3050 i2_byte = buf_charpos_to_bytepos (bp2, i2);
3052 while (i1 < endp1 && i2 < endp2)
3054 /* When we find a mismatch, we must compare the
3055 characters, not just the bytes. */
3056 int c1, c2;
3058 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
3060 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
3061 BUF_INC_POS (bp1, i1_byte);
3062 i1++;
3064 else
3066 c1 = BUF_FETCH_BYTE (bp1, i1);
3067 MAKE_CHAR_MULTIBYTE (c1);
3068 i1++;
3071 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
3073 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
3074 BUF_INC_POS (bp2, i2_byte);
3075 i2++;
3077 else
3079 c2 = BUF_FETCH_BYTE (bp2, i2);
3080 MAKE_CHAR_MULTIBYTE (c2);
3081 i2++;
3084 if (!NILP (trt))
3086 c1 = char_table_translate (trt, c1);
3087 c2 = char_table_translate (trt, c2);
3090 if (c1 != c2)
3091 return make_number (c1 < c2 ? -1 - chars : chars + 1);
3093 chars++;
3094 rarely_quit (chars);
3097 /* The strings match as far as they go.
3098 If one is shorter, that one is less. */
3099 if (chars < endp1 - begp1)
3100 return make_number (chars + 1);
3101 else if (chars < endp2 - begp2)
3102 return make_number (- chars - 1);
3104 /* Same length too => they are equal. */
3105 return make_number (0);
3108 static void
3109 subst_char_in_region_unwind (Lisp_Object arg)
3111 bset_undo_list (current_buffer, arg);
3114 static void
3115 subst_char_in_region_unwind_1 (Lisp_Object arg)
3117 bset_filename (current_buffer, arg);
3120 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
3121 Ssubst_char_in_region, 4, 5, 0,
3122 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3123 If optional arg NOUNDO is non-nil, don't record this change for undo
3124 and don't mark the buffer as really changed.
3125 Both characters must have the same length of multi-byte form. */)
3126 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
3128 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
3129 /* Keep track of the first change in the buffer:
3130 if 0 we haven't found it yet.
3131 if < 0 we've found it and we've run the before-change-function.
3132 if > 0 we've actually performed it and the value is its position. */
3133 ptrdiff_t changed = 0;
3134 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
3135 unsigned char *p;
3136 ptrdiff_t count = SPECPDL_INDEX ();
3137 #define COMBINING_NO 0
3138 #define COMBINING_BEFORE 1
3139 #define COMBINING_AFTER 2
3140 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3141 int maybe_byte_combining = COMBINING_NO;
3142 ptrdiff_t last_changed = 0;
3143 bool multibyte_p
3144 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3145 int fromc, toc;
3147 restart:
3149 validate_region (&start, &end);
3150 CHECK_CHARACTER (fromchar);
3151 CHECK_CHARACTER (tochar);
3152 fromc = XFASTINT (fromchar);
3153 toc = XFASTINT (tochar);
3155 if (multibyte_p)
3157 len = CHAR_STRING (fromc, fromstr);
3158 if (CHAR_STRING (toc, tostr) != len)
3159 error ("Characters in `subst-char-in-region' have different byte-lengths");
3160 if (!ASCII_CHAR_P (*tostr))
3162 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3163 complete multibyte character, it may be combined with the
3164 after bytes. If it is in the range 0xA0..0xFF, it may be
3165 combined with the before and after bytes. */
3166 if (!CHAR_HEAD_P (*tostr))
3167 maybe_byte_combining = COMBINING_BOTH;
3168 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3169 maybe_byte_combining = COMBINING_AFTER;
3172 else
3174 len = 1;
3175 fromstr[0] = fromc;
3176 tostr[0] = toc;
3179 pos = XINT (start);
3180 pos_byte = CHAR_TO_BYTE (pos);
3181 stop = CHAR_TO_BYTE (XINT (end));
3182 end_byte = stop;
3184 /* If we don't want undo, turn off putting stuff on the list.
3185 That's faster than getting rid of things,
3186 and it prevents even the entry for a first change.
3187 Also inhibit locking the file. */
3188 if (!changed && !NILP (noundo))
3190 record_unwind_protect (subst_char_in_region_unwind,
3191 BVAR (current_buffer, undo_list));
3192 bset_undo_list (current_buffer, Qt);
3193 /* Don't do file-locking. */
3194 record_unwind_protect (subst_char_in_region_unwind_1,
3195 BVAR (current_buffer, filename));
3196 bset_filename (current_buffer, Qnil);
3199 if (pos_byte < GPT_BYTE)
3200 stop = min (stop, GPT_BYTE);
3201 while (1)
3203 ptrdiff_t pos_byte_next = pos_byte;
3205 if (pos_byte >= stop)
3207 if (pos_byte >= end_byte) break;
3208 stop = end_byte;
3210 p = BYTE_POS_ADDR (pos_byte);
3211 if (multibyte_p)
3212 INC_POS (pos_byte_next);
3213 else
3214 ++pos_byte_next;
3215 if (pos_byte_next - pos_byte == len
3216 && p[0] == fromstr[0]
3217 && (len == 1
3218 || (p[1] == fromstr[1]
3219 && (len == 2 || (p[2] == fromstr[2]
3220 && (len == 3 || p[3] == fromstr[3]))))))
3222 if (changed < 0)
3223 /* We've already seen this and run the before-change-function;
3224 this time we only need to record the actual position. */
3225 changed = pos;
3226 else if (!changed)
3228 changed = -1;
3229 modify_text (pos, XINT (end));
3231 if (! NILP (noundo))
3233 if (MODIFF - 1 == SAVE_MODIFF)
3234 SAVE_MODIFF++;
3235 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3236 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3239 /* The before-change-function may have moved the gap
3240 or even modified the buffer so we should start over. */
3241 goto restart;
3244 /* Take care of the case where the new character
3245 combines with neighboring bytes. */
3246 if (maybe_byte_combining
3247 && (maybe_byte_combining == COMBINING_AFTER
3248 ? (pos_byte_next < Z_BYTE
3249 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3250 : ((pos_byte_next < Z_BYTE
3251 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3252 || (pos_byte > BEG_BYTE
3253 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3255 Lisp_Object tem, string;
3257 tem = BVAR (current_buffer, undo_list);
3259 /* Make a multibyte string containing this single character. */
3260 string = make_multibyte_string ((char *) tostr, 1, len);
3261 /* replace_range is less efficient, because it moves the gap,
3262 but it handles combining correctly. */
3263 replace_range (pos, pos + 1, string,
3264 0, 0, 1, 0);
3265 pos_byte_next = CHAR_TO_BYTE (pos);
3266 if (pos_byte_next > pos_byte)
3267 /* Before combining happened. We should not increment
3268 POS. So, to cancel the later increment of POS,
3269 decrease it now. */
3270 pos--;
3271 else
3272 INC_POS (pos_byte_next);
3274 if (! NILP (noundo))
3275 bset_undo_list (current_buffer, tem);
3277 else
3279 if (NILP (noundo))
3280 record_change (pos, 1);
3281 for (i = 0; i < len; i++) *p++ = tostr[i];
3283 last_changed = pos + 1;
3285 pos_byte = pos_byte_next;
3286 pos++;
3289 if (changed > 0)
3291 signal_after_change (changed,
3292 last_changed - changed, last_changed - changed);
3293 update_compositions (changed, last_changed, CHECK_ALL);
3296 unbind_to (count, Qnil);
3297 return Qnil;
3301 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3302 Lisp_Object);
3304 /* Helper function for Ftranslate_region_internal.
3306 Check if a character sequence at POS (POS_BYTE) matches an element
3307 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3308 element is found, return it. Otherwise return Qnil. */
3310 static Lisp_Object
3311 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3312 Lisp_Object val)
3314 int initial_buf[16];
3315 int *buf = initial_buf;
3316 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3317 int *bufalloc = 0;
3318 ptrdiff_t buf_used = 0;
3319 Lisp_Object result = Qnil;
3321 for (; CONSP (val); val = XCDR (val))
3323 Lisp_Object elt;
3324 ptrdiff_t len, i;
3326 elt = XCAR (val);
3327 if (! CONSP (elt))
3328 continue;
3329 elt = XCAR (elt);
3330 if (! VECTORP (elt))
3331 continue;
3332 len = ASIZE (elt);
3333 if (len <= end - pos)
3335 for (i = 0; i < len; i++)
3337 if (buf_used <= i)
3339 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3340 int len1;
3342 if (buf_used == buf_size)
3344 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3345 sizeof *bufalloc);
3346 if (buf == initial_buf)
3347 memcpy (bufalloc, buf, sizeof initial_buf);
3348 buf = bufalloc;
3350 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3351 pos_byte += len1;
3353 if (XINT (AREF (elt, i)) != buf[i])
3354 break;
3356 if (i == len)
3358 result = XCAR (val);
3359 break;
3364 xfree (bufalloc);
3365 return result;
3369 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3370 Stranslate_region_internal, 3, 3, 0,
3371 doc: /* Internal use only.
3372 From START to END, translate characters according to TABLE.
3373 TABLE is a string or a char-table; the Nth character in it is the
3374 mapping for the character with code N.
3375 It returns the number of characters changed. */)
3376 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3378 register unsigned char *tt; /* Trans table. */
3379 register int nc; /* New character. */
3380 int cnt; /* Number of changes made. */
3381 ptrdiff_t size; /* Size of translate table. */
3382 ptrdiff_t pos, pos_byte, end_pos;
3383 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3384 bool string_multibyte UNINIT;
3386 validate_region (&start, &end);
3387 if (CHAR_TABLE_P (table))
3389 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3390 error ("Not a translation table");
3391 size = MAX_CHAR;
3392 tt = NULL;
3394 else
3396 CHECK_STRING (table);
3398 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3399 table = string_make_unibyte (table);
3400 string_multibyte = SCHARS (table) < SBYTES (table);
3401 size = SBYTES (table);
3402 tt = SDATA (table);
3405 pos = XINT (start);
3406 pos_byte = CHAR_TO_BYTE (pos);
3407 end_pos = XINT (end);
3408 modify_text (pos, end_pos);
3410 cnt = 0;
3411 for (; pos < end_pos; )
3413 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3414 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3415 int len, str_len;
3416 int oc;
3417 Lisp_Object val;
3419 if (multibyte)
3420 oc = STRING_CHAR_AND_LENGTH (p, len);
3421 else
3422 oc = *p, len = 1;
3423 if (oc < size)
3425 if (tt)
3427 /* Reload as signal_after_change in last iteration may GC. */
3428 tt = SDATA (table);
3429 if (string_multibyte)
3431 str = tt + string_char_to_byte (table, oc);
3432 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3434 else
3436 nc = tt[oc];
3437 if (! ASCII_CHAR_P (nc) && multibyte)
3439 str_len = BYTE8_STRING (nc, buf);
3440 str = buf;
3442 else
3444 str_len = 1;
3445 str = tt + oc;
3449 else
3451 nc = oc;
3452 val = CHAR_TABLE_REF (table, oc);
3453 if (CHARACTERP (val))
3455 nc = XFASTINT (val);
3456 str_len = CHAR_STRING (nc, buf);
3457 str = buf;
3459 else if (VECTORP (val) || (CONSP (val)))
3461 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3462 where TO is TO-CHAR or [TO-CHAR ...]. */
3463 nc = -1;
3467 if (nc != oc && nc >= 0)
3469 /* Simple one char to one char translation. */
3470 if (len != str_len)
3472 Lisp_Object string;
3474 /* This is less efficient, because it moves the gap,
3475 but it should handle multibyte characters correctly. */
3476 string = make_multibyte_string ((char *) str, 1, str_len);
3477 replace_range (pos, pos + 1, string, 1, 0, 1, 0);
3478 len = str_len;
3480 else
3482 record_change (pos, 1);
3483 while (str_len-- > 0)
3484 *p++ = *str++;
3485 signal_after_change (pos, 1, 1);
3486 update_compositions (pos, pos + 1, CHECK_BORDER);
3488 ++cnt;
3490 else if (nc < 0)
3492 Lisp_Object string;
3494 if (CONSP (val))
3496 val = check_translation (pos, pos_byte, end_pos, val);
3497 if (NILP (val))
3499 pos_byte += len;
3500 pos++;
3501 continue;
3503 /* VAL is ([FROM-CHAR ...] . TO). */
3504 len = ASIZE (XCAR (val));
3505 val = XCDR (val);
3507 else
3508 len = 1;
3510 if (VECTORP (val))
3512 string = Fconcat (1, &val);
3514 else
3516 string = Fmake_string (make_number (1), val);
3518 replace_range (pos, pos + len, string, 1, 0, 1, 0);
3519 pos_byte += SBYTES (string);
3520 pos += SCHARS (string);
3521 cnt += SCHARS (string);
3522 end_pos += SCHARS (string) - len;
3523 continue;
3526 pos_byte += len;
3527 pos++;
3530 return make_number (cnt);
3533 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3534 doc: /* Delete the text between START and END.
3535 If called interactively, delete the region between point and mark.
3536 This command deletes buffer text without modifying the kill ring. */)
3537 (Lisp_Object start, Lisp_Object end)
3539 validate_region (&start, &end);
3540 del_range (XINT (start), XINT (end));
3541 return Qnil;
3544 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3545 Sdelete_and_extract_region, 2, 2, 0,
3546 doc: /* Delete the text between START and END and return it. */)
3547 (Lisp_Object start, Lisp_Object end)
3549 validate_region (&start, &end);
3550 if (XINT (start) == XINT (end))
3551 return empty_unibyte_string;
3552 return del_range_1 (XINT (start), XINT (end), 1, 1);
3555 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3556 doc: /* Remove restrictions (narrowing) from current buffer.
3557 This allows the buffer's full text to be seen and edited. */)
3558 (void)
3560 if (BEG != BEGV || Z != ZV)
3561 current_buffer->clip_changed = 1;
3562 BEGV = BEG;
3563 BEGV_BYTE = BEG_BYTE;
3564 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3565 /* Changing the buffer bounds invalidates any recorded current column. */
3566 invalidate_current_column ();
3567 return Qnil;
3570 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3571 doc: /* Restrict editing in this buffer to the current region.
3572 The rest of the text becomes temporarily invisible and untouchable
3573 but is not deleted; if you save the buffer in a file, the invisible
3574 text is included in the file. \\[widen] makes all visible again.
3575 See also `save-restriction'.
3577 When calling from a program, pass two arguments; positions (integers
3578 or markers) bounding the text that should remain visible. */)
3579 (register Lisp_Object start, Lisp_Object end)
3581 CHECK_NUMBER_COERCE_MARKER (start);
3582 CHECK_NUMBER_COERCE_MARKER (end);
3584 if (XINT (start) > XINT (end))
3586 Lisp_Object tem;
3587 tem = start; start = end; end = tem;
3590 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3591 args_out_of_range (start, end);
3593 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3594 current_buffer->clip_changed = 1;
3596 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3597 SET_BUF_ZV (current_buffer, XFASTINT (end));
3598 if (PT < XFASTINT (start))
3599 SET_PT (XFASTINT (start));
3600 if (PT > XFASTINT (end))
3601 SET_PT (XFASTINT (end));
3602 /* Changing the buffer bounds invalidates any recorded current column. */
3603 invalidate_current_column ();
3604 return Qnil;
3607 Lisp_Object
3608 save_restriction_save (void)
3610 if (BEGV == BEG && ZV == Z)
3611 /* The common case that the buffer isn't narrowed.
3612 We return just the buffer object, which save_restriction_restore
3613 recognizes as meaning `no restriction'. */
3614 return Fcurrent_buffer ();
3615 else
3616 /* We have to save a restriction, so return a pair of markers, one
3617 for the beginning and one for the end. */
3619 Lisp_Object beg, end;
3621 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3622 end = build_marker (current_buffer, ZV, ZV_BYTE);
3624 /* END must move forward if text is inserted at its exact location. */
3625 XMARKER (end)->insertion_type = 1;
3627 return Fcons (beg, end);
3631 void
3632 save_restriction_restore (Lisp_Object data)
3634 struct buffer *cur = NULL;
3635 struct buffer *buf = (CONSP (data)
3636 ? XMARKER (XCAR (data))->buffer
3637 : XBUFFER (data));
3639 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3640 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3641 is the case if it is or has an indirect buffer), then make
3642 sure it is current before we update BEGV, so
3643 set_buffer_internal takes care of managing those markers. */
3644 cur = current_buffer;
3645 set_buffer_internal (buf);
3648 if (CONSP (data))
3649 /* A pair of marks bounding a saved restriction. */
3651 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3652 struct Lisp_Marker *end = XMARKER (XCDR (data));
3653 eassert (buf == end->buffer);
3655 if (buf /* Verify marker still points to a buffer. */
3656 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3657 /* The restriction has changed from the saved one, so restore
3658 the saved restriction. */
3660 ptrdiff_t pt = BUF_PT (buf);
3662 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3663 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3665 if (pt < beg->charpos || pt > end->charpos)
3666 /* The point is outside the new visible range, move it inside. */
3667 SET_BUF_PT_BOTH (buf,
3668 clip_to_bounds (beg->charpos, pt, end->charpos),
3669 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3670 end->bytepos));
3672 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3674 /* These aren't needed anymore, so don't wait for GC. */
3675 free_marker (XCAR (data));
3676 free_marker (XCDR (data));
3677 free_cons (XCONS (data));
3679 else
3680 /* A buffer, which means that there was no old restriction. */
3682 if (buf /* Verify marker still points to a buffer. */
3683 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3684 /* The buffer has been narrowed, get rid of the narrowing. */
3686 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3687 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3689 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3693 /* Changing the buffer bounds invalidates any recorded current column. */
3694 invalidate_current_column ();
3696 if (cur)
3697 set_buffer_internal (cur);
3700 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3701 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3702 The buffer's restrictions make parts of the beginning and end invisible.
3703 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3704 This special form, `save-restriction', saves the current buffer's restrictions
3705 when it is entered, and restores them when it is exited.
3706 So any `narrow-to-region' within BODY lasts only until the end of the form.
3707 The old restrictions settings are restored
3708 even in case of abnormal exit (throw or error).
3710 The value returned is the value of the last form in BODY.
3712 Note: if you are using both `save-excursion' and `save-restriction',
3713 use `save-excursion' outermost:
3714 (save-excursion (save-restriction ...))
3716 usage: (save-restriction &rest BODY) */)
3717 (Lisp_Object body)
3719 register Lisp_Object val;
3720 ptrdiff_t count = SPECPDL_INDEX ();
3722 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3723 val = Fprogn (body);
3724 return unbind_to (count, val);
3727 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3728 doc: /* Display a message at the bottom of the screen.
3729 The message also goes into the `*Messages*' buffer, if `message-log-max'
3730 is non-nil. (In keyboard macros, that's all it does.)
3731 Return the message.
3733 In batch mode, the message is printed to the standard error stream,
3734 followed by a newline.
3736 The first argument is a format control string, and the rest are data
3737 to be formatted under control of the string. See `format-message' for
3738 details.
3740 Note: (message "%s" VALUE) displays the string VALUE without
3741 interpreting format characters like `%', `\\=`', and `\\=''.
3743 If the first argument is nil or the empty string, the function clears
3744 any existing message; this lets the minibuffer contents show. See
3745 also `current-message'.
3747 usage: (message FORMAT-STRING &rest ARGS) */)
3748 (ptrdiff_t nargs, Lisp_Object *args)
3750 if (NILP (args[0])
3751 || (STRINGP (args[0])
3752 && SBYTES (args[0]) == 0))
3754 message1 (0);
3755 return args[0];
3757 else
3759 Lisp_Object val = Fformat_message (nargs, args);
3760 message3 (val);
3761 return val;
3765 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3766 doc: /* Display a message, in a dialog box if possible.
3767 If a dialog box is not available, use the echo area.
3768 The first argument is a format control string, and the rest are data
3769 to be formatted under control of the string. See `format-message' for
3770 details.
3772 If the first argument is nil or the empty string, clear any existing
3773 message; let the minibuffer contents show.
3775 usage: (message-box FORMAT-STRING &rest ARGS) */)
3776 (ptrdiff_t nargs, Lisp_Object *args)
3778 if (NILP (args[0]))
3780 message1 (0);
3781 return Qnil;
3783 else
3785 Lisp_Object val = Fformat_message (nargs, args);
3786 Lisp_Object pane, menu;
3788 pane = list1 (Fcons (build_string ("OK"), Qt));
3789 menu = Fcons (val, pane);
3790 Fx_popup_dialog (Qt, menu, Qt);
3791 return val;
3795 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3796 doc: /* Display a message in a dialog box or in the echo area.
3797 If this command was invoked with the mouse, use a dialog box if
3798 `use-dialog-box' is non-nil.
3799 Otherwise, use the echo area.
3800 The first argument is a format control string, and the rest are data
3801 to be formatted under control of the string. See `format-message' for
3802 details.
3804 If the first argument is nil or the empty string, clear any existing
3805 message; let the minibuffer contents show.
3807 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3808 (ptrdiff_t nargs, Lisp_Object *args)
3810 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3811 && use_dialog_box)
3812 return Fmessage_box (nargs, args);
3813 return Fmessage (nargs, args);
3816 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3817 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3818 (void)
3820 return current_message ();
3824 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3825 doc: /* Return a copy of STRING with text properties added.
3826 First argument is the string to copy.
3827 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3828 properties to add to the result.
3829 usage: (propertize STRING &rest PROPERTIES) */)
3830 (ptrdiff_t nargs, Lisp_Object *args)
3832 Lisp_Object properties, string;
3833 ptrdiff_t i;
3835 /* Number of args must be odd. */
3836 if ((nargs & 1) == 0)
3837 error ("Wrong number of arguments");
3839 properties = string = Qnil;
3841 /* First argument must be a string. */
3842 CHECK_STRING (args[0]);
3843 string = Fcopy_sequence (args[0]);
3845 for (i = 1; i < nargs; i += 2)
3846 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3848 Fadd_text_properties (make_number (0),
3849 make_number (SCHARS (string)),
3850 properties, string);
3851 return string;
3854 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3855 doc: /* Format a string out of a format-string and arguments.
3856 The first argument is a format control string.
3857 The other arguments are substituted into it to make the result, a string.
3859 The format control string may contain %-sequences meaning to substitute
3860 the next available argument:
3862 %s means print a string argument. Actually, prints any object, with `princ'.
3863 %d means print as signed number in decimal.
3864 %o means print as unsigned number in octal, %x as unsigned number in hex.
3865 %X is like %x, but uses upper case.
3866 %e means print a number in exponential notation.
3867 %f means print a number in decimal-point notation.
3868 %g means print a number in exponential notation if the exponent would be
3869 less than -4 or greater than or equal to the precision (default: 6);
3870 otherwise it prints in decimal-point notation.
3871 %c means print a number as a single character.
3872 %S means print any object as an s-expression (using `prin1').
3874 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3875 Use %% to put a single % into the output.
3877 A %-sequence may contain optional flag, width, and precision
3878 specifiers, as follows:
3880 %<flags><width><precision>character
3882 where flags is [+ #-0]+, width is [0-9]+, and precision is a literal
3883 period "." followed by [0-9]+
3885 The + flag character inserts a + before any positive number, while a
3886 space inserts a space before any positive number; these flags only
3887 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3888 The - and 0 flags affect the width specifier, as described below.
3890 The # flag means to use an alternate display form for %o, %x, %X, %e,
3891 %f, and %g sequences: for %o, it ensures that the result begins with
3892 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3893 for %e and %f, it causes a decimal point to be included even if the
3894 the precision is zero; for %g, it causes a decimal point to be
3895 included even if the the precision is zero, and also forces trailing
3896 zeros after the decimal point to be left in place.
3898 The width specifier supplies a lower limit for the length of the
3899 printed representation. The padding, if any, normally goes on the
3900 left, but it goes on the right if the - flag is present. The padding
3901 character is normally a space, but it is 0 if the 0 flag is present.
3902 The 0 flag is ignored if the - flag is present, or the format sequence
3903 is something other than %d, %e, %f, and %g.
3905 For %e and %f sequences, the number after the "." in the precision
3906 specifier says how many decimal places to show; if zero, the decimal
3907 point itself is omitted. For %g, the precision specifies how many
3908 significant digits to print; zero or omitted are treated as 1.
3909 For %s and %S, the precision specifier truncates the string to the
3910 given width.
3912 Text properties, if any, are copied from the format-string to the
3913 produced text.
3915 usage: (format STRING &rest OBJECTS) */)
3916 (ptrdiff_t nargs, Lisp_Object *args)
3918 return styled_format (nargs, args, false);
3921 DEFUN ("format-message", Fformat_message, Sformat_message, 1, MANY, 0,
3922 doc: /* Format a string out of a format-string and arguments.
3923 The first argument is a format control string.
3924 The other arguments are substituted into it to make the result, a string.
3926 This acts like `format', except it also replaces each grave accent (\\=`)
3927 by a left quote, and each apostrophe (\\=') by a right quote. The left
3928 and right quote replacement characters are specified by
3929 `text-quoting-style'.
3931 usage: (format-message STRING &rest OBJECTS) */)
3932 (ptrdiff_t nargs, Lisp_Object *args)
3934 return styled_format (nargs, args, true);
3937 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise. */
3939 static Lisp_Object
3940 styled_format (ptrdiff_t nargs, Lisp_Object *args, bool message)
3942 ptrdiff_t n; /* The number of the next arg to substitute. */
3943 char initial_buffer[4000];
3944 char *buf = initial_buffer;
3945 ptrdiff_t bufsize = sizeof initial_buffer;
3946 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3947 char *p;
3948 ptrdiff_t buf_save_value_index UNINIT;
3949 char *format, *end;
3950 ptrdiff_t nchars;
3951 /* When we make a multibyte string, we must pay attention to the
3952 byte combining problem, i.e., a byte may be combined with a
3953 multibyte character of the previous string. This flag tells if we
3954 must consider such a situation or not. */
3955 bool maybe_combine_byte;
3956 bool arg_intervals = false;
3957 USE_SAFE_ALLOCA;
3959 /* Each element records, for one argument,
3960 the start and end bytepos in the output string,
3961 whether the argument has been converted to string (e.g., due to "%S"),
3962 and whether the argument is a string with intervals. */
3963 struct info
3965 ptrdiff_t start, end;
3966 bool_bf converted_to_string : 1;
3967 bool_bf intervals : 1;
3968 } *info;
3970 CHECK_STRING (args[0]);
3971 char *format_start = SSDATA (args[0]);
3972 ptrdiff_t formatlen = SBYTES (args[0]);
3974 /* Allocate the info and discarded tables. */
3975 ptrdiff_t alloca_size;
3976 if (INT_MULTIPLY_WRAPV (nargs, sizeof *info, &alloca_size)
3977 || INT_ADD_WRAPV (sizeof *info, alloca_size, &alloca_size)
3978 || INT_ADD_WRAPV (formatlen, alloca_size, &alloca_size)
3979 || SIZE_MAX < alloca_size)
3980 memory_full (SIZE_MAX);
3981 /* info[0] is unused. Unused elements have -1 for start. */
3982 info = SAFE_ALLOCA (alloca_size);
3983 memset (info, 0, alloca_size);
3984 for (ptrdiff_t i = 0; i < nargs + 1; i++)
3985 info[i].start = -1;
3986 /* discarded[I] is 1 if byte I of the format
3987 string was not copied into the output.
3988 It is 2 if byte I was not the first byte of its character. */
3989 char *discarded = (char *) &info[nargs + 1];
3991 /* Try to determine whether the result should be multibyte.
3992 This is not always right; sometimes the result needs to be multibyte
3993 because of an object that we will pass through prin1.
3994 or because a grave accent or apostrophe is requoted,
3995 and in that case, we won't know it here. */
3997 /* True if the format is multibyte. */
3998 bool multibyte_format = STRING_MULTIBYTE (args[0]);
3999 /* True if the output should be a multibyte string,
4000 which is true if any of the inputs is one. */
4001 bool multibyte = multibyte_format;
4002 for (ptrdiff_t i = 1; !multibyte && i < nargs; i++)
4003 if (STRINGP (args[i]) && STRING_MULTIBYTE (args[i]))
4004 multibyte = true;
4006 int quoting_style = message ? text_quoting_style () : -1;
4008 /* If we start out planning a unibyte result,
4009 then discover it has to be multibyte, we jump back to retry. */
4010 retry:
4012 p = buf;
4013 nchars = 0;
4014 n = 0;
4016 /* Scan the format and store result in BUF. */
4017 format = format_start;
4018 end = format + formatlen;
4019 maybe_combine_byte = false;
4021 while (format != end)
4023 /* The values of N and FORMAT when the loop body is entered. */
4024 ptrdiff_t n0 = n;
4025 char *format0 = format;
4026 char const *convsrc = format;
4027 unsigned char format_char = *format++;
4029 /* Bytes needed to represent the output of this conversion. */
4030 ptrdiff_t convbytes = 1;
4032 if (format_char == '%')
4034 /* General format specifications look like
4036 '%' [flags] [field-width] [precision] format
4038 where
4040 flags ::= [-+0# ]+
4041 field-width ::= [0-9]+
4042 precision ::= '.' [0-9]*
4044 If a field-width is specified, it specifies to which width
4045 the output should be padded with blanks, if the output
4046 string is shorter than field-width.
4048 If precision is specified, it specifies the number of
4049 digits to print after the '.' for floats, or the max.
4050 number of chars to print from a string. */
4052 bool minus_flag = false;
4053 bool plus_flag = false;
4054 bool space_flag = false;
4055 bool sharp_flag = false;
4056 bool zero_flag = false;
4058 for (; ; format++)
4060 switch (*format)
4062 case '-': minus_flag = true; continue;
4063 case '+': plus_flag = true; continue;
4064 case ' ': space_flag = true; continue;
4065 case '#': sharp_flag = true; continue;
4066 case '0': zero_flag = true; continue;
4068 break;
4071 /* Ignore flags when sprintf ignores them. */
4072 space_flag &= ! plus_flag;
4073 zero_flag &= ! minus_flag;
4075 char *num_end;
4076 uintmax_t raw_field_width = strtoumax (format, &num_end, 10);
4077 if (max_bufsize <= raw_field_width)
4078 string_overflow ();
4079 ptrdiff_t field_width = raw_field_width;
4081 bool precision_given = *num_end == '.';
4082 uintmax_t precision = (precision_given
4083 ? strtoumax (num_end + 1, &num_end, 10)
4084 : UINTMAX_MAX);
4085 format = num_end;
4087 if (format == end)
4088 error ("Format string ends in middle of format specifier");
4090 char conversion = *format++;
4091 memset (&discarded[format0 - format_start], 1,
4092 format - format0 - (conversion == '%'));
4093 if (conversion == '%')
4094 goto copy_char;
4096 ++n;
4097 if (! (n < nargs))
4098 error ("Not enough arguments for format string");
4100 /* For 'S', prin1 the argument, and then treat like 's'.
4101 For 's', princ any argument that is not a string or
4102 symbol. But don't do this conversion twice, which might
4103 happen after retrying. */
4104 if ((conversion == 'S'
4105 || (conversion == 's'
4106 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
4108 if (! info[n].converted_to_string)
4110 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
4111 args[n] = Fprin1_to_string (args[n], noescape);
4112 info[n].converted_to_string = true;
4113 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
4115 multibyte = true;
4116 goto retry;
4119 conversion = 's';
4121 else if (conversion == 'c')
4123 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
4125 if (!multibyte)
4127 multibyte = true;
4128 goto retry;
4130 args[n] = Fchar_to_string (args[n]);
4131 info[n].converted_to_string = true;
4134 if (info[n].converted_to_string)
4135 conversion = 's';
4136 zero_flag = false;
4139 if (SYMBOLP (args[n]))
4141 args[n] = SYMBOL_NAME (args[n]);
4142 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
4144 multibyte = true;
4145 goto retry;
4149 bool float_conversion
4150 = conversion == 'e' || conversion == 'f' || conversion == 'g';
4152 if (conversion == 's')
4154 /* handle case (precision[n] >= 0) */
4156 ptrdiff_t prec = -1;
4157 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
4158 prec = precision;
4160 /* lisp_string_width ignores a precision of 0, but GNU
4161 libc functions print 0 characters when the precision
4162 is 0. Imitate libc behavior here. Changing
4163 lisp_string_width is the right thing, and will be
4164 done, but meanwhile we work with it. */
4166 ptrdiff_t width, nbytes;
4167 ptrdiff_t nchars_string;
4168 if (prec == 0)
4169 width = nchars_string = nbytes = 0;
4170 else
4172 ptrdiff_t nch, nby;
4173 width = lisp_string_width (args[n], prec, &nch, &nby);
4174 if (prec < 0)
4176 nchars_string = SCHARS (args[n]);
4177 nbytes = SBYTES (args[n]);
4179 else
4181 nchars_string = nch;
4182 nbytes = nby;
4186 convbytes = nbytes;
4187 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
4188 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
4190 ptrdiff_t padding
4191 = width < field_width ? field_width - width : 0;
4193 if (max_bufsize - padding <= convbytes)
4194 string_overflow ();
4195 convbytes += padding;
4196 if (convbytes <= buf + bufsize - p)
4198 if (! minus_flag)
4200 memset (p, ' ', padding);
4201 p += padding;
4202 nchars += padding;
4204 info[n].start = nchars;
4206 if (p > buf
4207 && multibyte
4208 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4209 && STRING_MULTIBYTE (args[n])
4210 && !CHAR_HEAD_P (SREF (args[n], 0)))
4211 maybe_combine_byte = true;
4213 p += copy_text (SDATA (args[n]), (unsigned char *) p,
4214 nbytes,
4215 STRING_MULTIBYTE (args[n]), multibyte);
4217 nchars += nchars_string;
4219 if (minus_flag)
4221 memset (p, ' ', padding);
4222 p += padding;
4223 nchars += padding;
4225 info[n].end = nchars;
4227 /* If this argument has text properties, record where
4228 in the result string it appears. */
4229 if (string_intervals (args[n]))
4230 info[n].intervals = arg_intervals = true;
4232 continue;
4235 else if (! (conversion == 'c' || conversion == 'd'
4236 || float_conversion || conversion == 'i'
4237 || conversion == 'o' || conversion == 'x'
4238 || conversion == 'X'))
4239 error ("Invalid format operation %%%c",
4240 STRING_CHAR ((unsigned char *) format - 1));
4241 else if (! (INTEGERP (args[n])
4242 || (FLOATP (args[n]) && conversion != 'c')))
4243 error ("Format specifier doesn't match argument type");
4244 else
4246 enum
4248 /* Lower bound on the number of bits per
4249 base-FLT_RADIX digit. */
4250 DIG_BITS_LBOUND = FLT_RADIX < 16 ? 1 : 4,
4252 /* 1 if integers should be formatted as long doubles,
4253 because they may be so large that there is a rounding
4254 error when converting them to double, and long doubles
4255 are wider than doubles. */
4256 INT_AS_LDBL = (DIG_BITS_LBOUND * DBL_MANT_DIG < FIXNUM_BITS - 1
4257 && DBL_MANT_DIG < LDBL_MANT_DIG),
4259 /* Maximum precision for a %f conversion such that the
4260 trailing output digit might be nonzero. Any precision
4261 larger than this will not yield useful information. */
4262 USEFUL_PRECISION_MAX =
4263 ((1 - LDBL_MIN_EXP)
4264 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4265 : FLT_RADIX == 16 ? 4
4266 : -1)),
4268 /* Maximum number of bytes generated by any format, if
4269 precision is no more than USEFUL_PRECISION_MAX.
4270 On all practical hosts, %f is the worst case. */
4271 SPRINTF_BUFSIZE =
4272 sizeof "-." + (LDBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4274 /* Length of pM (that is, of pMd without the
4275 trailing "d"). */
4276 pMlen = sizeof pMd - 2
4278 verify (USEFUL_PRECISION_MAX > 0);
4280 /* Avoid undefined behavior in underlying sprintf. */
4281 if (conversion == 'd' || conversion == 'i')
4282 sharp_flag = false;
4284 /* Create the copy of the conversion specification, with
4285 any width and precision removed, with ".*" inserted,
4286 with "L" possibly inserted for floating-point formats,
4287 and with pM inserted for integer formats.
4288 At most two flags F can be specified at once. */
4289 char convspec[sizeof "%FF.*d" + max (INT_AS_LDBL, pMlen)];
4291 char *f = convspec;
4292 *f++ = '%';
4293 /* MINUS_FLAG and ZERO_FLAG are dealt with later. */
4294 *f = '+'; f += plus_flag;
4295 *f = ' '; f += space_flag;
4296 *f = '#'; f += sharp_flag;
4297 *f++ = '.';
4298 *f++ = '*';
4299 if (float_conversion)
4301 if (INT_AS_LDBL)
4303 *f = 'L';
4304 f += INTEGERP (args[n]);
4307 else if (conversion != 'c')
4309 memcpy (f, pMd, pMlen);
4310 f += pMlen;
4311 zero_flag &= ! precision_given;
4313 *f++ = conversion;
4314 *f = '\0';
4317 int prec = -1;
4318 if (precision_given)
4319 prec = min (precision, USEFUL_PRECISION_MAX);
4321 /* Use sprintf to format this number into sprintf_buf. Omit
4322 padding and excess precision, though, because sprintf limits
4323 output length to INT_MAX.
4325 There are four types of conversion: double, unsigned
4326 char (passed as int), wide signed int, and wide
4327 unsigned int. Treat them separately because the
4328 sprintf ABI is sensitive to which type is passed. Be
4329 careful about integer overflow, NaNs, infinities, and
4330 conversions; for example, the min and max macros are
4331 not suitable here. */
4332 char sprintf_buf[SPRINTF_BUFSIZE];
4333 ptrdiff_t sprintf_bytes;
4334 if (float_conversion)
4336 if (INT_AS_LDBL && INTEGERP (args[n]))
4338 /* Although long double may have a rounding error if
4339 DIG_BITS_LBOUND * LDBL_MANT_DIG < FIXNUM_BITS - 1,
4340 it is more accurate than plain 'double'. */
4341 long double x = XINT (args[n]);
4342 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4344 else
4345 sprintf_bytes = sprintf (sprintf_buf, convspec, prec,
4346 XFLOATINT (args[n]));
4348 else if (conversion == 'c')
4350 /* Don't use sprintf here, as it might mishandle prec. */
4351 sprintf_buf[0] = XINT (args[n]);
4352 sprintf_bytes = prec != 0;
4354 else if (conversion == 'd' || conversion == 'i')
4356 /* For float, maybe we should use "%1.0f"
4357 instead so it also works for values outside
4358 the integer range. */
4359 printmax_t x;
4360 if (INTEGERP (args[n]))
4361 x = XINT (args[n]);
4362 else
4364 double d = XFLOAT_DATA (args[n]);
4365 if (d < 0)
4367 x = TYPE_MINIMUM (printmax_t);
4368 if (x < d)
4369 x = d;
4371 else
4373 x = TYPE_MAXIMUM (printmax_t);
4374 if (d < x)
4375 x = d;
4378 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4380 else
4382 /* Don't sign-extend for octal or hex printing. */
4383 uprintmax_t x;
4384 if (INTEGERP (args[n]))
4385 x = XUINT (args[n]);
4386 else
4388 double d = XFLOAT_DATA (args[n]);
4389 if (d < 0)
4390 x = 0;
4391 else
4393 x = TYPE_MAXIMUM (uprintmax_t);
4394 if (d < x)
4395 x = d;
4398 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4401 /* Now the length of the formatted item is known, except it omits
4402 padding and excess precision. Deal with excess precision
4403 first. This happens only when the format specifies
4404 ridiculously large precision. */
4405 uintmax_t excess_precision = precision - prec;
4406 uintmax_t leading_zeros = 0, trailing_zeros = 0;
4407 if (excess_precision)
4409 if (float_conversion)
4411 if ((conversion == 'g' && ! sharp_flag)
4412 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4413 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4414 excess_precision = 0;
4415 else
4417 if (conversion == 'g')
4419 char *dot = strchr (sprintf_buf, '.');
4420 if (!dot)
4421 excess_precision = 0;
4424 trailing_zeros = excess_precision;
4426 else
4427 leading_zeros = excess_precision;
4430 /* Compute the total bytes needed for this item, including
4431 excess precision and padding. */
4432 uintmax_t numwidth = sprintf_bytes + excess_precision;
4433 ptrdiff_t padding
4434 = numwidth < field_width ? field_width - numwidth : 0;
4435 if (max_bufsize - sprintf_bytes <= excess_precision
4436 || max_bufsize - padding <= numwidth)
4437 string_overflow ();
4438 convbytes = numwidth + padding;
4440 if (convbytes <= buf + bufsize - p)
4442 /* Copy the formatted item from sprintf_buf into buf,
4443 inserting padding and excess-precision zeros. */
4445 char *src = sprintf_buf;
4446 char src0 = src[0];
4447 int exponent_bytes = 0;
4448 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4449 if (zero_flag
4450 && ((src[signedp] >= '0' && src[signedp] <= '9')
4451 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4452 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4454 leading_zeros += padding;
4455 padding = 0;
4458 if (excess_precision
4459 && (conversion == 'e' || conversion == 'g'))
4461 char *e = strchr (src, 'e');
4462 if (e)
4463 exponent_bytes = src + sprintf_bytes - e;
4466 info[n].start = nchars;
4467 if (! minus_flag)
4469 memset (p, ' ', padding);
4470 p += padding;
4471 nchars += padding;
4474 *p = src0;
4475 src += signedp;
4476 p += signedp;
4477 memset (p, '0', leading_zeros);
4478 p += leading_zeros;
4479 int significand_bytes
4480 = sprintf_bytes - signedp - exponent_bytes;
4481 memcpy (p, src, significand_bytes);
4482 p += significand_bytes;
4483 src += significand_bytes;
4484 memset (p, '0', trailing_zeros);
4485 p += trailing_zeros;
4486 memcpy (p, src, exponent_bytes);
4487 p += exponent_bytes;
4489 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4491 if (minus_flag)
4493 memset (p, ' ', padding);
4494 p += padding;
4495 nchars += padding;
4497 info[n].end = nchars;
4499 continue;
4503 else
4505 unsigned char str[MAX_MULTIBYTE_LENGTH];
4507 if ((format_char == '`' || format_char == '\'')
4508 && quoting_style == CURVE_QUOTING_STYLE)
4510 if (! multibyte)
4512 multibyte = true;
4513 goto retry;
4515 convsrc = format_char == '`' ? uLSQM : uRSQM;
4516 convbytes = 3;
4518 else if (format_char == '`' && quoting_style == STRAIGHT_QUOTING_STYLE)
4519 convsrc = "'";
4520 else
4522 /* Copy a single character from format to buf. */
4523 if (multibyte_format)
4525 /* Copy a whole multibyte character. */
4526 if (p > buf
4527 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4528 && !CHAR_HEAD_P (format_char))
4529 maybe_combine_byte = true;
4531 while (! CHAR_HEAD_P (*format))
4532 format++;
4534 convbytes = format - format0;
4535 memset (&discarded[format0 + 1 - format_start], 2,
4536 convbytes - 1);
4538 else if (multibyte && !ASCII_CHAR_P (format_char))
4540 int c = BYTE8_TO_CHAR (format_char);
4541 convbytes = CHAR_STRING (c, str);
4542 convsrc = (char *) str;
4546 copy_char:
4547 if (convbytes <= buf + bufsize - p)
4549 memcpy (p, convsrc, convbytes);
4550 p += convbytes;
4551 nchars++;
4552 continue;
4556 /* There wasn't enough room to store this conversion or single
4557 character. CONVBYTES says how much room is needed. Allocate
4558 enough room (and then some) and do it again. */
4560 ptrdiff_t used = p - buf;
4561 if (max_bufsize - used < convbytes)
4562 string_overflow ();
4563 bufsize = used + convbytes;
4564 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4566 if (buf == initial_buffer)
4568 buf = xmalloc (bufsize);
4569 sa_must_free = true;
4570 buf_save_value_index = SPECPDL_INDEX ();
4571 record_unwind_protect_ptr (xfree, buf);
4572 memcpy (buf, initial_buffer, used);
4574 else
4576 buf = xrealloc (buf, bufsize);
4577 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4580 p = buf + used;
4581 format = format0;
4582 n = n0;
4585 if (bufsize < p - buf)
4586 emacs_abort ();
4588 if (maybe_combine_byte)
4589 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4590 Lisp_Object val = make_specified_string (buf, nchars, p - buf, multibyte);
4592 /* If the format string has text properties, or any of the string
4593 arguments has text properties, set up text properties of the
4594 result string. */
4596 if (string_intervals (args[0]) || arg_intervals)
4598 /* Add text properties from the format string. */
4599 Lisp_Object len = make_number (SCHARS (args[0]));
4600 Lisp_Object props = text_property_list (args[0], make_number (0),
4601 len, Qnil);
4602 if (CONSP (props))
4604 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4605 ptrdiff_t argn = 1;
4607 /* Adjust the bounds of each text property
4608 to the proper start and end in the output string. */
4610 /* Put the positions in PROPS in increasing order, so that
4611 we can do (effectively) one scan through the position
4612 space of the format string. */
4613 props = Fnreverse (props);
4615 /* BYTEPOS is the byte position in the format string,
4616 POSITION is the untranslated char position in it,
4617 TRANSLATED is the translated char position in BUF,
4618 and ARGN is the number of the next arg we will come to. */
4619 for (Lisp_Object list = props; CONSP (list); list = XCDR (list))
4621 Lisp_Object item = XCAR (list);
4623 /* First adjust the property start position. */
4624 ptrdiff_t pos = XINT (XCAR (item));
4626 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4627 up to this position. */
4628 for (; position < pos; bytepos++)
4630 if (! discarded[bytepos])
4631 position++, translated++;
4632 else if (discarded[bytepos] == 1)
4634 position++;
4635 if (translated == info[argn].start)
4637 translated += info[argn].end - info[argn].start;
4638 argn++;
4643 XSETCAR (item, make_number (translated));
4645 /* Likewise adjust the property end position. */
4646 pos = XINT (XCAR (XCDR (item)));
4648 for (; position < pos; bytepos++)
4650 if (! discarded[bytepos])
4651 position++, translated++;
4652 else if (discarded[bytepos] == 1)
4654 position++;
4655 if (translated == info[argn].start)
4657 translated += info[argn].end - info[argn].start;
4658 argn++;
4663 XSETCAR (XCDR (item), make_number (translated));
4666 add_text_properties_from_list (val, props, make_number (0));
4669 /* Add text properties from arguments. */
4670 if (arg_intervals)
4671 for (ptrdiff_t i = 1; i < nargs; i++)
4672 if (info[i].intervals)
4674 len = make_number (SCHARS (args[i]));
4675 Lisp_Object new_len = make_number (info[i].end - info[i].start);
4676 props = text_property_list (args[i], make_number (0), len, Qnil);
4677 props = extend_property_ranges (props, len, new_len);
4678 /* If successive arguments have properties, be sure that
4679 the value of `composition' property be the copy. */
4680 if (1 < i && info[i - 1].end)
4681 make_composition_value_copy (props);
4682 add_text_properties_from_list (val, props,
4683 make_number (info[i].start));
4687 /* If we allocated BUF or INFO with malloc, free it too. */
4688 SAFE_FREE ();
4690 return val;
4693 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4694 doc: /* Return t if two characters match, optionally ignoring case.
4695 Both arguments must be characters (i.e. integers).
4696 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4697 (register Lisp_Object c1, Lisp_Object c2)
4699 int i1, i2;
4700 /* Check they're chars, not just integers, otherwise we could get array
4701 bounds violations in downcase. */
4702 CHECK_CHARACTER (c1);
4703 CHECK_CHARACTER (c2);
4705 if (XINT (c1) == XINT (c2))
4706 return Qt;
4707 if (NILP (BVAR (current_buffer, case_fold_search)))
4708 return Qnil;
4710 i1 = XFASTINT (c1);
4711 i2 = XFASTINT (c2);
4713 /* FIXME: It is possible to compare multibyte characters even when
4714 the current buffer is unibyte. Unfortunately this is ambiguous
4715 for characters between 128 and 255, as they could be either
4716 eight-bit raw bytes or Latin-1 characters. Assume the former for
4717 now. See Bug#17011, and also see casefiddle.c's casify_object,
4718 which has a similar problem. */
4719 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4721 if (SINGLE_BYTE_CHAR_P (i1))
4722 i1 = UNIBYTE_TO_CHAR (i1);
4723 if (SINGLE_BYTE_CHAR_P (i2))
4724 i2 = UNIBYTE_TO_CHAR (i2);
4727 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4730 /* Transpose the markers in two regions of the current buffer, and
4731 adjust the ones between them if necessary (i.e.: if the regions
4732 differ in size).
4734 START1, END1 are the character positions of the first region.
4735 START1_BYTE, END1_BYTE are the byte positions.
4736 START2, END2 are the character positions of the second region.
4737 START2_BYTE, END2_BYTE are the byte positions.
4739 Traverses the entire marker list of the buffer to do so, adding an
4740 appropriate amount to some, subtracting from some, and leaving the
4741 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4743 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4745 static void
4746 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4747 ptrdiff_t start2, ptrdiff_t end2,
4748 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4749 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4751 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4752 register struct Lisp_Marker *marker;
4754 /* Update point as if it were a marker. */
4755 if (PT < start1)
4757 else if (PT < end1)
4758 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4759 PT_BYTE + (end2_byte - end1_byte));
4760 else if (PT < start2)
4761 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4762 (PT_BYTE + (end2_byte - start2_byte)
4763 - (end1_byte - start1_byte)));
4764 else if (PT < end2)
4765 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4766 PT_BYTE - (start2_byte - start1_byte));
4768 /* We used to adjust the endpoints here to account for the gap, but that
4769 isn't good enough. Even if we assume the caller has tried to move the
4770 gap out of our way, it might still be at start1 exactly, for example;
4771 and that places it `inside' the interval, for our purposes. The amount
4772 of adjustment is nontrivial if there's a `denormalized' marker whose
4773 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4774 the dirty work to Fmarker_position, below. */
4776 /* The difference between the region's lengths */
4777 diff = (end2 - start2) - (end1 - start1);
4778 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4780 /* For shifting each marker in a region by the length of the other
4781 region plus the distance between the regions. */
4782 amt1 = (end2 - start2) + (start2 - end1);
4783 amt2 = (end1 - start1) + (start2 - end1);
4784 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4785 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4787 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4789 mpos = marker->bytepos;
4790 if (mpos >= start1_byte && mpos < end2_byte)
4792 if (mpos < end1_byte)
4793 mpos += amt1_byte;
4794 else if (mpos < start2_byte)
4795 mpos += diff_byte;
4796 else
4797 mpos -= amt2_byte;
4798 marker->bytepos = mpos;
4800 mpos = marker->charpos;
4801 if (mpos >= start1 && mpos < end2)
4803 if (mpos < end1)
4804 mpos += amt1;
4805 else if (mpos < start2)
4806 mpos += diff;
4807 else
4808 mpos -= amt2;
4810 marker->charpos = mpos;
4814 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4815 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4816 The regions should not be overlapping, because the size of the buffer is
4817 never changed in a transposition.
4819 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4820 any markers that happen to be located in the regions.
4822 Transposing beyond buffer boundaries is an error. */)
4823 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4825 register ptrdiff_t start1, end1, start2, end2;
4826 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4827 ptrdiff_t gap, len1, len_mid, len2;
4828 unsigned char *start1_addr, *start2_addr, *temp;
4830 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4831 Lisp_Object buf;
4833 XSETBUFFER (buf, current_buffer);
4834 cur_intv = buffer_intervals (current_buffer);
4836 validate_region (&startr1, &endr1);
4837 validate_region (&startr2, &endr2);
4839 start1 = XFASTINT (startr1);
4840 end1 = XFASTINT (endr1);
4841 start2 = XFASTINT (startr2);
4842 end2 = XFASTINT (endr2);
4843 gap = GPT;
4845 /* Swap the regions if they're reversed. */
4846 if (start2 < end1)
4848 register ptrdiff_t glumph = start1;
4849 start1 = start2;
4850 start2 = glumph;
4851 glumph = end1;
4852 end1 = end2;
4853 end2 = glumph;
4856 len1 = end1 - start1;
4857 len2 = end2 - start2;
4859 if (start2 < end1)
4860 error ("Transposed regions overlap");
4861 /* Nothing to change for adjacent regions with one being empty */
4862 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4863 return Qnil;
4865 /* The possibilities are:
4866 1. Adjacent (contiguous) regions, or separate but equal regions
4867 (no, really equal, in this case!), or
4868 2. Separate regions of unequal size.
4870 The worst case is usually No. 2. It means that (aside from
4871 potential need for getting the gap out of the way), there also
4872 needs to be a shifting of the text between the two regions. So
4873 if they are spread far apart, we are that much slower... sigh. */
4875 /* It must be pointed out that the really studly thing to do would
4876 be not to move the gap at all, but to leave it in place and work
4877 around it if necessary. This would be extremely efficient,
4878 especially considering that people are likely to do
4879 transpositions near where they are working interactively, which
4880 is exactly where the gap would be found. However, such code
4881 would be much harder to write and to read. So, if you are
4882 reading this comment and are feeling squirrely, by all means have
4883 a go! I just didn't feel like doing it, so I will simply move
4884 the gap the minimum distance to get it out of the way, and then
4885 deal with an unbroken array. */
4887 start1_byte = CHAR_TO_BYTE (start1);
4888 end2_byte = CHAR_TO_BYTE (end2);
4890 /* Make sure the gap won't interfere, by moving it out of the text
4891 we will operate on. */
4892 if (start1 < gap && gap < end2)
4894 if (gap - start1 < end2 - gap)
4895 move_gap_both (start1, start1_byte);
4896 else
4897 move_gap_both (end2, end2_byte);
4900 start2_byte = CHAR_TO_BYTE (start2);
4901 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4902 len2_byte = end2_byte - start2_byte;
4904 #ifdef BYTE_COMBINING_DEBUG
4905 if (end1 == start2)
4907 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4908 len2_byte, start1, start1_byte)
4909 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4910 len1_byte, end2, start2_byte + len2_byte)
4911 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4912 len1_byte, end2, start2_byte + len2_byte))
4913 emacs_abort ();
4915 else
4917 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4918 len2_byte, start1, start1_byte)
4919 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4920 len1_byte, start2, start2_byte)
4921 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4922 len2_byte, end1, start1_byte + len1_byte)
4923 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4924 len1_byte, end2, start2_byte + len2_byte))
4925 emacs_abort ();
4927 #endif
4929 /* Hmmm... how about checking to see if the gap is large
4930 enough to use as the temporary storage? That would avoid an
4931 allocation... interesting. Later, don't fool with it now. */
4933 /* Working without memmove, for portability (sigh), so must be
4934 careful of overlapping subsections of the array... */
4936 if (end1 == start2) /* adjacent regions */
4938 modify_text (start1, end2);
4939 record_change (start1, len1 + len2);
4941 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4942 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4943 /* Don't use Fset_text_properties: that can cause GC, which can
4944 clobber objects stored in the tmp_intervals. */
4945 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4946 if (tmp_interval3)
4947 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4949 USE_SAFE_ALLOCA;
4951 /* First region smaller than second. */
4952 if (len1_byte < len2_byte)
4954 temp = SAFE_ALLOCA (len2_byte);
4956 /* Don't precompute these addresses. We have to compute them
4957 at the last minute, because the relocating allocator might
4958 have moved the buffer around during the xmalloc. */
4959 start1_addr = BYTE_POS_ADDR (start1_byte);
4960 start2_addr = BYTE_POS_ADDR (start2_byte);
4962 memcpy (temp, start2_addr, len2_byte);
4963 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4964 memcpy (start1_addr, temp, len2_byte);
4966 else
4967 /* First region not smaller than second. */
4969 temp = SAFE_ALLOCA (len1_byte);
4970 start1_addr = BYTE_POS_ADDR (start1_byte);
4971 start2_addr = BYTE_POS_ADDR (start2_byte);
4972 memcpy (temp, start1_addr, len1_byte);
4973 memcpy (start1_addr, start2_addr, len2_byte);
4974 memcpy (start1_addr + len2_byte, temp, len1_byte);
4977 SAFE_FREE ();
4978 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4979 len1, current_buffer, 0);
4980 graft_intervals_into_buffer (tmp_interval2, start1,
4981 len2, current_buffer, 0);
4982 update_compositions (start1, start1 + len2, CHECK_BORDER);
4983 update_compositions (start1 + len2, end2, CHECK_TAIL);
4985 /* Non-adjacent regions, because end1 != start2, bleagh... */
4986 else
4988 len_mid = start2_byte - (start1_byte + len1_byte);
4990 if (len1_byte == len2_byte)
4991 /* Regions are same size, though, how nice. */
4993 USE_SAFE_ALLOCA;
4995 modify_text (start1, end1);
4996 modify_text (start2, end2);
4997 record_change (start1, len1);
4998 record_change (start2, len2);
4999 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5000 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5002 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
5003 if (tmp_interval3)
5004 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
5006 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
5007 if (tmp_interval3)
5008 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
5010 temp = SAFE_ALLOCA (len1_byte);
5011 start1_addr = BYTE_POS_ADDR (start1_byte);
5012 start2_addr = BYTE_POS_ADDR (start2_byte);
5013 memcpy (temp, start1_addr, len1_byte);
5014 memcpy (start1_addr, start2_addr, len2_byte);
5015 memcpy (start2_addr, temp, len1_byte);
5016 SAFE_FREE ();
5018 graft_intervals_into_buffer (tmp_interval1, start2,
5019 len1, current_buffer, 0);
5020 graft_intervals_into_buffer (tmp_interval2, start1,
5021 len2, current_buffer, 0);
5024 else if (len1_byte < len2_byte) /* Second region larger than first */
5025 /* Non-adjacent & unequal size, area between must also be shifted. */
5027 USE_SAFE_ALLOCA;
5029 modify_text (start1, end2);
5030 record_change (start1, (end2 - start1));
5031 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5032 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5033 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5035 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5036 if (tmp_interval3)
5037 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5039 /* holds region 2 */
5040 temp = SAFE_ALLOCA (len2_byte);
5041 start1_addr = BYTE_POS_ADDR (start1_byte);
5042 start2_addr = BYTE_POS_ADDR (start2_byte);
5043 memcpy (temp, start2_addr, len2_byte);
5044 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
5045 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5046 memcpy (start1_addr, temp, len2_byte);
5047 SAFE_FREE ();
5049 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5050 len1, current_buffer, 0);
5051 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5052 len_mid, current_buffer, 0);
5053 graft_intervals_into_buffer (tmp_interval2, start1,
5054 len2, current_buffer, 0);
5056 else
5057 /* Second region smaller than first. */
5059 USE_SAFE_ALLOCA;
5061 record_change (start1, (end2 - start1));
5062 modify_text (start1, end2);
5064 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
5065 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5066 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5068 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5069 if (tmp_interval3)
5070 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5072 /* holds region 1 */
5073 temp = SAFE_ALLOCA (len1_byte);
5074 start1_addr = BYTE_POS_ADDR (start1_byte);
5075 start2_addr = BYTE_POS_ADDR (start2_byte);
5076 memcpy (temp, start1_addr, len1_byte);
5077 memcpy (start1_addr, start2_addr, len2_byte);
5078 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5079 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
5080 SAFE_FREE ();
5082 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5083 len1, current_buffer, 0);
5084 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5085 len_mid, current_buffer, 0);
5086 graft_intervals_into_buffer (tmp_interval2, start1,
5087 len2, current_buffer, 0);
5090 update_compositions (start1, start1 + len2, CHECK_BORDER);
5091 update_compositions (end2 - len1, end2, CHECK_BORDER);
5094 /* When doing multiple transpositions, it might be nice
5095 to optimize this. Perhaps the markers in any one buffer
5096 should be organized in some sorted data tree. */
5097 if (NILP (leave_markers))
5099 transpose_markers (start1, end1, start2, end2,
5100 start1_byte, start1_byte + len1_byte,
5101 start2_byte, start2_byte + len2_byte);
5102 fix_start_end_in_overlays (start1, end2);
5104 else
5106 /* The character positions of the markers remain intact, but we
5107 still need to update their byte positions, because the
5108 transposed regions might include multibyte sequences which
5109 make some original byte positions of the markers invalid. */
5110 adjust_markers_bytepos (start1, start1_byte, end2, end2_byte, 0);
5113 signal_after_change (start1, end2 - start1, end2 - start1);
5114 return Qnil;
5118 void
5119 syms_of_editfns (void)
5121 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
5122 DEFSYM (Qwall, "wall");
5124 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
5125 doc: /* Non-nil means text motion commands don't notice fields. */);
5126 Vinhibit_field_text_motion = Qnil;
5128 DEFVAR_LISP ("buffer-access-fontify-functions",
5129 Vbuffer_access_fontify_functions,
5130 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
5131 Each function is called with two arguments which specify the range
5132 of the buffer being accessed. */);
5133 Vbuffer_access_fontify_functions = Qnil;
5136 Lisp_Object obuf;
5137 obuf = Fcurrent_buffer ();
5138 /* Do this here, because init_buffer_once is too early--it won't work. */
5139 Fset_buffer (Vprin1_to_string_buffer);
5140 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5141 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions), Qnil);
5142 Fset_buffer (obuf);
5145 DEFVAR_LISP ("buffer-access-fontified-property",
5146 Vbuffer_access_fontified_property,
5147 doc: /* Property which (if non-nil) indicates text has been fontified.
5148 `buffer-substring' need not call the `buffer-access-fontify-functions'
5149 functions if all the text being accessed has this property. */);
5150 Vbuffer_access_fontified_property = Qnil;
5152 DEFVAR_LISP ("system-name", Vsystem_name,
5153 doc: /* The host name of the machine Emacs is running on. */);
5154 Vsystem_name = cached_system_name = Qnil;
5156 DEFVAR_LISP ("user-full-name", Vuser_full_name,
5157 doc: /* The full name of the user logged in. */);
5159 DEFVAR_LISP ("user-login-name", Vuser_login_name,
5160 doc: /* The user's name, taken from environment variables if possible. */);
5161 Vuser_login_name = Qnil;
5163 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
5164 doc: /* The user's name, based upon the real uid only. */);
5166 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
5167 doc: /* The release of the operating system Emacs is running on. */);
5169 defsubr (&Spropertize);
5170 defsubr (&Schar_equal);
5171 defsubr (&Sgoto_char);
5172 defsubr (&Sstring_to_char);
5173 defsubr (&Schar_to_string);
5174 defsubr (&Sbyte_to_string);
5175 defsubr (&Sbuffer_substring);
5176 defsubr (&Sbuffer_substring_no_properties);
5177 defsubr (&Sbuffer_string);
5178 defsubr (&Sget_pos_property);
5180 defsubr (&Spoint_marker);
5181 defsubr (&Smark_marker);
5182 defsubr (&Spoint);
5183 defsubr (&Sregion_beginning);
5184 defsubr (&Sregion_end);
5186 /* Symbol for the text property used to mark fields. */
5187 DEFSYM (Qfield, "field");
5189 /* A special value for Qfield properties. */
5190 DEFSYM (Qboundary, "boundary");
5192 defsubr (&Sfield_beginning);
5193 defsubr (&Sfield_end);
5194 defsubr (&Sfield_string);
5195 defsubr (&Sfield_string_no_properties);
5196 defsubr (&Sdelete_field);
5197 defsubr (&Sconstrain_to_field);
5199 defsubr (&Sline_beginning_position);
5200 defsubr (&Sline_end_position);
5202 defsubr (&Ssave_excursion);
5203 defsubr (&Ssave_current_buffer);
5205 defsubr (&Sbuffer_size);
5206 defsubr (&Spoint_max);
5207 defsubr (&Spoint_min);
5208 defsubr (&Spoint_min_marker);
5209 defsubr (&Spoint_max_marker);
5210 defsubr (&Sgap_position);
5211 defsubr (&Sgap_size);
5212 defsubr (&Sposition_bytes);
5213 defsubr (&Sbyte_to_position);
5215 defsubr (&Sbobp);
5216 defsubr (&Seobp);
5217 defsubr (&Sbolp);
5218 defsubr (&Seolp);
5219 defsubr (&Sfollowing_char);
5220 defsubr (&Sprevious_char);
5221 defsubr (&Schar_after);
5222 defsubr (&Schar_before);
5223 defsubr (&Sinsert);
5224 defsubr (&Sinsert_before_markers);
5225 defsubr (&Sinsert_and_inherit);
5226 defsubr (&Sinsert_and_inherit_before_markers);
5227 defsubr (&Sinsert_char);
5228 defsubr (&Sinsert_byte);
5230 defsubr (&Suser_login_name);
5231 defsubr (&Suser_real_login_name);
5232 defsubr (&Suser_uid);
5233 defsubr (&Suser_real_uid);
5234 defsubr (&Sgroup_gid);
5235 defsubr (&Sgroup_real_gid);
5236 defsubr (&Suser_full_name);
5237 defsubr (&Semacs_pid);
5238 defsubr (&Scurrent_time);
5239 defsubr (&Stime_add);
5240 defsubr (&Stime_subtract);
5241 defsubr (&Stime_less_p);
5242 defsubr (&Sget_internal_run_time);
5243 defsubr (&Sformat_time_string);
5244 defsubr (&Sfloat_time);
5245 defsubr (&Sdecode_time);
5246 defsubr (&Sencode_time);
5247 defsubr (&Scurrent_time_string);
5248 defsubr (&Scurrent_time_zone);
5249 defsubr (&Sset_time_zone_rule);
5250 defsubr (&Ssystem_name);
5251 defsubr (&Smessage);
5252 defsubr (&Smessage_box);
5253 defsubr (&Smessage_or_box);
5254 defsubr (&Scurrent_message);
5255 defsubr (&Sformat);
5256 defsubr (&Sformat_message);
5258 defsubr (&Sinsert_buffer_substring);
5259 defsubr (&Scompare_buffer_substrings);
5260 defsubr (&Ssubst_char_in_region);
5261 defsubr (&Stranslate_region_internal);
5262 defsubr (&Sdelete_region);
5263 defsubr (&Sdelete_and_extract_region);
5264 defsubr (&Swiden);
5265 defsubr (&Snarrow_to_region);
5266 defsubr (&Ssave_restriction);
5267 defsubr (&Stranspose_regions);