Merge from origin/emacs-25
[emacs.git] / src / editfns.c
blob4f6108102dbf708699ce4603e7439615b745a0d8
1 /* Lisp functions pertaining to editing. -*- coding: utf-8 -*-
3 Copyright (C) 1985-1987, 1989, 1993-2016 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, to wall clock time,
85 and to UTC, respectively. */
86 static timezone_t local_tz;
87 static timezone_t wall_clock_tz;
88 static timezone_t const utc_tz = 0;
90 /* A valid but unlikely setting for the TZ environment variable.
91 It is OK (though a bit slower) if the user chooses this value. */
92 static char dump_tz_string[] = "TZ=UtC0";
94 /* The cached value of Vsystem_name. This is used only to compare it
95 to Vsystem_name, so it need not be visible to the GC. */
96 static Lisp_Object cached_system_name;
98 static void
99 init_and_cache_system_name (void)
101 init_system_name ();
102 cached_system_name = Vsystem_name;
105 static struct tm *
106 emacs_localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
108 tm = localtime_rz (tz, t, tm);
109 if (!tm && errno == ENOMEM)
110 memory_full (SIZE_MAX);
111 return tm;
114 static time_t
115 emacs_mktime_z (timezone_t tz, struct tm *tm)
117 errno = 0;
118 time_t t = mktime_z (tz, tm);
119 if (t == (time_t) -1 && errno == ENOMEM)
120 memory_full (SIZE_MAX);
121 return t;
124 /* Allocate a timezone, signaling on failure. */
125 static timezone_t
126 xtzalloc (char const *name)
128 timezone_t tz = tzalloc (name);
129 if (!tz)
130 memory_full (SIZE_MAX);
131 return tz;
134 /* Free a timezone, except do not free the time zone for local time.
135 Freeing utc_tz is also a no-op. */
136 static void
137 xtzfree (timezone_t tz)
139 if (tz != local_tz)
140 tzfree (tz);
143 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
144 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
145 If SETTZ, set Emacs local time to the time zone rule; otherwise,
146 the caller should eventually pass the returned value to xtzfree. */
147 static timezone_t
148 tzlookup (Lisp_Object zone, bool settz)
150 static char const tzbuf_format[] = "<%+.*"pI"d>%s%"pI"d:%02d:%02d";
151 char const *trailing_tzbuf_format = tzbuf_format + sizeof "<%+.*"pI"d" - 1;
152 char tzbuf[sizeof tzbuf_format + 2 * INT_STRLEN_BOUND (EMACS_INT)];
153 char const *zone_string;
154 timezone_t new_tz;
156 if (NILP (zone))
157 return local_tz;
158 else if (EQ (zone, Qt))
160 zone_string = "UTC0";
161 new_tz = utc_tz;
163 else
165 bool plain_integer = INTEGERP (zone);
167 if (EQ (zone, Qwall))
168 zone_string = 0;
169 else if (STRINGP (zone))
170 zone_string = SSDATA (ENCODE_SYSTEM (zone));
171 else if (plain_integer || (CONSP (zone) && INTEGERP (XCAR (zone))
172 && CONSP (XCDR (zone))))
174 Lisp_Object abbr;
175 if (!plain_integer)
177 abbr = XCAR (XCDR (zone));
178 zone = XCAR (zone);
181 EMACS_INT abszone = eabs (XINT (zone)), hour = abszone / (60 * 60);
182 int hour_remainder = abszone % (60 * 60);
183 int min = hour_remainder / 60, sec = hour_remainder % 60;
185 if (plain_integer)
187 int prec = 2;
188 EMACS_INT numzone = hour;
189 if (hour_remainder != 0)
191 prec += 2, numzone = 100 * numzone + min;
192 if (sec != 0)
193 prec += 2, numzone = 100 * numzone + sec;
195 sprintf (tzbuf, tzbuf_format, prec, numzone,
196 &"-"[XINT (zone) < 0], hour, min, sec);
197 zone_string = tzbuf;
199 else
201 AUTO_STRING (leading, "<");
202 AUTO_STRING_WITH_LEN (trailing, tzbuf,
203 sprintf (tzbuf, trailing_tzbuf_format,
204 &"-"[XINT (zone) < 0],
205 hour, min, sec));
206 zone_string = SSDATA (concat3 (leading, ENCODE_SYSTEM (abbr),
207 trailing));
210 else
211 xsignal2 (Qerror, build_string ("Invalid time zone specification"),
212 zone);
213 new_tz = xtzalloc (zone_string);
216 if (settz)
218 block_input ();
219 emacs_setenv_TZ (zone_string);
220 tzset ();
221 timezone_t old_tz = local_tz;
222 local_tz = new_tz;
223 tzfree (old_tz);
224 unblock_input ();
227 return new_tz;
230 void
231 init_editfns (bool dumping)
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 # ifdef HAVE_TZSET
247 xputenv (dump_tz_string);
248 tzset ();
249 # endif
250 return;
252 #endif
254 char *tz = getenv ("TZ");
256 #if !defined CANNOT_DUMP && defined HAVE_TZSET
257 /* If the execution TZ happens to be the same as the dump TZ,
258 change it to some other value and then change it back,
259 to force the underlying implementation to reload the TZ info.
260 This is needed on implementations that load TZ info from files,
261 since the TZ file contents may differ between dump and execution. */
262 if (tz && strcmp (tz, &dump_tz_string[tzeqlen]) == 0)
264 ++*tz;
265 tzset ();
266 --*tz;
268 #endif
270 /* Set the time zone rule now, so that the call to putenv is done
271 before multiple threads are active. */
272 wall_clock_tz = xtzalloc (0);
273 tzlookup (tz ? build_string (tz) : Qwall, true);
275 pw = getpwuid (getuid ());
276 #ifdef MSDOS
277 /* We let the real user name default to "root" because that's quite
278 accurate on MS-DOS and because it lets Emacs find the init file.
279 (The DVX libraries override the Djgpp libraries here.) */
280 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
281 #else
282 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
283 #endif
285 /* Get the effective user name, by consulting environment variables,
286 or the effective uid if those are unset. */
287 user_name = getenv ("LOGNAME");
288 if (!user_name)
289 #ifdef WINDOWSNT
290 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
291 #else /* WINDOWSNT */
292 user_name = getenv ("USER");
293 #endif /* WINDOWSNT */
294 if (!user_name)
296 pw = getpwuid (geteuid ());
297 user_name = pw ? pw->pw_name : "unknown";
299 Vuser_login_name = build_string (user_name);
301 /* If the user name claimed in the environment vars differs from
302 the real uid, use the claimed name to find the full name. */
303 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
304 if (! NILP (tem))
305 tem = Vuser_login_name;
306 else
308 uid_t euid = geteuid ();
309 tem = make_fixnum_or_float (euid);
311 Vuser_full_name = Fuser_full_name (tem);
313 p = getenv ("NAME");
314 if (p)
315 Vuser_full_name = build_string (p);
316 else if (NILP (Vuser_full_name))
317 Vuser_full_name = build_string ("unknown");
319 #ifdef HAVE_SYS_UTSNAME_H
321 struct utsname uts;
322 uname (&uts);
323 Voperating_system_release = build_string (uts.release);
325 #else
326 Voperating_system_release = Qnil;
327 #endif
330 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
331 doc: /* Convert arg CHAR to a string containing that character.
332 usage: (char-to-string CHAR) */)
333 (Lisp_Object character)
335 int c, len;
336 unsigned char str[MAX_MULTIBYTE_LENGTH];
338 CHECK_CHARACTER (character);
339 c = XFASTINT (character);
341 len = CHAR_STRING (c, str);
342 return make_string_from_bytes ((char *) str, 1, len);
345 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
346 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
347 (Lisp_Object byte)
349 unsigned char b;
350 CHECK_NUMBER (byte);
351 if (XINT (byte) < 0 || XINT (byte) > 255)
352 error ("Invalid byte");
353 b = XINT (byte);
354 return make_string_from_bytes ((char *) &b, 1, 1);
357 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
358 doc: /* Return the first character in STRING. */)
359 (register Lisp_Object string)
361 register Lisp_Object val;
362 CHECK_STRING (string);
363 if (SCHARS (string))
365 if (STRING_MULTIBYTE (string))
366 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
367 else
368 XSETFASTINT (val, SREF (string, 0));
370 else
371 XSETFASTINT (val, 0);
372 return val;
375 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
376 doc: /* Return value of point, as an integer.
377 Beginning of buffer is position (point-min). */)
378 (void)
380 Lisp_Object temp;
381 XSETFASTINT (temp, PT);
382 return temp;
385 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
386 doc: /* Return value of point, as a marker object. */)
387 (void)
389 return build_marker (current_buffer, PT, PT_BYTE);
392 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
393 doc: /* Set point to POSITION, a number or marker.
394 Beginning of buffer is position (point-min), end is (point-max).
396 The return value is POSITION. */)
397 (register Lisp_Object position)
399 if (MARKERP (position))
400 set_point_from_marker (position);
401 else if (INTEGERP (position))
402 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
403 else
404 wrong_type_argument (Qinteger_or_marker_p, position);
405 return position;
409 /* Return the start or end position of the region.
410 BEGINNINGP means return the start.
411 If there is no region active, signal an error. */
413 static Lisp_Object
414 region_limit (bool beginningp)
416 Lisp_Object m;
418 if (!NILP (Vtransient_mark_mode)
419 && NILP (Vmark_even_if_inactive)
420 && NILP (BVAR (current_buffer, mark_active)))
421 xsignal0 (Qmark_inactive);
423 m = Fmarker_position (BVAR (current_buffer, mark));
424 if (NILP (m))
425 error ("The mark is not set now, so there is no region");
427 /* Clip to the current narrowing (bug#11770). */
428 return make_number ((PT < XFASTINT (m)) == beginningp
429 ? PT
430 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
433 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
434 doc: /* Return the integer value of point or mark, whichever is smaller. */)
435 (void)
437 return region_limit (1);
440 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
441 doc: /* Return the integer value of point or mark, whichever is larger. */)
442 (void)
444 return region_limit (0);
447 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
448 doc: /* Return this buffer's mark, as a marker object.
449 Watch out! Moving this marker changes the mark position.
450 If you set the marker not to point anywhere, the buffer will have no mark. */)
451 (void)
453 return BVAR (current_buffer, mark);
457 /* Find all the overlays in the current buffer that touch position POS.
458 Return the number found, and store them in a vector in VEC
459 of length LEN. */
461 static ptrdiff_t
462 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
464 Lisp_Object overlay, start, end;
465 struct Lisp_Overlay *tail;
466 ptrdiff_t startpos, endpos;
467 ptrdiff_t idx = 0;
469 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
471 XSETMISC (overlay, tail);
473 end = OVERLAY_END (overlay);
474 endpos = OVERLAY_POSITION (end);
475 if (endpos < pos)
476 break;
477 start = OVERLAY_START (overlay);
478 startpos = OVERLAY_POSITION (start);
479 if (startpos <= pos)
481 if (idx < len)
482 vec[idx] = overlay;
483 /* Keep counting overlays even if we can't return them all. */
484 idx++;
488 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
490 XSETMISC (overlay, tail);
492 start = OVERLAY_START (overlay);
493 startpos = OVERLAY_POSITION (start);
494 if (pos < startpos)
495 break;
496 end = OVERLAY_END (overlay);
497 endpos = OVERLAY_POSITION (end);
498 if (pos <= endpos)
500 if (idx < len)
501 vec[idx] = overlay;
502 idx++;
506 return idx;
509 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
510 doc: /* Return the value of POSITION's property PROP, in OBJECT.
511 Almost identical to `get-char-property' except for the following difference:
512 Whereas `get-char-property' returns the property of the char at (i.e. right
513 after) POSITION, this pays attention to properties's stickiness and overlays's
514 advancement settings, in order to find the property of POSITION itself,
515 i.e. the property that a char would inherit if it were inserted
516 at POSITION. */)
517 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
519 CHECK_NUMBER_COERCE_MARKER (position);
521 if (NILP (object))
522 XSETBUFFER (object, current_buffer);
523 else if (WINDOWP (object))
524 object = XWINDOW (object)->contents;
526 if (!BUFFERP (object))
527 /* pos-property only makes sense in buffers right now, since strings
528 have no overlays and no notion of insertion for which stickiness
529 could be obeyed. */
530 return Fget_text_property (position, prop, object);
531 else
533 EMACS_INT posn = XINT (position);
534 ptrdiff_t noverlays;
535 Lisp_Object *overlay_vec, tem;
536 struct buffer *obuf = current_buffer;
537 USE_SAFE_ALLOCA;
539 set_buffer_temp (XBUFFER (object));
541 /* First try with room for 40 overlays. */
542 Lisp_Object overlay_vecbuf[40];
543 noverlays = ARRAYELTS (overlay_vecbuf);
544 overlay_vec = overlay_vecbuf;
545 noverlays = overlays_around (posn, overlay_vec, noverlays);
547 /* If there are more than 40,
548 make enough space for all, and try again. */
549 if (ARRAYELTS (overlay_vecbuf) < noverlays)
551 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
552 noverlays = overlays_around (posn, overlay_vec, noverlays);
554 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
556 set_buffer_temp (obuf);
558 /* Now check the overlays in order of decreasing priority. */
559 while (--noverlays >= 0)
561 Lisp_Object ol = overlay_vec[noverlays];
562 tem = Foverlay_get (ol, prop);
563 if (!NILP (tem))
565 /* Check the overlay is indeed active at point. */
566 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
567 if ((OVERLAY_POSITION (start) == posn
568 && XMARKER (start)->insertion_type == 1)
569 || (OVERLAY_POSITION (finish) == posn
570 && XMARKER (finish)->insertion_type == 0))
571 ; /* The overlay will not cover a char inserted at point. */
572 else
574 SAFE_FREE ();
575 return tem;
579 SAFE_FREE ();
581 { /* Now check the text properties. */
582 int stickiness = text_property_stickiness (prop, position, object);
583 if (stickiness > 0)
584 return Fget_text_property (position, prop, object);
585 else if (stickiness < 0
586 && XINT (position) > BUF_BEGV (XBUFFER (object)))
587 return Fget_text_property (make_number (XINT (position) - 1),
588 prop, object);
589 else
590 return Qnil;
595 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
596 the value of point is used instead. If BEG or END is null,
597 means don't store the beginning or end of the field.
599 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
600 results; they do not effect boundary behavior.
602 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
603 position of a field, then the beginning of the previous field is
604 returned instead of the beginning of POS's field (since the end of a
605 field is actually also the beginning of the next input field, this
606 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
607 non-nil case, if two fields are separated by a field with the special
608 value `boundary', and POS lies within it, then the two separated
609 fields are considered to be adjacent, and POS between them, when
610 finding the beginning and ending of the "merged" field.
612 Either BEG or END may be 0, in which case the corresponding value
613 is not stored. */
615 static void
616 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
617 Lisp_Object beg_limit,
618 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
620 /* Fields right before and after the point. */
621 Lisp_Object before_field, after_field;
622 /* True if POS counts as the start of a field. */
623 bool at_field_start = 0;
624 /* True if POS counts as the end of a field. */
625 bool at_field_end = 0;
627 if (NILP (pos))
628 XSETFASTINT (pos, PT);
629 else
630 CHECK_NUMBER_COERCE_MARKER (pos);
632 after_field
633 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
634 before_field
635 = (XFASTINT (pos) > BEGV
636 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
637 Qfield, Qnil, NULL)
638 /* Using nil here would be a more obvious choice, but it would
639 fail when the buffer starts with a non-sticky field. */
640 : after_field);
642 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
643 and POS is at beginning of a field, which can also be interpreted
644 as the end of the previous field. Note that the case where if
645 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
646 more natural one; then we avoid treating the beginning of a field
647 specially. */
648 if (NILP (merge_at_boundary))
650 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
651 if (!EQ (field, after_field))
652 at_field_end = 1;
653 if (!EQ (field, before_field))
654 at_field_start = 1;
655 if (NILP (field) && at_field_start && at_field_end)
656 /* If an inserted char would have a nil field while the surrounding
657 text is non-nil, we're probably not looking at a
658 zero-length field, but instead at a non-nil field that's
659 not intended for editing (such as comint's prompts). */
660 at_field_end = at_field_start = 0;
663 /* Note about special `boundary' fields:
665 Consider the case where the point (`.') is between the fields `x' and `y':
667 xxxx.yyyy
669 In this situation, if merge_at_boundary is non-nil, consider the
670 `x' and `y' fields as forming one big merged field, and so the end
671 of the field is the end of `y'.
673 However, if `x' and `y' are separated by a special `boundary' field
674 (a field with a `field' char-property of 'boundary), then ignore
675 this special field when merging adjacent fields. Here's the same
676 situation, but with a `boundary' field between the `x' and `y' fields:
678 xxx.BBBByyyy
680 Here, if point is at the end of `x', the beginning of `y', or
681 anywhere in-between (within the `boundary' field), merge all
682 three fields and consider the beginning as being the beginning of
683 the `x' field, and the end as being the end of the `y' field. */
685 if (beg)
687 if (at_field_start)
688 /* POS is at the edge of a field, and we should consider it as
689 the beginning of the following field. */
690 *beg = XFASTINT (pos);
691 else
692 /* Find the previous field boundary. */
694 Lisp_Object p = pos;
695 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
696 /* Skip a `boundary' field. */
697 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
698 beg_limit);
700 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
701 beg_limit);
702 *beg = NILP (p) ? BEGV : XFASTINT (p);
706 if (end)
708 if (at_field_end)
709 /* POS is at the edge of a field, and we should consider it as
710 the end of the previous field. */
711 *end = XFASTINT (pos);
712 else
713 /* Find the next field boundary. */
715 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
716 /* Skip a `boundary' field. */
717 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
718 end_limit);
720 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
721 end_limit);
722 *end = NILP (pos) ? ZV : XFASTINT (pos);
728 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
729 doc: /* Delete the field surrounding POS.
730 A field is a region of text with the same `field' property.
731 If POS is nil, the value of point is used for POS. */)
732 (Lisp_Object pos)
734 ptrdiff_t beg, end;
735 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
736 if (beg != end)
737 del_range (beg, end);
738 return Qnil;
741 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
742 doc: /* Return the contents of the field surrounding POS as a string.
743 A field is a region of text with the same `field' property.
744 If POS is nil, the value of point is used for POS. */)
745 (Lisp_Object pos)
747 ptrdiff_t beg, end;
748 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
749 return make_buffer_string (beg, end, 1);
752 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
753 doc: /* Return the contents of the field around POS, without text properties.
754 A field is a region of text with the same `field' property.
755 If POS is nil, the value of point is used for POS. */)
756 (Lisp_Object pos)
758 ptrdiff_t beg, end;
759 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
760 return make_buffer_string (beg, end, 0);
763 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
764 doc: /* Return the beginning of the field surrounding POS.
765 A field is a region of text with the same `field' property.
766 If POS is nil, the value of point is used for POS.
767 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
768 field, then the beginning of the *previous* field is returned.
769 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
770 is before LIMIT, then LIMIT will be returned instead. */)
771 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
773 ptrdiff_t beg;
774 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
775 return make_number (beg);
778 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
779 doc: /* Return the end of the field surrounding POS.
780 A field is a region of text with the same `field' property.
781 If POS is nil, the value of point is used for POS.
782 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
783 then the end of the *following* field is returned.
784 If LIMIT is non-nil, it is a buffer position; if the end of the field
785 is after LIMIT, then LIMIT will be returned instead. */)
786 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
788 ptrdiff_t end;
789 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
790 return make_number (end);
793 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
794 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
795 A field is a region of text with the same `field' property.
797 If NEW-POS is nil, then use the current point instead, and move point
798 to the resulting constrained position, in addition to returning that
799 position.
801 If OLD-POS is at the boundary of two fields, then the allowable
802 positions for NEW-POS depends on the value of the optional argument
803 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
804 constrained to the field that has the same `field' char-property
805 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
806 is non-nil, NEW-POS is constrained to the union of the two adjacent
807 fields. Additionally, if two fields are separated by another field with
808 the special value `boundary', then any point within this special field is
809 also considered to be `on the boundary'.
811 If the optional argument ONLY-IN-LINE is non-nil and constraining
812 NEW-POS would move it to a different line, NEW-POS is returned
813 unconstrained. This is useful for commands that move by line, like
814 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
815 only in the case where they can still move to the right line.
817 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
818 a non-nil property of that name, then any field boundaries are ignored.
820 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
821 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
822 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
824 /* If non-zero, then the original point, before re-positioning. */
825 ptrdiff_t orig_point = 0;
826 bool fwd;
827 Lisp_Object prev_old, prev_new;
829 if (NILP (new_pos))
830 /* Use the current point, and afterwards, set it. */
832 orig_point = PT;
833 XSETFASTINT (new_pos, PT);
836 CHECK_NUMBER_COERCE_MARKER (new_pos);
837 CHECK_NUMBER_COERCE_MARKER (old_pos);
839 fwd = (XINT (new_pos) > XINT (old_pos));
841 prev_old = make_number (XINT (old_pos) - 1);
842 prev_new = make_number (XINT (new_pos) - 1);
844 if (NILP (Vinhibit_field_text_motion)
845 && !EQ (new_pos, old_pos)
846 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
847 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
848 /* To recognize field boundaries, we must also look at the
849 previous positions; we could use `Fget_pos_property'
850 instead, but in itself that would fail inside non-sticky
851 fields (like comint prompts). */
852 || (XFASTINT (new_pos) > BEGV
853 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
854 || (XFASTINT (old_pos) > BEGV
855 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
856 && (NILP (inhibit_capture_property)
857 /* Field boundaries are again a problem; but now we must
858 decide the case exactly, so we need to call
859 `get_pos_property' as well. */
860 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
861 && (XFASTINT (old_pos) <= BEGV
862 || NILP (Fget_char_property
863 (old_pos, inhibit_capture_property, Qnil))
864 || NILP (Fget_char_property
865 (prev_old, inhibit_capture_property, Qnil))))))
866 /* It is possible that NEW_POS is not within the same field as
867 OLD_POS; try to move NEW_POS so that it is. */
869 ptrdiff_t shortage;
870 Lisp_Object field_bound;
872 if (fwd)
873 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
874 else
875 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
877 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
878 other side of NEW_POS, which would mean that NEW_POS is
879 already acceptable, and it's not necessary to constrain it
880 to FIELD_BOUND. */
881 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
882 /* NEW_POS should be constrained, but only if either
883 ONLY_IN_LINE is nil (in which case any constraint is OK),
884 or NEW_POS and FIELD_BOUND are on the same line (in which
885 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
886 && (NILP (only_in_line)
887 /* This is the ONLY_IN_LINE case, check that NEW_POS and
888 FIELD_BOUND are on the same line by seeing whether
889 there's an intervening newline or not. */
890 || (find_newline (XFASTINT (new_pos), -1,
891 XFASTINT (field_bound), -1,
892 fwd ? -1 : 1, &shortage, NULL, 1),
893 shortage != 0)))
894 /* Constrain NEW_POS to FIELD_BOUND. */
895 new_pos = field_bound;
897 if (orig_point && XFASTINT (new_pos) != orig_point)
898 /* The NEW_POS argument was originally nil, so automatically set PT. */
899 SET_PT (XFASTINT (new_pos));
902 return new_pos;
906 DEFUN ("line-beginning-position",
907 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
908 doc: /* Return the character position of the first character on the current line.
909 With optional argument N, scan forward N - 1 lines first.
910 If the scan reaches the end of the buffer, return that position.
912 This function ignores text display directionality; it returns the
913 position of the first character in logical order, i.e. the smallest
914 character position on the line.
916 This function constrains the returned position to the current field
917 unless that position would be on a different line than the original,
918 unconstrained result. If N is nil or 1, and a front-sticky field
919 starts at point, the scan stops as soon as it starts. To ignore field
920 boundaries, bind `inhibit-field-text-motion' to t.
922 This function does not move point. */)
923 (Lisp_Object n)
925 ptrdiff_t charpos, bytepos;
927 if (NILP (n))
928 XSETFASTINT (n, 1);
929 else
930 CHECK_NUMBER (n);
932 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
934 /* Return END constrained to the current input field. */
935 return Fconstrain_to_field (make_number (charpos), make_number (PT),
936 XINT (n) != 1 ? Qt : Qnil,
937 Qt, Qnil);
940 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
941 doc: /* Return the character position of the last character on the current line.
942 With argument N not nil or 1, move forward N - 1 lines first.
943 If scan reaches end of buffer, return that position.
945 This function ignores text display directionality; it returns the
946 position of the last character in logical order, i.e. the largest
947 character position on the line.
949 This function constrains the returned position to the current field
950 unless that would be on a different line than the original,
951 unconstrained result. If N is nil or 1, and a rear-sticky field ends
952 at point, the scan stops as soon as it starts. To ignore field
953 boundaries bind `inhibit-field-text-motion' to t.
955 This function does not move point. */)
956 (Lisp_Object n)
958 ptrdiff_t clipped_n;
959 ptrdiff_t end_pos;
960 ptrdiff_t orig = PT;
962 if (NILP (n))
963 XSETFASTINT (n, 1);
964 else
965 CHECK_NUMBER (n);
967 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
968 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
969 NULL);
971 /* Return END_POS constrained to the current input field. */
972 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
973 Qnil, Qt, Qnil);
976 /* Save current buffer state for `save-excursion' special form.
977 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
978 offload some work from GC. */
980 Lisp_Object
981 save_excursion_save (void)
983 return make_save_obj_obj_obj_obj
984 (Fpoint_marker (),
985 Qnil,
986 /* Selected window if current buffer is shown in it, nil otherwise. */
987 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
988 ? selected_window : Qnil),
989 Qnil);
992 /* Restore saved buffer before leaving `save-excursion' special form. */
994 void
995 save_excursion_restore (Lisp_Object info)
997 Lisp_Object tem, tem1;
999 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
1000 /* If we're unwinding to top level, saved buffer may be deleted. This
1001 means that all of its markers are unchained and so tem is nil. */
1002 if (NILP (tem))
1003 goto out;
1005 Fset_buffer (tem);
1007 /* Point marker. */
1008 tem = XSAVE_OBJECT (info, 0);
1009 Fgoto_char (tem);
1010 unchain_marker (XMARKER (tem));
1012 /* If buffer was visible in a window, and a different window was
1013 selected, and the old selected window is still showing this
1014 buffer, restore point in that window. */
1015 tem = XSAVE_OBJECT (info, 2);
1016 if (WINDOWP (tem)
1017 && !EQ (tem, selected_window)
1018 && (tem1 = XWINDOW (tem)->contents,
1019 (/* Window is live... */
1020 BUFFERP (tem1)
1021 /* ...and it shows the current buffer. */
1022 && XBUFFER (tem1) == current_buffer)))
1023 Fset_window_point (tem, make_number (PT));
1025 out:
1027 free_misc (info);
1030 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
1031 doc: /* Save point, and current buffer; execute BODY; restore those things.
1032 Executes BODY just like `progn'.
1033 The values of point and the current buffer are restored
1034 even in case of abnormal exit (throw or error).
1036 If you only want to save the current buffer but not point,
1037 then just use `save-current-buffer', or even `with-current-buffer'.
1039 Before Emacs 25.1, `save-excursion' used to save the mark state.
1040 To save the marker state as well as the point and buffer, use
1041 `save-mark-and-excursion'.
1043 usage: (save-excursion &rest BODY) */)
1044 (Lisp_Object args)
1046 register Lisp_Object val;
1047 ptrdiff_t count = SPECPDL_INDEX ();
1049 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1051 val = Fprogn (args);
1052 return unbind_to (count, val);
1055 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1056 doc: /* Record which buffer is current; execute BODY; make that buffer current.
1057 BODY is executed just like `progn'.
1058 usage: (save-current-buffer &rest BODY) */)
1059 (Lisp_Object args)
1061 ptrdiff_t count = SPECPDL_INDEX ();
1063 record_unwind_current_buffer ();
1064 return unbind_to (count, Fprogn (args));
1067 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
1068 doc: /* Return the number of characters in the current buffer.
1069 If BUFFER is not nil, return the number of characters in that buffer
1070 instead.
1072 This does not take narrowing into account; to count the number of
1073 characters in the accessible portion of the current buffer, use
1074 `(- (point-max) (point-min))', and to count the number of characters
1075 in some other BUFFER, use
1076 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1077 (Lisp_Object buffer)
1079 if (NILP (buffer))
1080 return make_number (Z - BEG);
1081 else
1083 CHECK_BUFFER (buffer);
1084 return make_number (BUF_Z (XBUFFER (buffer))
1085 - BUF_BEG (XBUFFER (buffer)));
1089 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1090 doc: /* Return the minimum permissible value of point in the current buffer.
1091 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1092 (void)
1094 Lisp_Object temp;
1095 XSETFASTINT (temp, BEGV);
1096 return temp;
1099 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1100 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1101 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1102 (void)
1104 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1107 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1108 doc: /* Return the maximum permissible value of point in the current buffer.
1109 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1110 is in effect, in which case it is less. */)
1111 (void)
1113 Lisp_Object temp;
1114 XSETFASTINT (temp, ZV);
1115 return temp;
1118 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1119 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1120 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1121 is in effect, in which case it is less. */)
1122 (void)
1124 return build_marker (current_buffer, ZV, ZV_BYTE);
1127 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1128 doc: /* Return the position of the gap, in the current buffer.
1129 See also `gap-size'. */)
1130 (void)
1132 Lisp_Object temp;
1133 XSETFASTINT (temp, GPT);
1134 return temp;
1137 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1138 doc: /* Return the size of the current buffer's gap.
1139 See also `gap-position'. */)
1140 (void)
1142 Lisp_Object temp;
1143 XSETFASTINT (temp, GAP_SIZE);
1144 return temp;
1147 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1148 doc: /* Return the byte position for character position POSITION.
1149 If POSITION is out of range, the value is nil. */)
1150 (Lisp_Object position)
1152 CHECK_NUMBER_COERCE_MARKER (position);
1153 if (XINT (position) < BEG || XINT (position) > Z)
1154 return Qnil;
1155 return make_number (CHAR_TO_BYTE (XINT (position)));
1158 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1159 doc: /* Return the character position for byte position BYTEPOS.
1160 If BYTEPOS is out of range, the value is nil. */)
1161 (Lisp_Object bytepos)
1163 ptrdiff_t pos_byte;
1165 CHECK_NUMBER (bytepos);
1166 pos_byte = XINT (bytepos);
1167 if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
1168 return Qnil;
1169 if (Z != Z_BYTE)
1170 /* There are multibyte characters in the buffer.
1171 The argument of BYTE_TO_CHAR must be a byte position at
1172 a character boundary, so search for the start of the current
1173 character. */
1174 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte)))
1175 pos_byte--;
1176 return make_number (BYTE_TO_CHAR (pos_byte));
1179 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1180 doc: /* Return the character following point, as a number.
1181 At the end of the buffer or accessible region, return 0. */)
1182 (void)
1184 Lisp_Object temp;
1185 if (PT >= ZV)
1186 XSETFASTINT (temp, 0);
1187 else
1188 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1189 return temp;
1192 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1193 doc: /* Return the character preceding point, as a number.
1194 At the beginning of the buffer or accessible region, return 0. */)
1195 (void)
1197 Lisp_Object temp;
1198 if (PT <= BEGV)
1199 XSETFASTINT (temp, 0);
1200 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1202 ptrdiff_t pos = PT_BYTE;
1203 DEC_POS (pos);
1204 XSETFASTINT (temp, FETCH_CHAR (pos));
1206 else
1207 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1208 return temp;
1211 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1212 doc: /* Return t if point is at the beginning of the buffer.
1213 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1214 (void)
1216 if (PT == BEGV)
1217 return Qt;
1218 return Qnil;
1221 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1222 doc: /* Return t if point is at the end of the buffer.
1223 If the buffer is narrowed, this means the end of the narrowed part. */)
1224 (void)
1226 if (PT == ZV)
1227 return Qt;
1228 return Qnil;
1231 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1232 doc: /* Return t if point is at the beginning of a line. */)
1233 (void)
1235 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1236 return Qt;
1237 return Qnil;
1240 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1241 doc: /* Return t if point is at the end of a line.
1242 `End of a line' includes point being at the end of the buffer. */)
1243 (void)
1245 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1246 return Qt;
1247 return Qnil;
1250 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1251 doc: /* Return character in current buffer at position POS.
1252 POS is an integer or a marker and defaults to point.
1253 If POS is out of range, the value is nil. */)
1254 (Lisp_Object pos)
1256 register ptrdiff_t pos_byte;
1258 if (NILP (pos))
1260 pos_byte = PT_BYTE;
1261 XSETFASTINT (pos, PT);
1264 if (MARKERP (pos))
1266 pos_byte = marker_byte_position (pos);
1267 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1268 return Qnil;
1270 else
1272 CHECK_NUMBER_COERCE_MARKER (pos);
1273 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1274 return Qnil;
1276 pos_byte = CHAR_TO_BYTE (XINT (pos));
1279 return make_number (FETCH_CHAR (pos_byte));
1282 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1283 doc: /* Return character in current buffer preceding position POS.
1284 POS is an integer or a marker and defaults to point.
1285 If POS is out of range, the value is nil. */)
1286 (Lisp_Object pos)
1288 register Lisp_Object val;
1289 register ptrdiff_t pos_byte;
1291 if (NILP (pos))
1293 pos_byte = PT_BYTE;
1294 XSETFASTINT (pos, PT);
1297 if (MARKERP (pos))
1299 pos_byte = marker_byte_position (pos);
1301 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1302 return Qnil;
1304 else
1306 CHECK_NUMBER_COERCE_MARKER (pos);
1308 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1309 return Qnil;
1311 pos_byte = CHAR_TO_BYTE (XINT (pos));
1314 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1316 DEC_POS (pos_byte);
1317 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1319 else
1321 pos_byte--;
1322 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1324 return val;
1327 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1328 doc: /* Return the name under which the user logged in, as a string.
1329 This is based on the effective uid, not the real uid.
1330 Also, if the environment variables LOGNAME or USER are set,
1331 that determines the value of this function.
1333 If optional argument UID is an integer or a float, return the login name
1334 of the user with that uid, or nil if there is no such user. */)
1335 (Lisp_Object uid)
1337 struct passwd *pw;
1338 uid_t id;
1340 /* Set up the user name info if we didn't do it before.
1341 (That can happen if Emacs is dumpable
1342 but you decide to run `temacs -l loadup' and not dump. */
1343 if (NILP (Vuser_login_name))
1344 init_editfns (false);
1346 if (NILP (uid))
1347 return Vuser_login_name;
1349 CONS_TO_INTEGER (uid, uid_t, id);
1350 block_input ();
1351 pw = getpwuid (id);
1352 unblock_input ();
1353 return (pw ? build_string (pw->pw_name) : Qnil);
1356 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1357 0, 0, 0,
1358 doc: /* Return the name of the user's real uid, as a string.
1359 This ignores the environment variables LOGNAME and USER, so it differs from
1360 `user-login-name' when running under `su'. */)
1361 (void)
1363 /* Set up the user name info if we didn't do it before.
1364 (That can happen if Emacs is dumpable
1365 but you decide to run `temacs -l loadup' and not dump. */
1366 if (NILP (Vuser_login_name))
1367 init_editfns (false);
1368 return Vuser_real_login_name;
1371 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1372 doc: /* Return the effective uid of Emacs.
1373 Value is an integer or a float, depending on the value. */)
1374 (void)
1376 uid_t euid = geteuid ();
1377 return make_fixnum_or_float (euid);
1380 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1381 doc: /* Return the real uid of Emacs.
1382 Value is an integer or a float, depending on the value. */)
1383 (void)
1385 uid_t uid = getuid ();
1386 return make_fixnum_or_float (uid);
1389 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1390 doc: /* Return the effective gid of Emacs.
1391 Value is an integer or a float, depending on the value. */)
1392 (void)
1394 gid_t egid = getegid ();
1395 return make_fixnum_or_float (egid);
1398 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1399 doc: /* Return the real gid of Emacs.
1400 Value is an integer or a float, depending on the value. */)
1401 (void)
1403 gid_t gid = getgid ();
1404 return make_fixnum_or_float (gid);
1407 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1408 doc: /* Return the full name of the user logged in, as a string.
1409 If the full name corresponding to Emacs's userid is not known,
1410 return "unknown".
1412 If optional argument UID is an integer or float, return the full name
1413 of the user with that uid, or nil if there is no such user.
1414 If UID is a string, return the full name of the user with that login
1415 name, or nil if there is no such user. */)
1416 (Lisp_Object uid)
1418 struct passwd *pw;
1419 register char *p, *q;
1420 Lisp_Object full;
1422 if (NILP (uid))
1423 return Vuser_full_name;
1424 else if (NUMBERP (uid))
1426 uid_t u;
1427 CONS_TO_INTEGER (uid, uid_t, u);
1428 block_input ();
1429 pw = getpwuid (u);
1430 unblock_input ();
1432 else if (STRINGP (uid))
1434 block_input ();
1435 pw = getpwnam (SSDATA (uid));
1436 unblock_input ();
1438 else
1439 error ("Invalid UID specification");
1441 if (!pw)
1442 return Qnil;
1444 p = USER_FULL_NAME;
1445 /* Chop off everything after the first comma. */
1446 q = strchr (p, ',');
1447 full = make_string (p, q ? q - p : strlen (p));
1449 #ifdef AMPERSAND_FULL_NAME
1450 p = SSDATA (full);
1451 q = strchr (p, '&');
1452 /* Substitute the login name for the &, upcasing the first character. */
1453 if (q)
1455 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1456 USE_SAFE_ALLOCA;
1457 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1458 memcpy (r, p, q - p);
1459 char *s = lispstpcpy (&r[q - p], login);
1460 r[q - p] = upcase ((unsigned char) r[q - p]);
1461 strcpy (s, q + 1);
1462 full = build_string (r);
1463 SAFE_FREE ();
1465 #endif /* AMPERSAND_FULL_NAME */
1467 return full;
1470 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1471 doc: /* Return the host name of the machine you are running on, as a string. */)
1472 (void)
1474 if (EQ (Vsystem_name, cached_system_name))
1475 init_and_cache_system_name ();
1476 return Vsystem_name;
1479 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1480 doc: /* Return the process ID of Emacs, as a number. */)
1481 (void)
1483 pid_t pid = getpid ();
1484 return make_fixnum_or_float (pid);
1489 #ifndef TIME_T_MIN
1490 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1491 #endif
1492 #ifndef TIME_T_MAX
1493 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1494 #endif
1496 /* Report that a time value is out of range for Emacs. */
1497 void
1498 time_overflow (void)
1500 error ("Specified time is not representable");
1503 static _Noreturn void
1504 invalid_time (void)
1506 error ("Invalid time specification");
1509 /* Check a return value compatible with that of decode_time_components. */
1510 static void
1511 check_time_validity (int validity)
1513 if (validity <= 0)
1515 if (validity < 0)
1516 time_overflow ();
1517 else
1518 invalid_time ();
1522 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1523 static EMACS_INT
1524 hi_time (time_t t)
1526 time_t hi = t >> LO_TIME_BITS;
1527 if (FIXNUM_OVERFLOW_P (hi))
1528 time_overflow ();
1529 return hi;
1532 /* Return the bottom bits of the time T. */
1533 static int
1534 lo_time (time_t t)
1536 return t & ((1 << LO_TIME_BITS) - 1);
1539 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1540 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1541 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1542 HIGH has the most significant bits of the seconds, while LOW has the
1543 least significant 16 bits. USEC and PSEC are the microsecond and
1544 picosecond counts. */)
1545 (void)
1547 return make_lisp_time (current_timespec ());
1550 static struct lisp_time
1551 time_add (struct lisp_time ta, struct lisp_time tb)
1553 EMACS_INT hi = ta.hi + tb.hi;
1554 int lo = ta.lo + tb.lo;
1555 int us = ta.us + tb.us;
1556 int ps = ta.ps + tb.ps;
1557 us += (1000000 <= ps);
1558 ps -= (1000000 <= ps) * 1000000;
1559 lo += (1000000 <= us);
1560 us -= (1000000 <= us) * 1000000;
1561 hi += (1 << LO_TIME_BITS <= lo);
1562 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1563 return (struct lisp_time) { hi, lo, us, ps };
1566 static struct lisp_time
1567 time_subtract (struct lisp_time ta, struct lisp_time tb)
1569 EMACS_INT hi = ta.hi - tb.hi;
1570 int lo = ta.lo - tb.lo;
1571 int us = ta.us - tb.us;
1572 int ps = ta.ps - tb.ps;
1573 us -= (ps < 0);
1574 ps += (ps < 0) * 1000000;
1575 lo -= (us < 0);
1576 us += (us < 0) * 1000000;
1577 hi -= (lo < 0);
1578 lo += (lo < 0) << LO_TIME_BITS;
1579 return (struct lisp_time) { hi, lo, us, ps };
1582 static Lisp_Object
1583 time_arith (Lisp_Object a, Lisp_Object b,
1584 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1586 int alen, blen;
1587 struct lisp_time ta = lisp_time_struct (a, &alen);
1588 struct lisp_time tb = lisp_time_struct (b, &blen);
1589 struct lisp_time t = op (ta, tb);
1590 if (FIXNUM_OVERFLOW_P (t.hi))
1591 time_overflow ();
1592 Lisp_Object val = Qnil;
1594 switch (max (alen, blen))
1596 default:
1597 val = Fcons (make_number (t.ps), val);
1598 /* Fall through. */
1599 case 3:
1600 val = Fcons (make_number (t.us), val);
1601 /* Fall through. */
1602 case 2:
1603 val = Fcons (make_number (t.lo), val);
1604 val = Fcons (make_number (t.hi), val);
1605 break;
1608 return val;
1611 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1612 doc: /* Return the sum of two time values A and B, as a time value. */)
1613 (Lisp_Object a, Lisp_Object b)
1615 return time_arith (a, b, time_add);
1618 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1619 doc: /* Return the difference between two time values A and B, as a time value. */)
1620 (Lisp_Object a, Lisp_Object b)
1622 return time_arith (a, b, time_subtract);
1625 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1626 doc: /* Return non-nil if time value T1 is earlier than time value T2. */)
1627 (Lisp_Object t1, Lisp_Object t2)
1629 int t1len, t2len;
1630 struct lisp_time a = lisp_time_struct (t1, &t1len);
1631 struct lisp_time b = lisp_time_struct (t2, &t2len);
1632 return ((a.hi != b.hi ? a.hi < b.hi
1633 : a.lo != b.lo ? a.lo < b.lo
1634 : a.us != b.us ? a.us < b.us
1635 : a.ps < b.ps)
1636 ? Qt : Qnil);
1640 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1641 0, 0, 0,
1642 doc: /* Return the current run time used by Emacs.
1643 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1644 style as (current-time).
1646 On systems that can't determine the run time, `get-internal-run-time'
1647 does the same thing as `current-time'. */)
1648 (void)
1650 #ifdef HAVE_GETRUSAGE
1651 struct rusage usage;
1652 time_t secs;
1653 int usecs;
1655 if (getrusage (RUSAGE_SELF, &usage) < 0)
1656 /* This shouldn't happen. What action is appropriate? */
1657 xsignal0 (Qerror);
1659 /* Sum up user time and system time. */
1660 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1661 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1662 if (usecs >= 1000000)
1664 usecs -= 1000000;
1665 secs++;
1667 return make_lisp_time (make_timespec (secs, usecs * 1000));
1668 #else /* ! HAVE_GETRUSAGE */
1669 #ifdef WINDOWSNT
1670 return w32_get_internal_run_time ();
1671 #else /* ! WINDOWSNT */
1672 return Fcurrent_time ();
1673 #endif /* WINDOWSNT */
1674 #endif /* HAVE_GETRUSAGE */
1678 /* Make a Lisp list that represents the Emacs time T. T may be an
1679 invalid time, with a slightly negative tv_nsec value such as
1680 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1681 correspondingly negative picosecond count. */
1682 Lisp_Object
1683 make_lisp_time (struct timespec t)
1685 time_t s = t.tv_sec;
1686 int ns = t.tv_nsec;
1687 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1690 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1691 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1692 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1693 if successful, 0 if unsuccessful. */
1694 static int
1695 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1696 Lisp_Object *plow, Lisp_Object *pusec,
1697 Lisp_Object *ppsec)
1699 Lisp_Object high = make_number (0);
1700 Lisp_Object low = specified_time;
1701 Lisp_Object usec = make_number (0);
1702 Lisp_Object psec = make_number (0);
1703 int len = 4;
1705 if (CONSP (specified_time))
1707 high = XCAR (specified_time);
1708 low = XCDR (specified_time);
1709 if (CONSP (low))
1711 Lisp_Object low_tail = XCDR (low);
1712 low = XCAR (low);
1713 if (CONSP (low_tail))
1715 usec = XCAR (low_tail);
1716 low_tail = XCDR (low_tail);
1717 if (CONSP (low_tail))
1718 psec = XCAR (low_tail);
1719 else
1720 len = 3;
1722 else if (!NILP (low_tail))
1724 usec = low_tail;
1725 len = 3;
1727 else
1728 len = 2;
1730 else
1731 len = 2;
1733 /* When combining components, require LOW to be an integer,
1734 as otherwise it would be a pain to add up times. */
1735 if (! INTEGERP (low))
1736 return 0;
1738 else if (INTEGERP (specified_time))
1739 len = 2;
1741 *phigh = high;
1742 *plow = low;
1743 *pusec = usec;
1744 *ppsec = psec;
1745 return len;
1748 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1749 Return true if T is in range, false otherwise. */
1750 static bool
1751 decode_float_time (double t, struct lisp_time *result)
1753 double lo_multiplier = 1 << LO_TIME_BITS;
1754 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1755 if (! (emacs_time_min <= t && t < -emacs_time_min))
1756 return false;
1758 double small_t = t / lo_multiplier;
1759 EMACS_INT hi = small_t;
1760 double t_sans_hi = t - hi * lo_multiplier;
1761 int lo = t_sans_hi;
1762 long double fracps = (t_sans_hi - lo) * 1e12L;
1763 #ifdef INT_FAST64_MAX
1764 int_fast64_t ifracps = fracps;
1765 int us = ifracps / 1000000;
1766 int ps = ifracps % 1000000;
1767 #else
1768 int us = fracps / 1e6L;
1769 int ps = fracps - us * 1e6L;
1770 #endif
1771 us -= (ps < 0);
1772 ps += (ps < 0) * 1000000;
1773 lo -= (us < 0);
1774 us += (us < 0) * 1000000;
1775 hi -= (lo < 0);
1776 lo += (lo < 0) << LO_TIME_BITS;
1777 result->hi = hi;
1778 result->lo = lo;
1779 result->us = us;
1780 result->ps = ps;
1781 return true;
1784 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1785 list, generate the corresponding time value.
1786 If LOW is floating point, the other components should be zero.
1788 If RESULT is not null, store into *RESULT the converted time.
1789 If *DRESULT is not null, store into *DRESULT the number of
1790 seconds since the start of the POSIX Epoch.
1792 Return 1 if successful, 0 if the components are of the
1793 wrong type, and -1 if the time is out of range. */
1795 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1796 Lisp_Object psec,
1797 struct lisp_time *result, double *dresult)
1799 EMACS_INT hi, lo, us, ps;
1800 if (! (INTEGERP (high)
1801 && INTEGERP (usec) && INTEGERP (psec)))
1802 return 0;
1803 if (! INTEGERP (low))
1805 if (FLOATP (low))
1807 double t = XFLOAT_DATA (low);
1808 if (result && ! decode_float_time (t, result))
1809 return -1;
1810 if (dresult)
1811 *dresult = t;
1812 return 1;
1814 else if (NILP (low))
1816 struct timespec now = current_timespec ();
1817 if (result)
1819 result->hi = hi_time (now.tv_sec);
1820 result->lo = lo_time (now.tv_sec);
1821 result->us = now.tv_nsec / 1000;
1822 result->ps = now.tv_nsec % 1000 * 1000;
1824 if (dresult)
1825 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1826 return 1;
1828 else
1829 return 0;
1832 hi = XINT (high);
1833 lo = XINT (low);
1834 us = XINT (usec);
1835 ps = XINT (psec);
1837 /* Normalize out-of-range lower-order components by carrying
1838 each overflow into the next higher-order component. */
1839 us += ps / 1000000 - (ps % 1000000 < 0);
1840 lo += us / 1000000 - (us % 1000000 < 0);
1841 hi += lo >> LO_TIME_BITS;
1842 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1843 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1844 lo &= (1 << LO_TIME_BITS) - 1;
1846 if (result)
1848 if (FIXNUM_OVERFLOW_P (hi))
1849 return -1;
1850 result->hi = hi;
1851 result->lo = lo;
1852 result->us = us;
1853 result->ps = ps;
1856 if (dresult)
1858 double dhi = hi;
1859 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1862 return 1;
1865 struct timespec
1866 lisp_to_timespec (struct lisp_time t)
1868 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1869 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1870 return invalid_timespec ();
1871 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1872 int ns = t.us * 1000 + t.ps / 1000;
1873 return make_timespec (s, ns);
1876 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1877 Store its effective length into *PLEN.
1878 If SPECIFIED_TIME is nil, use the current time.
1879 Signal an error if SPECIFIED_TIME does not represent a time. */
1880 static struct lisp_time
1881 lisp_time_struct (Lisp_Object specified_time, int *plen)
1883 Lisp_Object high, low, usec, psec;
1884 struct lisp_time t;
1885 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1886 if (!len)
1887 invalid_time ();
1888 int val = decode_time_components (high, low, usec, psec, &t, 0);
1889 check_time_validity (val);
1890 *plen = len;
1891 return t;
1894 /* Like lisp_time_struct, except return a struct timespec.
1895 Discard any low-order digits. */
1896 struct timespec
1897 lisp_time_argument (Lisp_Object specified_time)
1899 int len;
1900 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1901 struct timespec t = lisp_to_timespec (lt);
1902 if (! timespec_valid_p (t))
1903 time_overflow ();
1904 return t;
1907 /* Like lisp_time_argument, except decode only the seconds part,
1908 and do not check the subseconds part. */
1909 static time_t
1910 lisp_seconds_argument (Lisp_Object specified_time)
1912 Lisp_Object high, low, usec, psec;
1913 struct lisp_time t;
1915 int val = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1916 if (val != 0)
1918 val = decode_time_components (high, low, make_number (0),
1919 make_number (0), &t, 0);
1920 if (0 < val
1921 && ! ((TYPE_SIGNED (time_t)
1922 ? TIME_T_MIN >> LO_TIME_BITS <= t.hi
1923 : 0 <= t.hi)
1924 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1925 val = -1;
1927 check_time_validity (val);
1928 return (t.hi << LO_TIME_BITS) + t.lo;
1931 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1932 doc: /* Return the current time, as a float number of seconds since the epoch.
1933 If SPECIFIED-TIME is given, it is the time to convert to float
1934 instead of the current time. The argument should have the form
1935 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1936 you can use times from `current-time' and from `file-attributes'.
1937 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1938 considered obsolete.
1940 WARNING: Since the result is floating point, it may not be exact.
1941 If precise time stamps are required, use either `current-time',
1942 or (if you need time as a string) `format-time-string'. */)
1943 (Lisp_Object specified_time)
1945 double t;
1946 Lisp_Object high, low, usec, psec;
1947 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1948 && decode_time_components (high, low, usec, psec, 0, &t)))
1949 invalid_time ();
1950 return make_float (t);
1953 /* Write information into buffer S of size MAXSIZE, according to the
1954 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1955 Use the time zone specified by TZ.
1956 Use NS as the number of nanoseconds in the %N directive.
1957 Return the number of bytes written, not including the terminating
1958 '\0'. If S is NULL, nothing will be written anywhere; so to
1959 determine how many bytes would be written, use NULL for S and
1960 ((size_t) -1) for MAXSIZE.
1962 This function behaves like nstrftime, except it allows null
1963 bytes in FORMAT and it does not support nanoseconds. */
1964 static size_t
1965 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1966 size_t format_len, const struct tm *tp, timezone_t tz, int ns)
1968 size_t total = 0;
1970 /* Loop through all the null-terminated strings in the format
1971 argument. Normally there's just one null-terminated string, but
1972 there can be arbitrarily many, concatenated together, if the
1973 format contains '\0' bytes. nstrftime stops at the first
1974 '\0' byte so we must invoke it separately for each such string. */
1975 for (;;)
1977 size_t len;
1978 size_t result;
1980 if (s)
1981 s[0] = '\1';
1983 result = nstrftime (s, maxsize, format, tp, tz, ns);
1985 if (s)
1987 if (result == 0 && s[0] != '\0')
1988 return 0;
1989 s += result + 1;
1992 maxsize -= result + 1;
1993 total += result;
1994 len = strlen (format);
1995 if (len == format_len)
1996 return total;
1997 total++;
1998 format += len + 1;
1999 format_len -= len + 1;
2003 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
2004 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
2005 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2006 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
2007 is also still accepted.
2009 The optional ZONE is omitted or nil for Emacs local time, t for
2010 Universal Time, `wall' for system wall clock time, or a string as in
2011 the TZ environment variable. It can also be a list (as from
2012 `current-time-zone') or an integer (as from `decode-time') applied
2013 without consideration for daylight saving time.
2015 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2016 by text that describes the specified date and time in TIME:
2018 %Y is the year, %y within the century, %C the century.
2019 %G is the year corresponding to the ISO week, %g within the century.
2020 %m is the numeric month.
2021 %b and %h are the locale's abbreviated month name, %B the full name.
2022 (%h is not supported on MS-Windows.)
2023 %d is the day of the month, zero-padded, %e is blank-padded.
2024 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2025 %a is the locale's abbreviated name of the day of week, %A the full name.
2026 %U is the week number starting on Sunday, %W starting on Monday,
2027 %V according to ISO 8601.
2028 %j is the day of the year.
2030 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2031 only blank-padded, %l is like %I blank-padded.
2032 %p is the locale's equivalent of either AM or PM.
2033 %M is the minute.
2034 %S is the second.
2035 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2036 %Z is the time zone name, %z is the numeric form.
2037 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2039 %c is the locale's date and time format.
2040 %x is the locale's "preferred" date format.
2041 %D is like "%m/%d/%y".
2042 %F is the ISO 8601 date format (like "%Y-%m-%d").
2044 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2045 %X is the locale's "preferred" time format.
2047 Finally, %n is a newline, %t is a tab, %% is a literal %.
2049 Certain flags and modifiers are available with some format controls.
2050 The flags are `_', `-', `^' and `#'. For certain characters X,
2051 %_X is like %X, but padded with blanks; %-X is like %X,
2052 but without padding. %^X is like %X, but with all textual
2053 characters up-cased; %#X is like %X, but with letter-case of
2054 all textual characters reversed.
2055 %NX (where N stands for an integer) is like %X,
2056 but takes up at least N (a number) positions.
2057 The modifiers are `E' and `O'. For certain characters X,
2058 %EX is a locale's alternative version of %X;
2059 %OX is like %X, but uses the locale's number symbols.
2061 For example, to produce full ISO 8601 format, use "%FT%T%z".
2063 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2064 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object zone)
2066 struct timespec t = lisp_time_argument (timeval);
2067 struct tm tm;
2069 CHECK_STRING (format_string);
2070 format_string = code_convert_string_norecord (format_string,
2071 Vlocale_coding_system, 1);
2072 return format_time_string (SSDATA (format_string), SBYTES (format_string),
2073 t, zone, &tm);
2076 static Lisp_Object
2077 format_time_string (char const *format, ptrdiff_t formatlen,
2078 struct timespec t, Lisp_Object zone, struct tm *tmp)
2080 char buffer[4000];
2081 char *buf = buffer;
2082 ptrdiff_t size = sizeof buffer;
2083 size_t len;
2084 int ns = t.tv_nsec;
2085 USE_SAFE_ALLOCA;
2087 timezone_t tz = tzlookup (zone, false);
2088 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2089 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2090 expects a pointer to time_t value. */
2091 time_t tsec = t.tv_sec;
2092 tmp = emacs_localtime_rz (tz, &tsec, tmp);
2093 if (! tmp)
2095 xtzfree (tz);
2096 time_overflow ();
2098 synchronize_system_time_locale ();
2100 while (true)
2102 buf[0] = '\1';
2103 len = emacs_nmemftime (buf, size, format, formatlen, tmp, tz, ns);
2104 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
2105 break;
2107 /* Buffer was too small, so make it bigger and try again. */
2108 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, tz, ns);
2109 if (STRING_BYTES_BOUND <= len)
2111 xtzfree (tz);
2112 string_overflow ();
2114 size = len + 1;
2115 buf = SAFE_ALLOCA (size);
2118 xtzfree (tz);
2119 AUTO_STRING_WITH_LEN (bufstring, buf, len);
2120 Lisp_Object result = code_convert_string_norecord (bufstring,
2121 Vlocale_coding_system, 0);
2122 SAFE_FREE ();
2123 return result;
2126 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 2, 0,
2127 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2128 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
2129 as from `current-time' and `file-attributes', or nil to use the
2130 current time. The obsolete form (HIGH . LOW) is also still accepted.
2132 The optional ZONE is omitted or nil for Emacs local time, t for
2133 Universal Time, `wall' for system wall clock time, or a string as in
2134 the TZ environment variable. It can also be a list (as from
2135 `current-time-zone') or an integer (as from `decode-time') applied
2136 without consideration for daylight saving time.
2138 The list has the following nine members: SEC is an integer between 0
2139 and 60; SEC is 60 for a leap second, which only some operating systems
2140 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2141 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2142 integer between 1 and 12. YEAR is an integer indicating the
2143 four-digit year. DOW is the day of week, an integer between 0 and 6,
2144 where 0 is Sunday. DST is t if daylight saving time is in effect,
2145 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2146 seconds, i.e., the number of seconds east of Greenwich. (Note that
2147 Common Lisp has different meanings for DOW and UTCOFF.)
2149 usage: (decode-time &optional TIME ZONE) */)
2150 (Lisp_Object specified_time, Lisp_Object zone)
2152 time_t time_spec = lisp_seconds_argument (specified_time);
2153 struct tm local_tm, gmt_tm;
2154 timezone_t tz = tzlookup (zone, false);
2155 struct tm *tm = emacs_localtime_rz (tz, &time_spec, &local_tm);
2156 xtzfree (tz);
2158 if (! (tm
2159 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2160 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2161 time_overflow ();
2163 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2164 EMACS_INT tm_year_base = TM_YEAR_BASE;
2166 return CALLN (Flist,
2167 make_number (local_tm.tm_sec),
2168 make_number (local_tm.tm_min),
2169 make_number (local_tm.tm_hour),
2170 make_number (local_tm.tm_mday),
2171 make_number (local_tm.tm_mon + 1),
2172 make_number (local_tm.tm_year + tm_year_base),
2173 make_number (local_tm.tm_wday),
2174 local_tm.tm_isdst ? Qt : Qnil,
2175 (HAVE_TM_GMTOFF
2176 ? make_number (tm_gmtoff (&local_tm))
2177 : gmtime_r (&time_spec, &gmt_tm)
2178 ? make_number (tm_diff (&local_tm, &gmt_tm))
2179 : Qnil));
2182 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2183 the result is representable as an int. */
2184 static int
2185 check_tm_member (Lisp_Object obj, int offset)
2187 CHECK_NUMBER (obj);
2188 EMACS_INT n = XINT (obj);
2189 int result;
2190 if (INT_SUBTRACT_WRAPV (n, offset, &result))
2191 time_overflow ();
2192 return result;
2195 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2196 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2197 This is the reverse operation of `decode-time', which see.
2199 The optional ZONE is omitted or nil for Emacs local time, t for
2200 Universal Time, `wall' for system wall clock time, or a string as in
2201 the TZ environment variable. It can also be a list (as from
2202 `current-time-zone') or an integer (as from `decode-time') applied
2203 without consideration for daylight saving time.
2205 You can pass more than 7 arguments; then the first six arguments
2206 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2207 The intervening arguments are ignored.
2208 This feature lets (apply \\='encode-time (decode-time ...)) work.
2210 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2211 for example, a DAY of 0 means the day preceding the given month.
2212 Year numbers less than 100 are treated just like other year numbers.
2213 If you want them to stand for years in this century, you must do that yourself.
2215 Years before 1970 are not guaranteed to work. On some systems,
2216 year values as low as 1901 do work.
2218 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2219 (ptrdiff_t nargs, Lisp_Object *args)
2221 time_t value;
2222 struct tm tm;
2223 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2225 tm.tm_sec = check_tm_member (args[0], 0);
2226 tm.tm_min = check_tm_member (args[1], 0);
2227 tm.tm_hour = check_tm_member (args[2], 0);
2228 tm.tm_mday = check_tm_member (args[3], 0);
2229 tm.tm_mon = check_tm_member (args[4], 1);
2230 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2231 tm.tm_isdst = -1;
2233 timezone_t tz = tzlookup (zone, false);
2234 value = emacs_mktime_z (tz, &tm);
2235 xtzfree (tz);
2237 if (value == (time_t) -1)
2238 time_overflow ();
2240 return list2i (hi_time (value), lo_time (value));
2243 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string,
2244 0, 2, 0,
2245 doc: /* Return the current local time, as a human-readable string.
2246 Programs can use this function to decode a time,
2247 since the number of columns in each field is fixed
2248 if the year is in the range 1000-9999.
2249 The format is `Sun Sep 16 01:03:52 1973'.
2250 However, see also the functions `decode-time' and `format-time-string'
2251 which provide a much more powerful and general facility.
2253 If SPECIFIED-TIME is given, it is a time to format instead of the
2254 current time. The argument should have the form (HIGH LOW . IGNORED).
2255 Thus, you can use times obtained from `current-time' and from
2256 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
2257 but this is considered obsolete.
2259 The optional ZONE is omitted or nil for Emacs local time, t for
2260 Universal Time, `wall' for system wall clock time, or a string as in
2261 the TZ environment variable. It can also be a list (as from
2262 `current-time-zone') or an integer (as from `decode-time') applied
2263 without consideration for daylight saving time. */)
2264 (Lisp_Object specified_time, Lisp_Object zone)
2266 time_t value = lisp_seconds_argument (specified_time);
2267 timezone_t tz = tzlookup (zone, false);
2269 /* Convert to a string in ctime format, except without the trailing
2270 newline, and without the 4-digit year limit. Don't use asctime
2271 or ctime, as they might dump core if the year is outside the
2272 range -999 .. 9999. */
2273 struct tm tm;
2274 struct tm *tmp = emacs_localtime_rz (tz, &value, &tm);
2275 xtzfree (tz);
2276 if (! tmp)
2277 time_overflow ();
2279 static char const wday_name[][4] =
2280 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2281 static char const mon_name[][4] =
2282 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2283 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2284 printmax_t year_base = TM_YEAR_BASE;
2285 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2286 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2287 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2288 tm.tm_hour, tm.tm_min, tm.tm_sec,
2289 tm.tm_year + year_base);
2291 return make_unibyte_string (buf, len);
2294 /* Yield A - B, measured in seconds.
2295 This function is copied from the GNU C Library. */
2296 static int
2297 tm_diff (struct tm *a, struct tm *b)
2299 /* Compute intervening leap days correctly even if year is negative.
2300 Take care to avoid int overflow in leap day calculations,
2301 but it's OK to assume that A and B are close to each other. */
2302 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2303 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2304 int a100 = a4 / 25 - (a4 % 25 < 0);
2305 int b100 = b4 / 25 - (b4 % 25 < 0);
2306 int a400 = a100 >> 2;
2307 int b400 = b100 >> 2;
2308 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2309 int years = a->tm_year - b->tm_year;
2310 int days = (365 * years + intervening_leap_days
2311 + (a->tm_yday - b->tm_yday));
2312 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2313 + (a->tm_min - b->tm_min))
2314 + (a->tm_sec - b->tm_sec));
2317 /* Yield A's UTC offset, or an unspecified value if unknown. */
2318 static long int
2319 tm_gmtoff (struct tm *a)
2321 #if HAVE_TM_GMTOFF
2322 return a->tm_gmtoff;
2323 #else
2324 return 0;
2325 #endif
2328 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 2, 0,
2329 doc: /* Return the offset and name for the local time zone.
2330 This returns a list of the form (OFFSET NAME).
2331 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2332 A negative value means west of Greenwich.
2333 NAME is a string giving the name of the time zone.
2334 If SPECIFIED-TIME is given, the time zone offset is determined from it
2335 instead of using the current time. The argument should have the form
2336 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2337 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2338 have the form (HIGH . LOW), but this is considered obsolete.
2340 The optional ZONE is omitted or nil for Emacs local time, t for
2341 Universal Time, `wall' for system wall clock time, or a string as in
2342 the TZ environment variable. It can also be a list (as from
2343 `current-time-zone') or an integer (as from `decode-time') applied
2344 without consideration for daylight saving time.
2346 Some operating systems cannot provide all this information to Emacs;
2347 in this case, `current-time-zone' returns a list containing nil for
2348 the data it can't find. */)
2349 (Lisp_Object specified_time, Lisp_Object zone)
2351 struct timespec value;
2352 struct tm local_tm, gmt_tm;
2353 Lisp_Object zone_offset, zone_name;
2355 zone_offset = Qnil;
2356 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2357 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value,
2358 zone, &local_tm);
2360 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2361 timespec on some systems (MinGW) is a 64-bit field. */
2362 time_t tsec = value.tv_sec;
2363 if (HAVE_TM_GMTOFF || gmtime_r (&tsec, &gmt_tm))
2365 long int offset = (HAVE_TM_GMTOFF
2366 ? tm_gmtoff (&local_tm)
2367 : tm_diff (&local_tm, &gmt_tm));
2368 zone_offset = make_number (offset);
2369 if (SCHARS (zone_name) == 0)
2371 /* No local time zone name is available; use numeric zone instead. */
2372 long int hour = offset / 3600;
2373 int min_sec = offset % 3600;
2374 int amin_sec = min_sec < 0 ? - min_sec : min_sec;
2375 int min = amin_sec / 60;
2376 int sec = amin_sec % 60;
2377 int min_prec = min_sec ? 2 : 0;
2378 int sec_prec = sec ? 2 : 0;
2379 char buf[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2380 zone_name = make_formatted_string (buf, "%c%.2ld%.*d%.*d",
2381 (offset < 0 ? '-' : '+'),
2382 hour, min_prec, min, sec_prec, sec);
2386 return list2 (zone_offset, zone_name);
2389 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2390 doc: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2391 If TZ is nil or `wall', use system wall clock time; this differs from
2392 the usual Emacs convention where nil means current local time. If TZ
2393 is t, use Universal Time. If TZ is a list (as from
2394 `current-time-zone') or an integer (as from `decode-time'), use the
2395 specified time zone without consideration for daylight saving time.
2397 Instead of calling this function, you typically want something else.
2398 To temporarily use a different time zone rule for just one invocation
2399 of `decode-time', `encode-time', or `format-time-string', pass the
2400 function a ZONE argument. To change local time consistently
2401 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2402 environment of the Emacs process and the variable
2403 `process-environment', whereas `set-time-zone-rule' affects only the
2404 former. */)
2405 (Lisp_Object tz)
2407 tzlookup (NILP (tz) ? Qwall : tz, true);
2408 return Qnil;
2411 /* A buffer holding a string of the form "TZ=value", intended
2412 to be part of the environment. If TZ is supposed to be unset,
2413 the buffer string is "tZ=". */
2414 static char *tzvalbuf;
2416 /* Get the local time zone rule. */
2417 char *
2418 emacs_getenv_TZ (void)
2420 return tzvalbuf[0] == 'T' ? tzvalbuf + tzeqlen : 0;
2423 /* Set the local time zone rule to TZSTRING, which can be null to
2424 denote wall clock time. Do not record the setting in LOCAL_TZ.
2426 This function is not thread-safe, in theory because putenv is not,
2427 but mostly because of the static storage it updates. Other threads
2428 that invoke localtime etc. may be adversely affected while this
2429 function is executing. */
2432 emacs_setenv_TZ (const char *tzstring)
2434 static ptrdiff_t tzvalbufsize;
2435 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2436 char *tzval = tzvalbuf;
2437 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2439 if (new_tzvalbuf)
2441 /* Do not attempt to free the old tzvalbuf, since another thread
2442 may be using it. In practice, the first allocation is large
2443 enough and memory does not leak. */
2444 tzval = xpalloc (NULL, &tzvalbufsize,
2445 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2446 tzvalbuf = tzval;
2447 tzval[1] = 'Z';
2448 tzval[2] = '=';
2451 if (tzstring)
2453 /* Modify TZVAL in place. Although this is dicey in a
2454 multithreaded environment, we know of no portable alternative.
2455 Calling putenv or setenv could crash some other thread. */
2456 tzval[0] = 'T';
2457 strcpy (tzval + tzeqlen, tzstring);
2459 else
2461 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2462 Although this is also dicey, calling unsetenv here can crash Emacs.
2463 See Bug#8705. */
2464 tzval[0] = 't';
2465 tzval[tzeqlen] = 0;
2469 #ifndef WINDOWSNT
2470 /* Modifying *TZVAL merely requires calling tzset (which is the
2471 caller's responsibility). However, modifying TZVAL requires
2472 calling putenv; although this is not thread-safe, in practice this
2473 runs only on startup when there is only one thread. */
2474 bool need_putenv = new_tzvalbuf;
2475 #else
2476 /* MS-Windows 'putenv' copies the argument string into a block it
2477 allocates, so modifying *TZVAL will not change the environment.
2478 However, the other threads run by Emacs on MS-Windows never call
2479 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2480 dicey in-place modification technique doesn't exist there in the
2481 first place. */
2482 bool need_putenv = true;
2483 #endif
2484 if (need_putenv)
2485 xputenv (tzval);
2487 return 0;
2490 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2491 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2492 type of object is Lisp_String). INHERIT is passed to
2493 INSERT_FROM_STRING_FUNC as the last argument. */
2495 static void
2496 general_insert_function (void (*insert_func)
2497 (const char *, ptrdiff_t),
2498 void (*insert_from_string_func)
2499 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2500 ptrdiff_t, ptrdiff_t, bool),
2501 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2503 ptrdiff_t argnum;
2504 Lisp_Object val;
2506 for (argnum = 0; argnum < nargs; argnum++)
2508 val = args[argnum];
2509 if (CHARACTERP (val))
2511 int c = XFASTINT (val);
2512 unsigned char str[MAX_MULTIBYTE_LENGTH];
2513 int len;
2515 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2516 len = CHAR_STRING (c, str);
2517 else
2519 str[0] = CHAR_TO_BYTE8 (c);
2520 len = 1;
2522 (*insert_func) ((char *) str, len);
2524 else if (STRINGP (val))
2526 (*insert_from_string_func) (val, 0, 0,
2527 SCHARS (val),
2528 SBYTES (val),
2529 inherit);
2531 else
2532 wrong_type_argument (Qchar_or_string_p, val);
2536 void
2537 insert1 (Lisp_Object arg)
2539 Finsert (1, &arg);
2543 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2544 doc: /* Insert the arguments, either strings or characters, at point.
2545 Point and after-insertion markers move forward to end up
2546 after the inserted text.
2547 Any other markers at the point of insertion remain before the text.
2549 If the current buffer is multibyte, unibyte strings are converted
2550 to multibyte for insertion (see `string-make-multibyte').
2551 If the current buffer is unibyte, multibyte strings are converted
2552 to unibyte for insertion (see `string-make-unibyte').
2554 When operating on binary data, it may be necessary to preserve the
2555 original bytes of a unibyte string when inserting it into a multibyte
2556 buffer; to accomplish this, apply `string-as-multibyte' to the string
2557 and insert the result.
2559 usage: (insert &rest ARGS) */)
2560 (ptrdiff_t nargs, Lisp_Object *args)
2562 general_insert_function (insert, insert_from_string, 0, nargs, args);
2563 return Qnil;
2566 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2567 0, MANY, 0,
2568 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2569 Point and after-insertion markers move forward to end up
2570 after the inserted text.
2571 Any other markers at the point of insertion remain before the text.
2573 If the current buffer is multibyte, unibyte strings are converted
2574 to multibyte for insertion (see `unibyte-char-to-multibyte').
2575 If the current buffer is unibyte, multibyte strings are converted
2576 to unibyte for insertion.
2578 usage: (insert-and-inherit &rest ARGS) */)
2579 (ptrdiff_t nargs, Lisp_Object *args)
2581 general_insert_function (insert_and_inherit, insert_from_string, 1,
2582 nargs, args);
2583 return Qnil;
2586 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2587 doc: /* Insert strings or characters at point, relocating markers after the text.
2588 Point and markers move forward to end up after the inserted text.
2590 If the current buffer is multibyte, unibyte strings are converted
2591 to multibyte for insertion (see `unibyte-char-to-multibyte').
2592 If the current buffer is unibyte, multibyte strings are converted
2593 to unibyte for insertion.
2595 If an overlay begins at the insertion point, the inserted text falls
2596 outside the overlay; if a nonempty overlay ends at the insertion
2597 point, the inserted text falls inside that overlay.
2599 usage: (insert-before-markers &rest ARGS) */)
2600 (ptrdiff_t nargs, Lisp_Object *args)
2602 general_insert_function (insert_before_markers,
2603 insert_from_string_before_markers, 0,
2604 nargs, args);
2605 return Qnil;
2608 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2609 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2610 doc: /* Insert text at point, relocating markers and inheriting properties.
2611 Point and markers move forward to end up after the inserted text.
2613 If the current buffer is multibyte, unibyte strings are converted
2614 to multibyte for insertion (see `unibyte-char-to-multibyte').
2615 If the current buffer is unibyte, multibyte strings are converted
2616 to unibyte for insertion.
2618 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2619 (ptrdiff_t nargs, Lisp_Object *args)
2621 general_insert_function (insert_before_markers_and_inherit,
2622 insert_from_string_before_markers, 1,
2623 nargs, args);
2624 return Qnil;
2627 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2628 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2629 (prefix-numeric-value current-prefix-arg)\
2630 t))",
2631 doc: /* Insert COUNT copies of CHARACTER.
2632 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2633 of these ways:
2635 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2636 Completion is available; if you type a substring of the name
2637 preceded by an asterisk `*', Emacs shows all names which include
2638 that substring, not necessarily at the beginning of the name.
2640 - As a hexadecimal code point, e.g. 263A. Note that code points in
2641 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2642 the Unicode code space).
2644 - As a code point with a radix specified with #, e.g. #o21430
2645 (octal), #x2318 (hex), or #10r8984 (decimal).
2647 If called interactively, COUNT is given by the prefix argument. If
2648 omitted or nil, it defaults to 1.
2650 Inserting the character(s) relocates point and before-insertion
2651 markers in the same ways as the function `insert'.
2653 The optional third argument INHERIT, if non-nil, says to inherit text
2654 properties from adjoining text, if those properties are sticky. If
2655 called interactively, INHERIT is t. */)
2656 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2658 int i, stringlen;
2659 register ptrdiff_t n;
2660 int c, len;
2661 unsigned char str[MAX_MULTIBYTE_LENGTH];
2662 char string[4000];
2664 CHECK_CHARACTER (character);
2665 if (NILP (count))
2666 XSETFASTINT (count, 1);
2667 CHECK_NUMBER (count);
2668 c = XFASTINT (character);
2670 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2671 len = CHAR_STRING (c, str);
2672 else
2673 str[0] = c, len = 1;
2674 if (XINT (count) <= 0)
2675 return Qnil;
2676 if (BUF_BYTES_MAX / len < XINT (count))
2677 buffer_overflow ();
2678 n = XINT (count) * len;
2679 stringlen = min (n, sizeof string - sizeof string % len);
2680 for (i = 0; i < stringlen; i++)
2681 string[i] = str[i % len];
2682 while (n > stringlen)
2684 QUIT;
2685 if (!NILP (inherit))
2686 insert_and_inherit (string, stringlen);
2687 else
2688 insert (string, stringlen);
2689 n -= stringlen;
2691 if (!NILP (inherit))
2692 insert_and_inherit (string, n);
2693 else
2694 insert (string, n);
2695 return Qnil;
2698 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2699 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2700 Both arguments are required.
2701 BYTE is a number of the range 0..255.
2703 If BYTE is 128..255 and the current buffer is multibyte, the
2704 corresponding eight-bit character is inserted.
2706 Point, and before-insertion markers, are relocated as in the function `insert'.
2707 The optional third arg INHERIT, if non-nil, says to inherit text properties
2708 from adjoining text, if those properties are sticky. */)
2709 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2711 CHECK_NUMBER (byte);
2712 if (XINT (byte) < 0 || XINT (byte) > 255)
2713 args_out_of_range_3 (byte, make_number (0), make_number (255));
2714 if (XINT (byte) >= 128
2715 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2716 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2717 return Finsert_char (byte, count, inherit);
2721 /* Making strings from buffer contents. */
2723 /* Return a Lisp_String containing the text of the current buffer from
2724 START to END. If text properties are in use and the current buffer
2725 has properties in the range specified, the resulting string will also
2726 have them, if PROPS is true.
2728 We don't want to use plain old make_string here, because it calls
2729 make_uninit_string, which can cause the buffer arena to be
2730 compacted. make_string has no way of knowing that the data has
2731 been moved, and thus copies the wrong data into the string. This
2732 doesn't effect most of the other users of make_string, so it should
2733 be left as is. But we should use this function when conjuring
2734 buffer substrings. */
2736 Lisp_Object
2737 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2739 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2740 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2742 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2745 /* Return a Lisp_String containing the text of the current buffer from
2746 START / START_BYTE to END / END_BYTE.
2748 If text properties are in use and the current buffer
2749 has properties in the range specified, the resulting string will also
2750 have them, if PROPS is true.
2752 We don't want to use plain old make_string here, because it calls
2753 make_uninit_string, which can cause the buffer arena to be
2754 compacted. make_string has no way of knowing that the data has
2755 been moved, and thus copies the wrong data into the string. This
2756 doesn't effect most of the other users of make_string, so it should
2757 be left as is. But we should use this function when conjuring
2758 buffer substrings. */
2760 Lisp_Object
2761 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2762 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2764 Lisp_Object result, tem, tem1;
2765 ptrdiff_t beg0, end0, beg1, end1, size;
2767 if (start_byte < GPT_BYTE && GPT_BYTE < end_byte)
2769 /* Two regions, before and after the gap. */
2770 beg0 = start_byte;
2771 end0 = GPT_BYTE;
2772 beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
2773 end1 = end_byte + GAP_SIZE - BEG_BYTE;
2775 else
2777 /* The only region. */
2778 beg0 = start_byte;
2779 end0 = end_byte;
2780 beg1 = -1;
2781 end1 = -1;
2784 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2785 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2786 else
2787 result = make_uninit_string (end - start);
2789 size = end0 - beg0;
2790 memcpy (SDATA (result), BYTE_POS_ADDR (beg0), size);
2791 if (beg1 != -1)
2792 memcpy (SDATA (result) + size, BEG_ADDR + beg1, end1 - beg1);
2794 /* If desired, update and copy the text properties. */
2795 if (props)
2797 update_buffer_properties (start, end);
2799 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2800 tem1 = Ftext_properties_at (make_number (start), Qnil);
2802 if (XINT (tem) != end || !NILP (tem1))
2803 copy_intervals_to_string (result, current_buffer, start,
2804 end - start);
2807 return result;
2810 /* Call Vbuffer_access_fontify_functions for the range START ... END
2811 in the current buffer, if necessary. */
2813 static void
2814 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2816 /* If this buffer has some access functions,
2817 call them, specifying the range of the buffer being accessed. */
2818 if (!NILP (Vbuffer_access_fontify_functions))
2820 /* But don't call them if we can tell that the work
2821 has already been done. */
2822 if (!NILP (Vbuffer_access_fontified_property))
2824 Lisp_Object tem
2825 = Ftext_property_any (make_number (start), make_number (end),
2826 Vbuffer_access_fontified_property,
2827 Qnil, Qnil);
2828 if (NILP (tem))
2829 return;
2832 CALLN (Frun_hook_with_args, Qbuffer_access_fontify_functions,
2833 make_number (start), make_number (end));
2837 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2838 doc: /* Return the contents of part of the current buffer as a string.
2839 The two arguments START and END are character positions;
2840 they can be in either order.
2841 The string returned is multibyte if the buffer is multibyte.
2843 This function copies the text properties of that part of the buffer
2844 into the result string; if you don't want the text properties,
2845 use `buffer-substring-no-properties' instead. */)
2846 (Lisp_Object start, Lisp_Object end)
2848 register ptrdiff_t b, e;
2850 validate_region (&start, &end);
2851 b = XINT (start);
2852 e = XINT (end);
2854 return make_buffer_string (b, e, 1);
2857 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2858 Sbuffer_substring_no_properties, 2, 2, 0,
2859 doc: /* Return the characters of part of the buffer, without the text properties.
2860 The two arguments START and END are character positions;
2861 they can be in either order. */)
2862 (Lisp_Object start, Lisp_Object end)
2864 register ptrdiff_t b, e;
2866 validate_region (&start, &end);
2867 b = XINT (start);
2868 e = XINT (end);
2870 return make_buffer_string (b, e, 0);
2873 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2874 doc: /* Return the contents of the current buffer as a string.
2875 If narrowing is in effect, this function returns only the visible part
2876 of the buffer. */)
2877 (void)
2879 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2882 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2883 1, 3, 0,
2884 doc: /* Insert before point a substring of the contents of BUFFER.
2885 BUFFER may be a buffer or a buffer name.
2886 Arguments START and END are character positions specifying the substring.
2887 They default to the values of (point-min) and (point-max) in BUFFER.
2889 Point and before-insertion markers move forward to end up after the
2890 inserted text.
2891 Any other markers at the point of insertion remain before the text.
2893 If the current buffer is multibyte and BUFFER is unibyte, or vice
2894 versa, strings are converted from unibyte to multibyte or vice versa
2895 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2896 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2898 register EMACS_INT b, e, temp;
2899 register struct buffer *bp, *obuf;
2900 Lisp_Object buf;
2902 buf = Fget_buffer (buffer);
2903 if (NILP (buf))
2904 nsberror (buffer);
2905 bp = XBUFFER (buf);
2906 if (!BUFFER_LIVE_P (bp))
2907 error ("Selecting deleted buffer");
2909 if (NILP (start))
2910 b = BUF_BEGV (bp);
2911 else
2913 CHECK_NUMBER_COERCE_MARKER (start);
2914 b = XINT (start);
2916 if (NILP (end))
2917 e = BUF_ZV (bp);
2918 else
2920 CHECK_NUMBER_COERCE_MARKER (end);
2921 e = XINT (end);
2924 if (b > e)
2925 temp = b, b = e, e = temp;
2927 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2928 args_out_of_range (start, end);
2930 obuf = current_buffer;
2931 set_buffer_internal_1 (bp);
2932 update_buffer_properties (b, e);
2933 set_buffer_internal_1 (obuf);
2935 insert_from_buffer (bp, b, e - b, 0);
2936 return Qnil;
2939 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2940 6, 6, 0,
2941 doc: /* Compare two substrings of two buffers; return result as number.
2942 Return -N if first string is less after N-1 chars, +N if first string is
2943 greater after N-1 chars, or 0 if strings match.
2944 The first substring is in BUFFER1 from START1 to END1 and the second
2945 is in BUFFER2 from START2 to END2.
2946 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2947 buffer is used. If START1 or START2 is nil, the value of `point-min'
2948 in the respective buffers is used. If END1 or END2 is nil, the value
2949 of `point-max' in the respective buffers is used.
2950 The value of `case-fold-search' in the current buffer
2951 determines whether case is significant or ignored. */)
2952 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2954 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2955 register struct buffer *bp1, *bp2;
2956 register Lisp_Object trt
2957 = (!NILP (BVAR (current_buffer, case_fold_search))
2958 ? BVAR (current_buffer, case_canon_table) : Qnil);
2959 ptrdiff_t chars = 0;
2960 ptrdiff_t i1, i2, i1_byte, i2_byte;
2962 /* Find the first buffer and its substring. */
2964 if (NILP (buffer1))
2965 bp1 = current_buffer;
2966 else
2968 Lisp_Object buf1;
2969 buf1 = Fget_buffer (buffer1);
2970 if (NILP (buf1))
2971 nsberror (buffer1);
2972 bp1 = XBUFFER (buf1);
2973 if (!BUFFER_LIVE_P (bp1))
2974 error ("Selecting deleted buffer");
2977 if (NILP (start1))
2978 begp1 = BUF_BEGV (bp1);
2979 else
2981 CHECK_NUMBER_COERCE_MARKER (start1);
2982 begp1 = XINT (start1);
2984 if (NILP (end1))
2985 endp1 = BUF_ZV (bp1);
2986 else
2988 CHECK_NUMBER_COERCE_MARKER (end1);
2989 endp1 = XINT (end1);
2992 if (begp1 > endp1)
2993 temp = begp1, begp1 = endp1, endp1 = temp;
2995 if (!(BUF_BEGV (bp1) <= begp1
2996 && begp1 <= endp1
2997 && endp1 <= BUF_ZV (bp1)))
2998 args_out_of_range (start1, end1);
3000 /* Likewise for second substring. */
3002 if (NILP (buffer2))
3003 bp2 = current_buffer;
3004 else
3006 Lisp_Object buf2;
3007 buf2 = Fget_buffer (buffer2);
3008 if (NILP (buf2))
3009 nsberror (buffer2);
3010 bp2 = XBUFFER (buf2);
3011 if (!BUFFER_LIVE_P (bp2))
3012 error ("Selecting deleted buffer");
3015 if (NILP (start2))
3016 begp2 = BUF_BEGV (bp2);
3017 else
3019 CHECK_NUMBER_COERCE_MARKER (start2);
3020 begp2 = XINT (start2);
3022 if (NILP (end2))
3023 endp2 = BUF_ZV (bp2);
3024 else
3026 CHECK_NUMBER_COERCE_MARKER (end2);
3027 endp2 = XINT (end2);
3030 if (begp2 > endp2)
3031 temp = begp2, begp2 = endp2, endp2 = temp;
3033 if (!(BUF_BEGV (bp2) <= begp2
3034 && begp2 <= endp2
3035 && endp2 <= BUF_ZV (bp2)))
3036 args_out_of_range (start2, end2);
3038 i1 = begp1;
3039 i2 = begp2;
3040 i1_byte = buf_charpos_to_bytepos (bp1, i1);
3041 i2_byte = buf_charpos_to_bytepos (bp2, i2);
3043 while (i1 < endp1 && i2 < endp2)
3045 /* When we find a mismatch, we must compare the
3046 characters, not just the bytes. */
3047 int c1, c2;
3049 QUIT;
3051 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
3053 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
3054 BUF_INC_POS (bp1, i1_byte);
3055 i1++;
3057 else
3059 c1 = BUF_FETCH_BYTE (bp1, i1);
3060 MAKE_CHAR_MULTIBYTE (c1);
3061 i1++;
3064 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
3066 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
3067 BUF_INC_POS (bp2, i2_byte);
3068 i2++;
3070 else
3072 c2 = BUF_FETCH_BYTE (bp2, i2);
3073 MAKE_CHAR_MULTIBYTE (c2);
3074 i2++;
3077 if (!NILP (trt))
3079 c1 = char_table_translate (trt, c1);
3080 c2 = char_table_translate (trt, c2);
3082 if (c1 < c2)
3083 return make_number (- 1 - chars);
3084 if (c1 > c2)
3085 return make_number (chars + 1);
3087 chars++;
3090 /* The strings match as far as they go.
3091 If one is shorter, that one is less. */
3092 if (chars < endp1 - begp1)
3093 return make_number (chars + 1);
3094 else if (chars < endp2 - begp2)
3095 return make_number (- chars - 1);
3097 /* Same length too => they are equal. */
3098 return make_number (0);
3101 static void
3102 subst_char_in_region_unwind (Lisp_Object arg)
3104 bset_undo_list (current_buffer, arg);
3107 static void
3108 subst_char_in_region_unwind_1 (Lisp_Object arg)
3110 bset_filename (current_buffer, arg);
3113 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
3114 Ssubst_char_in_region, 4, 5, 0,
3115 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3116 If optional arg NOUNDO is non-nil, don't record this change for undo
3117 and don't mark the buffer as really changed.
3118 Both characters must have the same length of multi-byte form. */)
3119 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
3121 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
3122 /* Keep track of the first change in the buffer:
3123 if 0 we haven't found it yet.
3124 if < 0 we've found it and we've run the before-change-function.
3125 if > 0 we've actually performed it and the value is its position. */
3126 ptrdiff_t changed = 0;
3127 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
3128 unsigned char *p;
3129 ptrdiff_t count = SPECPDL_INDEX ();
3130 #define COMBINING_NO 0
3131 #define COMBINING_BEFORE 1
3132 #define COMBINING_AFTER 2
3133 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3134 int maybe_byte_combining = COMBINING_NO;
3135 ptrdiff_t last_changed = 0;
3136 bool multibyte_p
3137 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3138 int fromc, toc;
3140 restart:
3142 validate_region (&start, &end);
3143 CHECK_CHARACTER (fromchar);
3144 CHECK_CHARACTER (tochar);
3145 fromc = XFASTINT (fromchar);
3146 toc = XFASTINT (tochar);
3148 if (multibyte_p)
3150 len = CHAR_STRING (fromc, fromstr);
3151 if (CHAR_STRING (toc, tostr) != len)
3152 error ("Characters in `subst-char-in-region' have different byte-lengths");
3153 if (!ASCII_CHAR_P (*tostr))
3155 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3156 complete multibyte character, it may be combined with the
3157 after bytes. If it is in the range 0xA0..0xFF, it may be
3158 combined with the before and after bytes. */
3159 if (!CHAR_HEAD_P (*tostr))
3160 maybe_byte_combining = COMBINING_BOTH;
3161 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3162 maybe_byte_combining = COMBINING_AFTER;
3165 else
3167 len = 1;
3168 fromstr[0] = fromc;
3169 tostr[0] = toc;
3172 pos = XINT (start);
3173 pos_byte = CHAR_TO_BYTE (pos);
3174 stop = CHAR_TO_BYTE (XINT (end));
3175 end_byte = stop;
3177 /* If we don't want undo, turn off putting stuff on the list.
3178 That's faster than getting rid of things,
3179 and it prevents even the entry for a first change.
3180 Also inhibit locking the file. */
3181 if (!changed && !NILP (noundo))
3183 record_unwind_protect (subst_char_in_region_unwind,
3184 BVAR (current_buffer, undo_list));
3185 bset_undo_list (current_buffer, Qt);
3186 /* Don't do file-locking. */
3187 record_unwind_protect (subst_char_in_region_unwind_1,
3188 BVAR (current_buffer, filename));
3189 bset_filename (current_buffer, Qnil);
3192 if (pos_byte < GPT_BYTE)
3193 stop = min (stop, GPT_BYTE);
3194 while (1)
3196 ptrdiff_t pos_byte_next = pos_byte;
3198 if (pos_byte >= stop)
3200 if (pos_byte >= end_byte) break;
3201 stop = end_byte;
3203 p = BYTE_POS_ADDR (pos_byte);
3204 if (multibyte_p)
3205 INC_POS (pos_byte_next);
3206 else
3207 ++pos_byte_next;
3208 if (pos_byte_next - pos_byte == len
3209 && p[0] == fromstr[0]
3210 && (len == 1
3211 || (p[1] == fromstr[1]
3212 && (len == 2 || (p[2] == fromstr[2]
3213 && (len == 3 || p[3] == fromstr[3]))))))
3215 if (changed < 0)
3216 /* We've already seen this and run the before-change-function;
3217 this time we only need to record the actual position. */
3218 changed = pos;
3219 else if (!changed)
3221 changed = -1;
3222 modify_text (pos, XINT (end));
3224 if (! NILP (noundo))
3226 if (MODIFF - 1 == SAVE_MODIFF)
3227 SAVE_MODIFF++;
3228 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3229 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3232 /* The before-change-function may have moved the gap
3233 or even modified the buffer so we should start over. */
3234 goto restart;
3237 /* Take care of the case where the new character
3238 combines with neighboring bytes. */
3239 if (maybe_byte_combining
3240 && (maybe_byte_combining == COMBINING_AFTER
3241 ? (pos_byte_next < Z_BYTE
3242 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3243 : ((pos_byte_next < Z_BYTE
3244 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3245 || (pos_byte > BEG_BYTE
3246 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3248 Lisp_Object tem, string;
3250 tem = BVAR (current_buffer, undo_list);
3252 /* Make a multibyte string containing this single character. */
3253 string = make_multibyte_string ((char *) tostr, 1, len);
3254 /* replace_range is less efficient, because it moves the gap,
3255 but it handles combining correctly. */
3256 replace_range (pos, pos + 1, string,
3257 0, 0, 1, 0);
3258 pos_byte_next = CHAR_TO_BYTE (pos);
3259 if (pos_byte_next > pos_byte)
3260 /* Before combining happened. We should not increment
3261 POS. So, to cancel the later increment of POS,
3262 decrease it now. */
3263 pos--;
3264 else
3265 INC_POS (pos_byte_next);
3267 if (! NILP (noundo))
3268 bset_undo_list (current_buffer, tem);
3270 else
3272 if (NILP (noundo))
3273 record_change (pos, 1);
3274 for (i = 0; i < len; i++) *p++ = tostr[i];
3276 last_changed = pos + 1;
3278 pos_byte = pos_byte_next;
3279 pos++;
3282 if (changed > 0)
3284 signal_after_change (changed,
3285 last_changed - changed, last_changed - changed);
3286 update_compositions (changed, last_changed, CHECK_ALL);
3289 unbind_to (count, Qnil);
3290 return Qnil;
3294 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3295 Lisp_Object);
3297 /* Helper function for Ftranslate_region_internal.
3299 Check if a character sequence at POS (POS_BYTE) matches an element
3300 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3301 element is found, return it. Otherwise return Qnil. */
3303 static Lisp_Object
3304 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3305 Lisp_Object val)
3307 int initial_buf[16];
3308 int *buf = initial_buf;
3309 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3310 int *bufalloc = 0;
3311 ptrdiff_t buf_used = 0;
3312 Lisp_Object result = Qnil;
3314 for (; CONSP (val); val = XCDR (val))
3316 Lisp_Object elt;
3317 ptrdiff_t len, i;
3319 elt = XCAR (val);
3320 if (! CONSP (elt))
3321 continue;
3322 elt = XCAR (elt);
3323 if (! VECTORP (elt))
3324 continue;
3325 len = ASIZE (elt);
3326 if (len <= end - pos)
3328 for (i = 0; i < len; i++)
3330 if (buf_used <= i)
3332 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3333 int len1;
3335 if (buf_used == buf_size)
3337 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3338 sizeof *bufalloc);
3339 if (buf == initial_buf)
3340 memcpy (bufalloc, buf, sizeof initial_buf);
3341 buf = bufalloc;
3343 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3344 pos_byte += len1;
3346 if (XINT (AREF (elt, i)) != buf[i])
3347 break;
3349 if (i == len)
3351 result = XCAR (val);
3352 break;
3357 xfree (bufalloc);
3358 return result;
3362 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3363 Stranslate_region_internal, 3, 3, 0,
3364 doc: /* Internal use only.
3365 From START to END, translate characters according to TABLE.
3366 TABLE is a string or a char-table; the Nth character in it is the
3367 mapping for the character with code N.
3368 It returns the number of characters changed. */)
3369 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3371 register unsigned char *tt; /* Trans table. */
3372 register int nc; /* New character. */
3373 int cnt; /* Number of changes made. */
3374 ptrdiff_t size; /* Size of translate table. */
3375 ptrdiff_t pos, pos_byte, end_pos;
3376 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3377 bool string_multibyte UNINIT;
3379 validate_region (&start, &end);
3380 if (CHAR_TABLE_P (table))
3382 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3383 error ("Not a translation table");
3384 size = MAX_CHAR;
3385 tt = NULL;
3387 else
3389 CHECK_STRING (table);
3391 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3392 table = string_make_unibyte (table);
3393 string_multibyte = SCHARS (table) < SBYTES (table);
3394 size = SBYTES (table);
3395 tt = SDATA (table);
3398 pos = XINT (start);
3399 pos_byte = CHAR_TO_BYTE (pos);
3400 end_pos = XINT (end);
3401 modify_text (pos, end_pos);
3403 cnt = 0;
3404 for (; pos < end_pos; )
3406 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3407 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3408 int len, str_len;
3409 int oc;
3410 Lisp_Object val;
3412 if (multibyte)
3413 oc = STRING_CHAR_AND_LENGTH (p, len);
3414 else
3415 oc = *p, len = 1;
3416 if (oc < size)
3418 if (tt)
3420 /* Reload as signal_after_change in last iteration may GC. */
3421 tt = SDATA (table);
3422 if (string_multibyte)
3424 str = tt + string_char_to_byte (table, oc);
3425 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3427 else
3429 nc = tt[oc];
3430 if (! ASCII_CHAR_P (nc) && multibyte)
3432 str_len = BYTE8_STRING (nc, buf);
3433 str = buf;
3435 else
3437 str_len = 1;
3438 str = tt + oc;
3442 else
3444 nc = oc;
3445 val = CHAR_TABLE_REF (table, oc);
3446 if (CHARACTERP (val))
3448 nc = XFASTINT (val);
3449 str_len = CHAR_STRING (nc, buf);
3450 str = buf;
3452 else if (VECTORP (val) || (CONSP (val)))
3454 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3455 where TO is TO-CHAR or [TO-CHAR ...]. */
3456 nc = -1;
3460 if (nc != oc && nc >= 0)
3462 /* Simple one char to one char translation. */
3463 if (len != str_len)
3465 Lisp_Object string;
3467 /* This is less efficient, because it moves the gap,
3468 but it should handle multibyte characters correctly. */
3469 string = make_multibyte_string ((char *) str, 1, str_len);
3470 replace_range (pos, pos + 1, string, 1, 0, 1, 0);
3471 len = str_len;
3473 else
3475 record_change (pos, 1);
3476 while (str_len-- > 0)
3477 *p++ = *str++;
3478 signal_after_change (pos, 1, 1);
3479 update_compositions (pos, pos + 1, CHECK_BORDER);
3481 ++cnt;
3483 else if (nc < 0)
3485 Lisp_Object string;
3487 if (CONSP (val))
3489 val = check_translation (pos, pos_byte, end_pos, val);
3490 if (NILP (val))
3492 pos_byte += len;
3493 pos++;
3494 continue;
3496 /* VAL is ([FROM-CHAR ...] . TO). */
3497 len = ASIZE (XCAR (val));
3498 val = XCDR (val);
3500 else
3501 len = 1;
3503 if (VECTORP (val))
3505 string = Fconcat (1, &val);
3507 else
3509 string = Fmake_string (make_number (1), val);
3511 replace_range (pos, pos + len, string, 1, 0, 1, 0);
3512 pos_byte += SBYTES (string);
3513 pos += SCHARS (string);
3514 cnt += SCHARS (string);
3515 end_pos += SCHARS (string) - len;
3516 continue;
3519 pos_byte += len;
3520 pos++;
3523 return make_number (cnt);
3526 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3527 doc: /* Delete the text between START and END.
3528 If called interactively, delete the region between point and mark.
3529 This command deletes buffer text without modifying the kill ring. */)
3530 (Lisp_Object start, Lisp_Object end)
3532 validate_region (&start, &end);
3533 del_range (XINT (start), XINT (end));
3534 return Qnil;
3537 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3538 Sdelete_and_extract_region, 2, 2, 0,
3539 doc: /* Delete the text between START and END and return it. */)
3540 (Lisp_Object start, Lisp_Object end)
3542 validate_region (&start, &end);
3543 if (XINT (start) == XINT (end))
3544 return empty_unibyte_string;
3545 return del_range_1 (XINT (start), XINT (end), 1, 1);
3548 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3549 doc: /* Remove restrictions (narrowing) from current buffer.
3550 This allows the buffer's full text to be seen and edited. */)
3551 (void)
3553 if (BEG != BEGV || Z != ZV)
3554 current_buffer->clip_changed = 1;
3555 BEGV = BEG;
3556 BEGV_BYTE = BEG_BYTE;
3557 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3558 /* Changing the buffer bounds invalidates any recorded current column. */
3559 invalidate_current_column ();
3560 return Qnil;
3563 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3564 doc: /* Restrict editing in this buffer to the current region.
3565 The rest of the text becomes temporarily invisible and untouchable
3566 but is not deleted; if you save the buffer in a file, the invisible
3567 text is included in the file. \\[widen] makes all visible again.
3568 See also `save-restriction'.
3570 When calling from a program, pass two arguments; positions (integers
3571 or markers) bounding the text that should remain visible. */)
3572 (register Lisp_Object start, Lisp_Object end)
3574 CHECK_NUMBER_COERCE_MARKER (start);
3575 CHECK_NUMBER_COERCE_MARKER (end);
3577 if (XINT (start) > XINT (end))
3579 Lisp_Object tem;
3580 tem = start; start = end; end = tem;
3583 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3584 args_out_of_range (start, end);
3586 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3587 current_buffer->clip_changed = 1;
3589 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3590 SET_BUF_ZV (current_buffer, XFASTINT (end));
3591 if (PT < XFASTINT (start))
3592 SET_PT (XFASTINT (start));
3593 if (PT > XFASTINT (end))
3594 SET_PT (XFASTINT (end));
3595 /* Changing the buffer bounds invalidates any recorded current column. */
3596 invalidate_current_column ();
3597 return Qnil;
3600 Lisp_Object
3601 save_restriction_save (void)
3603 if (BEGV == BEG && ZV == Z)
3604 /* The common case that the buffer isn't narrowed.
3605 We return just the buffer object, which save_restriction_restore
3606 recognizes as meaning `no restriction'. */
3607 return Fcurrent_buffer ();
3608 else
3609 /* We have to save a restriction, so return a pair of markers, one
3610 for the beginning and one for the end. */
3612 Lisp_Object beg, end;
3614 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3615 end = build_marker (current_buffer, ZV, ZV_BYTE);
3617 /* END must move forward if text is inserted at its exact location. */
3618 XMARKER (end)->insertion_type = 1;
3620 return Fcons (beg, end);
3624 void
3625 save_restriction_restore (Lisp_Object data)
3627 struct buffer *cur = NULL;
3628 struct buffer *buf = (CONSP (data)
3629 ? XMARKER (XCAR (data))->buffer
3630 : XBUFFER (data));
3632 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3633 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3634 is the case if it is or has an indirect buffer), then make
3635 sure it is current before we update BEGV, so
3636 set_buffer_internal takes care of managing those markers. */
3637 cur = current_buffer;
3638 set_buffer_internal (buf);
3641 if (CONSP (data))
3642 /* A pair of marks bounding a saved restriction. */
3644 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3645 struct Lisp_Marker *end = XMARKER (XCDR (data));
3646 eassert (buf == end->buffer);
3648 if (buf /* Verify marker still points to a buffer. */
3649 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3650 /* The restriction has changed from the saved one, so restore
3651 the saved restriction. */
3653 ptrdiff_t pt = BUF_PT (buf);
3655 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3656 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3658 if (pt < beg->charpos || pt > end->charpos)
3659 /* The point is outside the new visible range, move it inside. */
3660 SET_BUF_PT_BOTH (buf,
3661 clip_to_bounds (beg->charpos, pt, end->charpos),
3662 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3663 end->bytepos));
3665 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3667 /* These aren't needed anymore, so don't wait for GC. */
3668 free_marker (XCAR (data));
3669 free_marker (XCDR (data));
3670 free_cons (XCONS (data));
3672 else
3673 /* A buffer, which means that there was no old restriction. */
3675 if (buf /* Verify marker still points to a buffer. */
3676 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3677 /* The buffer has been narrowed, get rid of the narrowing. */
3679 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3680 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3682 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3686 /* Changing the buffer bounds invalidates any recorded current column. */
3687 invalidate_current_column ();
3689 if (cur)
3690 set_buffer_internal (cur);
3693 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3694 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3695 The buffer's restrictions make parts of the beginning and end invisible.
3696 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3697 This special form, `save-restriction', saves the current buffer's restrictions
3698 when it is entered, and restores them when it is exited.
3699 So any `narrow-to-region' within BODY lasts only until the end of the form.
3700 The old restrictions settings are restored
3701 even in case of abnormal exit (throw or error).
3703 The value returned is the value of the last form in BODY.
3705 Note: if you are using both `save-excursion' and `save-restriction',
3706 use `save-excursion' outermost:
3707 (save-excursion (save-restriction ...))
3709 usage: (save-restriction &rest BODY) */)
3710 (Lisp_Object body)
3712 register Lisp_Object val;
3713 ptrdiff_t count = SPECPDL_INDEX ();
3715 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3716 val = Fprogn (body);
3717 return unbind_to (count, val);
3720 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3721 doc: /* Display a message at the bottom of the screen.
3722 The message also goes into the `*Messages*' buffer, if `message-log-max'
3723 is non-nil. (In keyboard macros, that's all it does.)
3724 Return the message.
3726 In batch mode, the message is printed to the standard error stream,
3727 followed by a newline.
3729 The first argument is a format control string, and the rest are data
3730 to be formatted under control of the string. See `format-message' for
3731 details.
3733 Note: (message "%s" VALUE) displays the string VALUE without
3734 interpreting format characters like `%', `\\=`', and `\\=''.
3736 If the first argument is nil or the empty string, the function clears
3737 any existing message; this lets the minibuffer contents show. See
3738 also `current-message'.
3740 usage: (message FORMAT-STRING &rest ARGS) */)
3741 (ptrdiff_t nargs, Lisp_Object *args)
3743 if (NILP (args[0])
3744 || (STRINGP (args[0])
3745 && SBYTES (args[0]) == 0))
3747 message1 (0);
3748 return args[0];
3750 else
3752 Lisp_Object val = Fformat_message (nargs, args);
3753 message3 (val);
3754 return val;
3758 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3759 doc: /* Display a message, in a dialog box if possible.
3760 If a dialog box is not available, use the echo area.
3761 The first argument is a format control string, and the rest are data
3762 to be formatted under control of the string. See `format-message' for
3763 details.
3765 If the first argument is nil or the empty string, clear any existing
3766 message; let the minibuffer contents show.
3768 usage: (message-box FORMAT-STRING &rest ARGS) */)
3769 (ptrdiff_t nargs, Lisp_Object *args)
3771 if (NILP (args[0]))
3773 message1 (0);
3774 return Qnil;
3776 else
3778 Lisp_Object val = Fformat_message (nargs, args);
3779 Lisp_Object pane, menu;
3781 pane = list1 (Fcons (build_string ("OK"), Qt));
3782 menu = Fcons (val, pane);
3783 Fx_popup_dialog (Qt, menu, Qt);
3784 return val;
3788 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3789 doc: /* Display a message in a dialog box or in the echo area.
3790 If this command was invoked with the mouse, use a dialog box if
3791 `use-dialog-box' is non-nil.
3792 Otherwise, use the echo area.
3793 The first argument is a format control string, and the rest are data
3794 to be formatted under control of the string. See `format-message' for
3795 details.
3797 If the first argument is nil or the empty string, clear any existing
3798 message; let the minibuffer contents show.
3800 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3801 (ptrdiff_t nargs, Lisp_Object *args)
3803 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3804 && use_dialog_box)
3805 return Fmessage_box (nargs, args);
3806 return Fmessage (nargs, args);
3809 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3810 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3811 (void)
3813 return current_message ();
3817 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3818 doc: /* Return a copy of STRING with text properties added.
3819 First argument is the string to copy.
3820 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3821 properties to add to the result.
3822 usage: (propertize STRING &rest PROPERTIES) */)
3823 (ptrdiff_t nargs, Lisp_Object *args)
3825 Lisp_Object properties, string;
3826 ptrdiff_t i;
3828 /* Number of args must be odd. */
3829 if ((nargs & 1) == 0)
3830 error ("Wrong number of arguments");
3832 properties = string = Qnil;
3834 /* First argument must be a string. */
3835 CHECK_STRING (args[0]);
3836 string = Fcopy_sequence (args[0]);
3838 for (i = 1; i < nargs; i += 2)
3839 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3841 Fadd_text_properties (make_number (0),
3842 make_number (SCHARS (string)),
3843 properties, string);
3844 return string;
3847 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3848 doc: /* Format a string out of a format-string and arguments.
3849 The first argument is a format control string.
3850 The other arguments are substituted into it to make the result, a string.
3852 The format control string may contain %-sequences meaning to substitute
3853 the next available argument:
3855 %s means print a string argument. Actually, prints any object, with `princ'.
3856 %d means print as number in decimal (%o octal, %x hex).
3857 %X is like %x, but uses upper case.
3858 %e means print a number in exponential notation.
3859 %f means print a number in decimal-point notation.
3860 %g means print a number in exponential notation
3861 or decimal-point notation, whichever uses fewer characters.
3862 %c means print a number as a single character.
3863 %S means print any object as an s-expression (using `prin1').
3865 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3866 Use %% to put a single % into the output.
3868 A %-sequence may contain optional flag, width, and precision
3869 specifiers, as follows:
3871 %<flags><width><precision>character
3873 where flags is [+ #-0]+, width is [0-9]+, and precision is a literal
3874 period "." followed by [0-9]+
3876 The + flag character inserts a + before any positive number, while a
3877 space inserts a space before any positive number; these flags only
3878 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3879 The - and 0 flags affect the width specifier, as described below.
3881 The # flag means to use an alternate display form for %o, %x, %X, %e,
3882 %f, and %g sequences: for %o, it ensures that the result begins with
3883 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3884 for %e, %f, and %g, it causes a decimal point to be included even if
3885 the precision is zero.
3887 The width specifier supplies a lower limit for the length of the
3888 printed representation. The padding, if any, normally goes on the
3889 left, but it goes on the right if the - flag is present. The padding
3890 character is normally a space, but it is 0 if the 0 flag is present.
3891 The 0 flag is ignored if the - flag is present, or the format sequence
3892 is something other than %d, %e, %f, and %g.
3894 For %e, %f, and %g sequences, the number after the "." in the
3895 precision specifier says how many decimal places to show; if zero, the
3896 decimal point itself is omitted. For %s and %S, the precision
3897 specifier truncates the string to the given width.
3899 Text properties, if any, are copied from the format-string to the
3900 produced text.
3902 usage: (format STRING &rest OBJECTS) */)
3903 (ptrdiff_t nargs, Lisp_Object *args)
3905 return styled_format (nargs, args, false);
3908 DEFUN ("format-message", Fformat_message, Sformat_message, 1, MANY, 0,
3909 doc: /* Format a string out of a format-string and arguments.
3910 The first argument is a format control string.
3911 The other arguments are substituted into it to make the result, a string.
3913 This acts like `format', except it also replaces each grave accent (\\=`)
3914 by a left quote, and each apostrophe (\\=') by a right quote. The left
3915 and right quote replacement characters are specified by
3916 `text-quoting-style'.
3918 usage: (format-message STRING &rest OBJECTS) */)
3919 (ptrdiff_t nargs, Lisp_Object *args)
3921 return styled_format (nargs, args, true);
3924 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise. */
3926 static Lisp_Object
3927 styled_format (ptrdiff_t nargs, Lisp_Object *args, bool message)
3929 ptrdiff_t n; /* The number of the next arg to substitute. */
3930 char initial_buffer[4000];
3931 char *buf = initial_buffer;
3932 ptrdiff_t bufsize = sizeof initial_buffer;
3933 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3934 char *p;
3935 ptrdiff_t buf_save_value_index UNINIT;
3936 char *format, *end;
3937 ptrdiff_t nchars;
3938 /* When we make a multibyte string, we must pay attention to the
3939 byte combining problem, i.e., a byte may be combined with a
3940 multibyte character of the previous string. This flag tells if we
3941 must consider such a situation or not. */
3942 bool maybe_combine_byte;
3943 bool arg_intervals = false;
3944 USE_SAFE_ALLOCA;
3946 /* Each element records, for one argument,
3947 the start and end bytepos in the output string,
3948 whether the argument has been converted to string (e.g., due to "%S"),
3949 and whether the argument is a string with intervals. */
3950 struct info
3952 ptrdiff_t start, end;
3953 bool_bf converted_to_string : 1;
3954 bool_bf intervals : 1;
3955 } *info;
3957 CHECK_STRING (args[0]);
3958 char *format_start = SSDATA (args[0]);
3959 ptrdiff_t formatlen = SBYTES (args[0]);
3961 /* Allocate the info and discarded tables. */
3962 ptrdiff_t alloca_size;
3963 if (INT_MULTIPLY_WRAPV (nargs, sizeof *info, &alloca_size)
3964 || INT_ADD_WRAPV (sizeof *info, alloca_size, &alloca_size)
3965 || INT_ADD_WRAPV (formatlen, alloca_size, &alloca_size)
3966 || SIZE_MAX < alloca_size)
3967 memory_full (SIZE_MAX);
3968 /* info[0] is unused. Unused elements have -1 for start. */
3969 info = SAFE_ALLOCA (alloca_size);
3970 memset (info, 0, alloca_size);
3971 for (ptrdiff_t i = 0; i < nargs + 1; i++)
3972 info[i].start = -1;
3973 /* discarded[I] is 1 if byte I of the format
3974 string was not copied into the output.
3975 It is 2 if byte I was not the first byte of its character. */
3976 char *discarded = (char *) &info[nargs + 1];
3978 /* Try to determine whether the result should be multibyte.
3979 This is not always right; sometimes the result needs to be multibyte
3980 because of an object that we will pass through prin1.
3981 or because a grave accent or apostrophe is requoted,
3982 and in that case, we won't know it here. */
3984 /* True if the format is multibyte. */
3985 bool multibyte_format = STRING_MULTIBYTE (args[0]);
3986 /* True if the output should be a multibyte string,
3987 which is true if any of the inputs is one. */
3988 bool multibyte = multibyte_format;
3989 for (ptrdiff_t i = 1; !multibyte && i < nargs; i++)
3990 if (STRINGP (args[i]) && STRING_MULTIBYTE (args[i]))
3991 multibyte = true;
3993 int quoting_style = message ? text_quoting_style () : -1;
3995 /* If we start out planning a unibyte result,
3996 then discover it has to be multibyte, we jump back to retry. */
3997 retry:
3999 p = buf;
4000 nchars = 0;
4001 n = 0;
4003 /* Scan the format and store result in BUF. */
4004 format = format_start;
4005 end = format + formatlen;
4006 maybe_combine_byte = false;
4008 while (format != end)
4010 /* The values of N and FORMAT when the loop body is entered. */
4011 ptrdiff_t n0 = n;
4012 char *format0 = format;
4013 char const *convsrc = format;
4014 unsigned char format_char = *format++;
4016 /* Bytes needed to represent the output of this conversion. */
4017 ptrdiff_t convbytes = 1;
4019 if (format_char == '%')
4021 /* General format specifications look like
4023 '%' [flags] [field-width] [precision] format
4025 where
4027 flags ::= [-+0# ]+
4028 field-width ::= [0-9]+
4029 precision ::= '.' [0-9]*
4031 If a field-width is specified, it specifies to which width
4032 the output should be padded with blanks, if the output
4033 string is shorter than field-width.
4035 If precision is specified, it specifies the number of
4036 digits to print after the '.' for floats, or the max.
4037 number of chars to print from a string. */
4039 bool minus_flag = false;
4040 bool plus_flag = false;
4041 bool space_flag = false;
4042 bool sharp_flag = false;
4043 bool zero_flag = false;
4045 for (; ; format++)
4047 switch (*format)
4049 case '-': minus_flag = true; continue;
4050 case '+': plus_flag = true; continue;
4051 case ' ': space_flag = true; continue;
4052 case '#': sharp_flag = true; continue;
4053 case '0': zero_flag = true; continue;
4055 break;
4058 /* Ignore flags when sprintf ignores them. */
4059 space_flag &= ~ plus_flag;
4060 zero_flag &= ~ minus_flag;
4062 char *num_end;
4063 uintmax_t raw_field_width = strtoumax (format, &num_end, 10);
4064 if (max_bufsize <= raw_field_width)
4065 string_overflow ();
4066 ptrdiff_t field_width = raw_field_width;
4068 bool precision_given = *num_end == '.';
4069 uintmax_t precision = (precision_given
4070 ? strtoumax (num_end + 1, &num_end, 10)
4071 : UINTMAX_MAX);
4072 format = num_end;
4074 if (format == end)
4075 error ("Format string ends in middle of format specifier");
4077 char conversion = *format++;
4078 memset (&discarded[format0 - format_start], 1,
4079 format - format0 - (conversion == '%'));
4080 if (conversion == '%')
4081 goto copy_char;
4083 ++n;
4084 if (! (n < nargs))
4085 error ("Not enough arguments for format string");
4087 /* For 'S', prin1 the argument, and then treat like 's'.
4088 For 's', princ any argument that is not a string or
4089 symbol. But don't do this conversion twice, which might
4090 happen after retrying. */
4091 if ((conversion == 'S'
4092 || (conversion == 's'
4093 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
4095 if (! info[n].converted_to_string)
4097 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
4098 args[n] = Fprin1_to_string (args[n], noescape);
4099 info[n].converted_to_string = true;
4100 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
4102 multibyte = true;
4103 goto retry;
4106 conversion = 's';
4108 else if (conversion == 'c')
4110 if (FLOATP (args[n]))
4112 double d = XFLOAT_DATA (args[n]);
4113 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
4116 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
4118 if (!multibyte)
4120 multibyte = true;
4121 goto retry;
4123 args[n] = Fchar_to_string (args[n]);
4124 info[n].converted_to_string = true;
4127 if (info[n].converted_to_string)
4128 conversion = 's';
4129 zero_flag = false;
4132 if (SYMBOLP (args[n]))
4134 args[n] = SYMBOL_NAME (args[n]);
4135 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
4137 multibyte = true;
4138 goto retry;
4142 if (conversion == 's')
4144 /* handle case (precision[n] >= 0) */
4146 ptrdiff_t prec = -1;
4147 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
4148 prec = precision;
4150 /* lisp_string_width ignores a precision of 0, but GNU
4151 libc functions print 0 characters when the precision
4152 is 0. Imitate libc behavior here. Changing
4153 lisp_string_width is the right thing, and will be
4154 done, but meanwhile we work with it. */
4156 ptrdiff_t width, nbytes;
4157 ptrdiff_t nchars_string;
4158 if (prec == 0)
4159 width = nchars_string = nbytes = 0;
4160 else
4162 ptrdiff_t nch, nby;
4163 width = lisp_string_width (args[n], prec, &nch, &nby);
4164 if (prec < 0)
4166 nchars_string = SCHARS (args[n]);
4167 nbytes = SBYTES (args[n]);
4169 else
4171 nchars_string = nch;
4172 nbytes = nby;
4176 convbytes = nbytes;
4177 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
4178 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
4180 ptrdiff_t padding
4181 = width < field_width ? field_width - width : 0;
4183 if (max_bufsize - padding <= convbytes)
4184 string_overflow ();
4185 convbytes += padding;
4186 if (convbytes <= buf + bufsize - p)
4188 if (! minus_flag)
4190 memset (p, ' ', padding);
4191 p += padding;
4192 nchars += padding;
4194 info[n].start = nchars;
4196 if (p > buf
4197 && multibyte
4198 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4199 && STRING_MULTIBYTE (args[n])
4200 && !CHAR_HEAD_P (SREF (args[n], 0)))
4201 maybe_combine_byte = true;
4203 p += copy_text (SDATA (args[n]), (unsigned char *) p,
4204 nbytes,
4205 STRING_MULTIBYTE (args[n]), multibyte);
4207 nchars += nchars_string;
4209 if (minus_flag)
4211 memset (p, ' ', padding);
4212 p += padding;
4213 nchars += padding;
4215 info[n].end = nchars;
4217 /* If this argument has text properties, record where
4218 in the result string it appears. */
4219 if (string_intervals (args[n]))
4220 info[n].intervals = arg_intervals = true;
4222 continue;
4225 else if (! (conversion == 'c' || conversion == 'd'
4226 || conversion == 'e' || conversion == 'f'
4227 || conversion == 'g' || conversion == 'i'
4228 || conversion == 'o' || conversion == 'x'
4229 || conversion == 'X'))
4230 error ("Invalid format operation %%%c",
4231 STRING_CHAR ((unsigned char *) format - 1));
4232 else if (! NUMBERP (args[n]))
4233 error ("Format specifier doesn't match argument type");
4234 else
4236 enum
4238 /* Maximum precision for a %f conversion such that the
4239 trailing output digit might be nonzero. Any precision
4240 larger than this will not yield useful information. */
4241 USEFUL_PRECISION_MAX =
4242 ((1 - DBL_MIN_EXP)
4243 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4244 : FLT_RADIX == 16 ? 4
4245 : -1)),
4247 /* Maximum number of bytes generated by any format, if
4248 precision is no more than USEFUL_PRECISION_MAX.
4249 On all practical hosts, %f is the worst case. */
4250 SPRINTF_BUFSIZE =
4251 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4253 /* Length of pM (that is, of pMd without the
4254 trailing "d"). */
4255 pMlen = sizeof pMd - 2
4257 verify (USEFUL_PRECISION_MAX > 0);
4259 /* Avoid undefined behavior in underlying sprintf. */
4260 if (conversion == 'd' || conversion == 'i')
4261 sharp_flag = false;
4263 /* Create the copy of the conversion specification, with
4264 any width and precision removed, with ".*" inserted,
4265 and with pM inserted for integer formats.
4266 At most three flags F can be specified at once. */
4267 char convspec[sizeof "%FFF.*d" + pMlen];
4269 char *f = convspec;
4270 *f++ = '%';
4271 *f = '-'; f += minus_flag;
4272 *f = '+'; f += plus_flag;
4273 *f = ' '; f += space_flag;
4274 *f = '#'; f += sharp_flag;
4275 *f = '0'; f += zero_flag;
4276 *f++ = '.';
4277 *f++ = '*';
4278 if (conversion == 'd' || conversion == 'i'
4279 || conversion == 'o' || conversion == 'x'
4280 || conversion == 'X')
4282 memcpy (f, pMd, pMlen);
4283 f += pMlen;
4284 zero_flag &= ~ precision_given;
4286 *f++ = conversion;
4287 *f = '\0';
4290 int prec = -1;
4291 if (precision_given)
4292 prec = min (precision, USEFUL_PRECISION_MAX);
4294 /* Use sprintf to format this number into sprintf_buf. Omit
4295 padding and excess precision, though, because sprintf limits
4296 output length to INT_MAX.
4298 There are four types of conversion: double, unsigned
4299 char (passed as int), wide signed int, and wide
4300 unsigned int. Treat them separately because the
4301 sprintf ABI is sensitive to which type is passed. Be
4302 careful about integer overflow, NaNs, infinities, and
4303 conversions; for example, the min and max macros are
4304 not suitable here. */
4305 char sprintf_buf[SPRINTF_BUFSIZE];
4306 ptrdiff_t sprintf_bytes;
4307 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
4309 double x = (INTEGERP (args[n])
4310 ? XINT (args[n])
4311 : XFLOAT_DATA (args[n]));
4312 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4314 else if (conversion == 'c')
4316 /* Don't use sprintf here, as it might mishandle prec. */
4317 sprintf_buf[0] = XINT (args[n]);
4318 sprintf_bytes = prec != 0;
4320 else if (conversion == 'd')
4322 /* For float, maybe we should use "%1.0f"
4323 instead so it also works for values outside
4324 the integer range. */
4325 printmax_t x;
4326 if (INTEGERP (args[n]))
4327 x = XINT (args[n]);
4328 else
4330 double d = XFLOAT_DATA (args[n]);
4331 if (d < 0)
4333 x = TYPE_MINIMUM (printmax_t);
4334 if (x < d)
4335 x = d;
4337 else
4339 x = TYPE_MAXIMUM (printmax_t);
4340 if (d < x)
4341 x = d;
4344 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4346 else
4348 /* Don't sign-extend for octal or hex printing. */
4349 uprintmax_t x;
4350 if (INTEGERP (args[n]))
4351 x = XUINT (args[n]);
4352 else
4354 double d = XFLOAT_DATA (args[n]);
4355 if (d < 0)
4356 x = 0;
4357 else
4359 x = TYPE_MAXIMUM (uprintmax_t);
4360 if (d < x)
4361 x = d;
4364 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4367 /* Now the length of the formatted item is known, except it omits
4368 padding and excess precision. Deal with excess precision
4369 first. This happens only when the format specifies
4370 ridiculously large precision. */
4371 uintmax_t excess_precision = precision - prec;
4372 uintmax_t leading_zeros = 0, trailing_zeros = 0;
4373 if (excess_precision)
4375 if (conversion == 'e' || conversion == 'f'
4376 || conversion == 'g')
4378 if ((conversion == 'g' && ! sharp_flag)
4379 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4380 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4381 excess_precision = 0;
4382 else
4384 if (conversion == 'g')
4386 char *dot = strchr (sprintf_buf, '.');
4387 if (!dot)
4388 excess_precision = 0;
4391 trailing_zeros = excess_precision;
4393 else
4394 leading_zeros = excess_precision;
4397 /* Compute the total bytes needed for this item, including
4398 excess precision and padding. */
4399 uintmax_t numwidth = sprintf_bytes + excess_precision;
4400 ptrdiff_t padding
4401 = numwidth < field_width ? field_width - numwidth : 0;
4402 if (max_bufsize - sprintf_bytes <= excess_precision
4403 || max_bufsize - padding <= numwidth)
4404 string_overflow ();
4405 convbytes = numwidth + padding;
4407 if (convbytes <= buf + bufsize - p)
4409 /* Copy the formatted item from sprintf_buf into buf,
4410 inserting padding and excess-precision zeros. */
4412 char *src = sprintf_buf;
4413 char src0 = src[0];
4414 int exponent_bytes = 0;
4415 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4416 if (zero_flag
4417 && ((src[signedp] >= '0' && src[signedp] <= '9')
4418 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4419 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4421 leading_zeros += padding;
4422 padding = 0;
4425 if (excess_precision
4426 && (conversion == 'e' || conversion == 'g'))
4428 char *e = strchr (src, 'e');
4429 if (e)
4430 exponent_bytes = src + sprintf_bytes - e;
4433 info[n].start = nchars;
4434 if (! minus_flag)
4436 memset (p, ' ', padding);
4437 p += padding;
4438 nchars += padding;
4441 *p = src0;
4442 src += signedp;
4443 p += signedp;
4444 memset (p, '0', leading_zeros);
4445 p += leading_zeros;
4446 int significand_bytes
4447 = sprintf_bytes - signedp - exponent_bytes;
4448 memcpy (p, src, significand_bytes);
4449 p += significand_bytes;
4450 src += significand_bytes;
4451 memset (p, '0', trailing_zeros);
4452 p += trailing_zeros;
4453 memcpy (p, src, exponent_bytes);
4454 p += exponent_bytes;
4456 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4458 if (minus_flag)
4460 memset (p, ' ', padding);
4461 p += padding;
4462 nchars += padding;
4464 info[n].end = nchars;
4466 continue;
4470 else
4472 unsigned char str[MAX_MULTIBYTE_LENGTH];
4474 if ((format_char == '`' || format_char == '\'')
4475 && quoting_style == CURVE_QUOTING_STYLE)
4477 if (! multibyte)
4479 multibyte = true;
4480 goto retry;
4482 convsrc = format_char == '`' ? uLSQM : uRSQM;
4483 convbytes = 3;
4485 else if (format_char == '`' && quoting_style == STRAIGHT_QUOTING_STYLE)
4486 convsrc = "'";
4487 else
4489 /* Copy a single character from format to buf. */
4490 if (multibyte_format)
4492 /* Copy a whole multibyte character. */
4493 if (p > buf
4494 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4495 && !CHAR_HEAD_P (format_char))
4496 maybe_combine_byte = true;
4498 while (! CHAR_HEAD_P (*format))
4499 format++;
4501 convbytes = format - format0;
4502 memset (&discarded[format0 + 1 - format_start], 2,
4503 convbytes - 1);
4505 else if (multibyte && !ASCII_CHAR_P (format_char))
4507 int c = BYTE8_TO_CHAR (format_char);
4508 convbytes = CHAR_STRING (c, str);
4509 convsrc = (char *) str;
4513 copy_char:
4514 if (convbytes <= buf + bufsize - p)
4516 memcpy (p, convsrc, convbytes);
4517 p += convbytes;
4518 nchars++;
4519 continue;
4523 /* There wasn't enough room to store this conversion or single
4524 character. CONVBYTES says how much room is needed. Allocate
4525 enough room (and then some) and do it again. */
4527 ptrdiff_t used = p - buf;
4528 if (max_bufsize - used < convbytes)
4529 string_overflow ();
4530 bufsize = used + convbytes;
4531 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4533 if (buf == initial_buffer)
4535 buf = xmalloc (bufsize);
4536 sa_must_free = true;
4537 buf_save_value_index = SPECPDL_INDEX ();
4538 record_unwind_protect_ptr (xfree, buf);
4539 memcpy (buf, initial_buffer, used);
4541 else
4543 buf = xrealloc (buf, bufsize);
4544 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4547 p = buf + used;
4548 format = format0;
4549 n = n0;
4552 if (bufsize < p - buf)
4553 emacs_abort ();
4555 if (maybe_combine_byte)
4556 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4557 Lisp_Object val = make_specified_string (buf, nchars, p - buf, multibyte);
4559 /* If the format string has text properties, or any of the string
4560 arguments has text properties, set up text properties of the
4561 result string. */
4563 if (string_intervals (args[0]) || arg_intervals)
4565 /* Add text properties from the format string. */
4566 Lisp_Object len = make_number (SCHARS (args[0]));
4567 Lisp_Object props = text_property_list (args[0], make_number (0),
4568 len, Qnil);
4569 if (CONSP (props))
4571 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4572 ptrdiff_t argn = 1;
4574 /* Adjust the bounds of each text property
4575 to the proper start and end in the output string. */
4577 /* Put the positions in PROPS in increasing order, so that
4578 we can do (effectively) one scan through the position
4579 space of the format string. */
4580 props = Fnreverse (props);
4582 /* BYTEPOS is the byte position in the format string,
4583 POSITION is the untranslated char position in it,
4584 TRANSLATED is the translated char position in BUF,
4585 and ARGN is the number of the next arg we will come to. */
4586 for (Lisp_Object list = props; CONSP (list); list = XCDR (list))
4588 Lisp_Object item = XCAR (list);
4590 /* First adjust the property start position. */
4591 ptrdiff_t pos = XINT (XCAR (item));
4593 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4594 up to this position. */
4595 for (; position < pos; bytepos++)
4597 if (! discarded[bytepos])
4598 position++, translated++;
4599 else if (discarded[bytepos] == 1)
4601 position++;
4602 if (translated == info[argn].start)
4604 translated += info[argn].end - info[argn].start;
4605 argn++;
4610 XSETCAR (item, make_number (translated));
4612 /* Likewise adjust the property end position. */
4613 pos = XINT (XCAR (XCDR (item)));
4615 for (; position < pos; bytepos++)
4617 if (! discarded[bytepos])
4618 position++, translated++;
4619 else if (discarded[bytepos] == 1)
4621 position++;
4622 if (translated == info[argn].start)
4624 translated += info[argn].end - info[argn].start;
4625 argn++;
4630 XSETCAR (XCDR (item), make_number (translated));
4633 add_text_properties_from_list (val, props, make_number (0));
4636 /* Add text properties from arguments. */
4637 if (arg_intervals)
4638 for (ptrdiff_t i = 1; i < nargs; i++)
4639 if (info[i].intervals)
4641 len = make_number (SCHARS (args[i]));
4642 Lisp_Object new_len = make_number (info[i].end - info[i].start);
4643 props = text_property_list (args[i], make_number (0), len, Qnil);
4644 props = extend_property_ranges (props, len, new_len);
4645 /* If successive arguments have properties, be sure that
4646 the value of `composition' property be the copy. */
4647 if (1 < i && info[i - 1].end)
4648 make_composition_value_copy (props);
4649 add_text_properties_from_list (val, props,
4650 make_number (info[i].start));
4654 /* If we allocated BUF or INFO with malloc, free it too. */
4655 SAFE_FREE ();
4657 return val;
4660 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4661 doc: /* Return t if two characters match, optionally ignoring case.
4662 Both arguments must be characters (i.e. integers).
4663 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4664 (register Lisp_Object c1, Lisp_Object c2)
4666 int i1, i2;
4667 /* Check they're chars, not just integers, otherwise we could get array
4668 bounds violations in downcase. */
4669 CHECK_CHARACTER (c1);
4670 CHECK_CHARACTER (c2);
4672 if (XINT (c1) == XINT (c2))
4673 return Qt;
4674 if (NILP (BVAR (current_buffer, case_fold_search)))
4675 return Qnil;
4677 i1 = XFASTINT (c1);
4678 i2 = XFASTINT (c2);
4680 /* FIXME: It is possible to compare multibyte characters even when
4681 the current buffer is unibyte. Unfortunately this is ambiguous
4682 for characters between 128 and 255, as they could be either
4683 eight-bit raw bytes or Latin-1 characters. Assume the former for
4684 now. See Bug#17011, and also see casefiddle.c's casify_object,
4685 which has a similar problem. */
4686 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4688 if (SINGLE_BYTE_CHAR_P (i1))
4689 i1 = UNIBYTE_TO_CHAR (i1);
4690 if (SINGLE_BYTE_CHAR_P (i2))
4691 i2 = UNIBYTE_TO_CHAR (i2);
4694 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4697 /* Transpose the markers in two regions of the current buffer, and
4698 adjust the ones between them if necessary (i.e.: if the regions
4699 differ in size).
4701 START1, END1 are the character positions of the first region.
4702 START1_BYTE, END1_BYTE are the byte positions.
4703 START2, END2 are the character positions of the second region.
4704 START2_BYTE, END2_BYTE are the byte positions.
4706 Traverses the entire marker list of the buffer to do so, adding an
4707 appropriate amount to some, subtracting from some, and leaving the
4708 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4710 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4712 static void
4713 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4714 ptrdiff_t start2, ptrdiff_t end2,
4715 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4716 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4718 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4719 register struct Lisp_Marker *marker;
4721 /* Update point as if it were a marker. */
4722 if (PT < start1)
4724 else if (PT < end1)
4725 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4726 PT_BYTE + (end2_byte - end1_byte));
4727 else if (PT < start2)
4728 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4729 (PT_BYTE + (end2_byte - start2_byte)
4730 - (end1_byte - start1_byte)));
4731 else if (PT < end2)
4732 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4733 PT_BYTE - (start2_byte - start1_byte));
4735 /* We used to adjust the endpoints here to account for the gap, but that
4736 isn't good enough. Even if we assume the caller has tried to move the
4737 gap out of our way, it might still be at start1 exactly, for example;
4738 and that places it `inside' the interval, for our purposes. The amount
4739 of adjustment is nontrivial if there's a `denormalized' marker whose
4740 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4741 the dirty work to Fmarker_position, below. */
4743 /* The difference between the region's lengths */
4744 diff = (end2 - start2) - (end1 - start1);
4745 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4747 /* For shifting each marker in a region by the length of the other
4748 region plus the distance between the regions. */
4749 amt1 = (end2 - start2) + (start2 - end1);
4750 amt2 = (end1 - start1) + (start2 - end1);
4751 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4752 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4754 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4756 mpos = marker->bytepos;
4757 if (mpos >= start1_byte && mpos < end2_byte)
4759 if (mpos < end1_byte)
4760 mpos += amt1_byte;
4761 else if (mpos < start2_byte)
4762 mpos += diff_byte;
4763 else
4764 mpos -= amt2_byte;
4765 marker->bytepos = mpos;
4767 mpos = marker->charpos;
4768 if (mpos >= start1 && mpos < end2)
4770 if (mpos < end1)
4771 mpos += amt1;
4772 else if (mpos < start2)
4773 mpos += diff;
4774 else
4775 mpos -= amt2;
4777 marker->charpos = mpos;
4781 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4782 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4783 The regions should not be overlapping, because the size of the buffer is
4784 never changed in a transposition.
4786 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4787 any markers that happen to be located in the regions.
4789 Transposing beyond buffer boundaries is an error. */)
4790 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4792 register ptrdiff_t start1, end1, start2, end2;
4793 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4794 ptrdiff_t gap, len1, len_mid, len2;
4795 unsigned char *start1_addr, *start2_addr, *temp;
4797 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4798 Lisp_Object buf;
4800 XSETBUFFER (buf, current_buffer);
4801 cur_intv = buffer_intervals (current_buffer);
4803 validate_region (&startr1, &endr1);
4804 validate_region (&startr2, &endr2);
4806 start1 = XFASTINT (startr1);
4807 end1 = XFASTINT (endr1);
4808 start2 = XFASTINT (startr2);
4809 end2 = XFASTINT (endr2);
4810 gap = GPT;
4812 /* Swap the regions if they're reversed. */
4813 if (start2 < end1)
4815 register ptrdiff_t glumph = start1;
4816 start1 = start2;
4817 start2 = glumph;
4818 glumph = end1;
4819 end1 = end2;
4820 end2 = glumph;
4823 len1 = end1 - start1;
4824 len2 = end2 - start2;
4826 if (start2 < end1)
4827 error ("Transposed regions overlap");
4828 /* Nothing to change for adjacent regions with one being empty */
4829 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4830 return Qnil;
4832 /* The possibilities are:
4833 1. Adjacent (contiguous) regions, or separate but equal regions
4834 (no, really equal, in this case!), or
4835 2. Separate regions of unequal size.
4837 The worst case is usually No. 2. It means that (aside from
4838 potential need for getting the gap out of the way), there also
4839 needs to be a shifting of the text between the two regions. So
4840 if they are spread far apart, we are that much slower... sigh. */
4842 /* It must be pointed out that the really studly thing to do would
4843 be not to move the gap at all, but to leave it in place and work
4844 around it if necessary. This would be extremely efficient,
4845 especially considering that people are likely to do
4846 transpositions near where they are working interactively, which
4847 is exactly where the gap would be found. However, such code
4848 would be much harder to write and to read. So, if you are
4849 reading this comment and are feeling squirrely, by all means have
4850 a go! I just didn't feel like doing it, so I will simply move
4851 the gap the minimum distance to get it out of the way, and then
4852 deal with an unbroken array. */
4854 start1_byte = CHAR_TO_BYTE (start1);
4855 end2_byte = CHAR_TO_BYTE (end2);
4857 /* Make sure the gap won't interfere, by moving it out of the text
4858 we will operate on. */
4859 if (start1 < gap && gap < end2)
4861 if (gap - start1 < end2 - gap)
4862 move_gap_both (start1, start1_byte);
4863 else
4864 move_gap_both (end2, end2_byte);
4867 start2_byte = CHAR_TO_BYTE (start2);
4868 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4869 len2_byte = end2_byte - start2_byte;
4871 #ifdef BYTE_COMBINING_DEBUG
4872 if (end1 == start2)
4874 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4875 len2_byte, start1, start1_byte)
4876 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4877 len1_byte, end2, start2_byte + len2_byte)
4878 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4879 len1_byte, end2, start2_byte + len2_byte))
4880 emacs_abort ();
4882 else
4884 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4885 len2_byte, start1, start1_byte)
4886 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4887 len1_byte, start2, start2_byte)
4888 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4889 len2_byte, end1, start1_byte + len1_byte)
4890 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4891 len1_byte, end2, start2_byte + len2_byte))
4892 emacs_abort ();
4894 #endif
4896 /* Hmmm... how about checking to see if the gap is large
4897 enough to use as the temporary storage? That would avoid an
4898 allocation... interesting. Later, don't fool with it now. */
4900 /* Working without memmove, for portability (sigh), so must be
4901 careful of overlapping subsections of the array... */
4903 if (end1 == start2) /* adjacent regions */
4905 modify_text (start1, end2);
4906 record_change (start1, len1 + len2);
4908 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4909 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4910 /* Don't use Fset_text_properties: that can cause GC, which can
4911 clobber objects stored in the tmp_intervals. */
4912 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4913 if (tmp_interval3)
4914 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4916 USE_SAFE_ALLOCA;
4918 /* First region smaller than second. */
4919 if (len1_byte < len2_byte)
4921 temp = SAFE_ALLOCA (len2_byte);
4923 /* Don't precompute these addresses. We have to compute them
4924 at the last minute, because the relocating allocator might
4925 have moved the buffer around during the xmalloc. */
4926 start1_addr = BYTE_POS_ADDR (start1_byte);
4927 start2_addr = BYTE_POS_ADDR (start2_byte);
4929 memcpy (temp, start2_addr, len2_byte);
4930 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4931 memcpy (start1_addr, temp, len2_byte);
4933 else
4934 /* First region not smaller than second. */
4936 temp = SAFE_ALLOCA (len1_byte);
4937 start1_addr = BYTE_POS_ADDR (start1_byte);
4938 start2_addr = BYTE_POS_ADDR (start2_byte);
4939 memcpy (temp, start1_addr, len1_byte);
4940 memcpy (start1_addr, start2_addr, len2_byte);
4941 memcpy (start1_addr + len2_byte, temp, len1_byte);
4944 SAFE_FREE ();
4945 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4946 len1, current_buffer, 0);
4947 graft_intervals_into_buffer (tmp_interval2, start1,
4948 len2, current_buffer, 0);
4949 update_compositions (start1, start1 + len2, CHECK_BORDER);
4950 update_compositions (start1 + len2, end2, CHECK_TAIL);
4952 /* Non-adjacent regions, because end1 != start2, bleagh... */
4953 else
4955 len_mid = start2_byte - (start1_byte + len1_byte);
4957 if (len1_byte == len2_byte)
4958 /* Regions are same size, though, how nice. */
4960 USE_SAFE_ALLOCA;
4962 modify_text (start1, end1);
4963 modify_text (start2, end2);
4964 record_change (start1, len1);
4965 record_change (start2, len2);
4966 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4967 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4969 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4970 if (tmp_interval3)
4971 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4973 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4974 if (tmp_interval3)
4975 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4977 temp = SAFE_ALLOCA (len1_byte);
4978 start1_addr = BYTE_POS_ADDR (start1_byte);
4979 start2_addr = BYTE_POS_ADDR (start2_byte);
4980 memcpy (temp, start1_addr, len1_byte);
4981 memcpy (start1_addr, start2_addr, len2_byte);
4982 memcpy (start2_addr, temp, len1_byte);
4983 SAFE_FREE ();
4985 graft_intervals_into_buffer (tmp_interval1, start2,
4986 len1, current_buffer, 0);
4987 graft_intervals_into_buffer (tmp_interval2, start1,
4988 len2, current_buffer, 0);
4991 else if (len1_byte < len2_byte) /* Second region larger than first */
4992 /* Non-adjacent & unequal size, area between must also be shifted. */
4994 USE_SAFE_ALLOCA;
4996 modify_text (start1, end2);
4997 record_change (start1, (end2 - start1));
4998 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4999 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
5000 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
5002 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
5003 if (tmp_interval3)
5004 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
5006 /* holds region 2 */
5007 temp = SAFE_ALLOCA (len2_byte);
5008 start1_addr = BYTE_POS_ADDR (start1_byte);
5009 start2_addr = BYTE_POS_ADDR (start2_byte);
5010 memcpy (temp, start2_addr, len2_byte);
5011 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
5012 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5013 memcpy (start1_addr, temp, len2_byte);
5014 SAFE_FREE ();
5016 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
5017 len1, current_buffer, 0);
5018 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
5019 len_mid, current_buffer, 0);
5020 graft_intervals_into_buffer (tmp_interval2, start1,
5021 len2, current_buffer, 0);
5023 else
5024 /* Second region smaller than first. */
5026 USE_SAFE_ALLOCA;
5028 record_change (start1, (end2 - start1));
5029 modify_text (start1, end2);
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 1 */
5040 temp = SAFE_ALLOCA (len1_byte);
5041 start1_addr = BYTE_POS_ADDR (start1_byte);
5042 start2_addr = BYTE_POS_ADDR (start2_byte);
5043 memcpy (temp, start1_addr, len1_byte);
5044 memcpy (start1_addr, start2_addr, len2_byte);
5045 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
5046 memcpy (start1_addr + len2_byte + len_mid, temp, len1_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);
5057 update_compositions (start1, start1 + len2, CHECK_BORDER);
5058 update_compositions (end2 - len1, end2, CHECK_BORDER);
5061 /* When doing multiple transpositions, it might be nice
5062 to optimize this. Perhaps the markers in any one buffer
5063 should be organized in some sorted data tree. */
5064 if (NILP (leave_markers))
5066 transpose_markers (start1, end1, start2, end2,
5067 start1_byte, start1_byte + len1_byte,
5068 start2_byte, start2_byte + len2_byte);
5069 fix_start_end_in_overlays (start1, end2);
5071 else
5073 /* The character positions of the markers remain intact, but we
5074 still need to update their byte positions, because the
5075 transposed regions might include multibyte sequences which
5076 make some original byte positions of the markers invalid. */
5077 adjust_markers_bytepos (start1, start1_byte, end2, end2_byte, 0);
5080 signal_after_change (start1, end2 - start1, end2 - start1);
5081 return Qnil;
5085 void
5086 syms_of_editfns (void)
5088 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
5089 DEFSYM (Qwall, "wall");
5091 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
5092 doc: /* Non-nil means text motion commands don't notice fields. */);
5093 Vinhibit_field_text_motion = Qnil;
5095 DEFVAR_LISP ("buffer-access-fontify-functions",
5096 Vbuffer_access_fontify_functions,
5097 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
5098 Each function is called with two arguments which specify the range
5099 of the buffer being accessed. */);
5100 Vbuffer_access_fontify_functions = Qnil;
5103 Lisp_Object obuf;
5104 obuf = Fcurrent_buffer ();
5105 /* Do this here, because init_buffer_once is too early--it won't work. */
5106 Fset_buffer (Vprin1_to_string_buffer);
5107 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5108 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions), Qnil);
5109 Fset_buffer (obuf);
5112 DEFVAR_LISP ("buffer-access-fontified-property",
5113 Vbuffer_access_fontified_property,
5114 doc: /* Property which (if non-nil) indicates text has been fontified.
5115 `buffer-substring' need not call the `buffer-access-fontify-functions'
5116 functions if all the text being accessed has this property. */);
5117 Vbuffer_access_fontified_property = Qnil;
5119 DEFVAR_LISP ("system-name", Vsystem_name,
5120 doc: /* The host name of the machine Emacs is running on. */);
5121 Vsystem_name = cached_system_name = Qnil;
5123 DEFVAR_LISP ("user-full-name", Vuser_full_name,
5124 doc: /* The full name of the user logged in. */);
5126 DEFVAR_LISP ("user-login-name", Vuser_login_name,
5127 doc: /* The user's name, taken from environment variables if possible. */);
5128 Vuser_login_name = Qnil;
5130 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
5131 doc: /* The user's name, based upon the real uid only. */);
5133 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
5134 doc: /* The release of the operating system Emacs is running on. */);
5136 defsubr (&Spropertize);
5137 defsubr (&Schar_equal);
5138 defsubr (&Sgoto_char);
5139 defsubr (&Sstring_to_char);
5140 defsubr (&Schar_to_string);
5141 defsubr (&Sbyte_to_string);
5142 defsubr (&Sbuffer_substring);
5143 defsubr (&Sbuffer_substring_no_properties);
5144 defsubr (&Sbuffer_string);
5145 defsubr (&Sget_pos_property);
5147 defsubr (&Spoint_marker);
5148 defsubr (&Smark_marker);
5149 defsubr (&Spoint);
5150 defsubr (&Sregion_beginning);
5151 defsubr (&Sregion_end);
5153 /* Symbol for the text property used to mark fields. */
5154 DEFSYM (Qfield, "field");
5156 /* A special value for Qfield properties. */
5157 DEFSYM (Qboundary, "boundary");
5159 defsubr (&Sfield_beginning);
5160 defsubr (&Sfield_end);
5161 defsubr (&Sfield_string);
5162 defsubr (&Sfield_string_no_properties);
5163 defsubr (&Sdelete_field);
5164 defsubr (&Sconstrain_to_field);
5166 defsubr (&Sline_beginning_position);
5167 defsubr (&Sline_end_position);
5169 defsubr (&Ssave_excursion);
5170 defsubr (&Ssave_current_buffer);
5172 defsubr (&Sbuffer_size);
5173 defsubr (&Spoint_max);
5174 defsubr (&Spoint_min);
5175 defsubr (&Spoint_min_marker);
5176 defsubr (&Spoint_max_marker);
5177 defsubr (&Sgap_position);
5178 defsubr (&Sgap_size);
5179 defsubr (&Sposition_bytes);
5180 defsubr (&Sbyte_to_position);
5182 defsubr (&Sbobp);
5183 defsubr (&Seobp);
5184 defsubr (&Sbolp);
5185 defsubr (&Seolp);
5186 defsubr (&Sfollowing_char);
5187 defsubr (&Sprevious_char);
5188 defsubr (&Schar_after);
5189 defsubr (&Schar_before);
5190 defsubr (&Sinsert);
5191 defsubr (&Sinsert_before_markers);
5192 defsubr (&Sinsert_and_inherit);
5193 defsubr (&Sinsert_and_inherit_before_markers);
5194 defsubr (&Sinsert_char);
5195 defsubr (&Sinsert_byte);
5197 defsubr (&Suser_login_name);
5198 defsubr (&Suser_real_login_name);
5199 defsubr (&Suser_uid);
5200 defsubr (&Suser_real_uid);
5201 defsubr (&Sgroup_gid);
5202 defsubr (&Sgroup_real_gid);
5203 defsubr (&Suser_full_name);
5204 defsubr (&Semacs_pid);
5205 defsubr (&Scurrent_time);
5206 defsubr (&Stime_add);
5207 defsubr (&Stime_subtract);
5208 defsubr (&Stime_less_p);
5209 defsubr (&Sget_internal_run_time);
5210 defsubr (&Sformat_time_string);
5211 defsubr (&Sfloat_time);
5212 defsubr (&Sdecode_time);
5213 defsubr (&Sencode_time);
5214 defsubr (&Scurrent_time_string);
5215 defsubr (&Scurrent_time_zone);
5216 defsubr (&Sset_time_zone_rule);
5217 defsubr (&Ssystem_name);
5218 defsubr (&Smessage);
5219 defsubr (&Smessage_box);
5220 defsubr (&Smessage_or_box);
5221 defsubr (&Scurrent_message);
5222 defsubr (&Sformat);
5223 defsubr (&Sformat_message);
5225 defsubr (&Sinsert_buffer_substring);
5226 defsubr (&Scompare_buffer_substrings);
5227 defsubr (&Ssubst_char_in_region);
5228 defsubr (&Stranslate_region_internal);
5229 defsubr (&Sdelete_region);
5230 defsubr (&Sdelete_and_extract_region);
5231 defsubr (&Swiden);
5232 defsubr (&Snarrow_to_region);
5233 defsubr (&Ssave_restriction);
5234 defsubr (&Stranspose_regions);