* configure.ac: Move the OSX 10.6 test.
[emacs.git] / src / editfns.c
blob376d8e3a0eae779e84a12143bea43468dcac5bb0
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2014 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
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 <float.h>
48 #include <limits.h>
49 #include <intprops.h>
50 #include <strftime.h>
51 #include <verify.h>
53 #include "intervals.h"
54 #include "character.h"
55 #include "buffer.h"
56 #include "coding.h"
57 #include "frame.h"
58 #include "window.h"
59 #include "blockinput.h"
61 #define TM_YEAR_BASE 1900
63 #ifdef WINDOWSNT
64 extern Lisp_Object w32_get_internal_run_time (void);
65 #endif
67 static void set_time_zone_rule (char const *);
68 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
69 bool, struct tm *);
70 static long int tm_gmtoff (struct tm *);
71 static int tm_diff (struct tm *, struct tm *);
72 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
74 #ifndef HAVE_TM_GMTOFF
75 # define HAVE_TM_GMTOFF false
76 #endif
78 static Lisp_Object Qbuffer_access_fontify_functions;
80 /* Symbol for the text property used to mark fields. */
82 Lisp_Object Qfield;
84 /* A special value for Qfield properties. */
86 static Lisp_Object Qboundary;
88 /* The startup value of the TZ environment variable; null if unset. */
89 static char const *initial_tz;
91 /* A valid but unlikely setting for the TZ environment variable.
92 It is OK (though a bit slower) if the user chooses this value. */
93 static char dump_tz_string[] = "TZ=UtC0";
95 void
96 init_editfns (void)
98 const char *user_name;
99 register char *p;
100 struct passwd *pw; /* password entry for the current user */
101 Lisp_Object tem;
103 /* Set up system_name even when dumping. */
104 init_system_name ();
106 #ifndef CANNOT_DUMP
107 /* When just dumping out, set the time zone to a known unlikely value
108 and skip the rest of this function. */
109 if (!initialized)
111 # ifdef HAVE_TZSET
112 xputenv (dump_tz_string);
113 tzset ();
114 # endif
115 return;
117 #endif
119 char *tz = getenv ("TZ");
120 initial_tz = tz;
122 #if !defined CANNOT_DUMP && defined HAVE_TZSET
123 /* If the execution TZ happens to be the same as the dump TZ,
124 change it to some other value and then change it back,
125 to force the underlying implementation to reload the TZ info.
126 This is needed on implementations that load TZ info from files,
127 since the TZ file contents may differ between dump and execution. */
128 if (tz && strcmp (tz, &dump_tz_string[sizeof "TZ=" - 1]) == 0)
130 ++*tz;
131 tzset ();
132 --*tz;
134 #endif
136 /* Call set_time_zone_rule now, so that its call to putenv is done
137 before multiple threads are active. */
138 set_time_zone_rule (tz);
140 pw = getpwuid (getuid ());
141 #ifdef MSDOS
142 /* We let the real user name default to "root" because that's quite
143 accurate on MS-DOS and because it lets Emacs find the init file.
144 (The DVX libraries override the Djgpp libraries here.) */
145 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
146 #else
147 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
148 #endif
150 /* Get the effective user name, by consulting environment variables,
151 or the effective uid if those are unset. */
152 user_name = getenv ("LOGNAME");
153 if (!user_name)
154 #ifdef WINDOWSNT
155 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
156 #else /* WINDOWSNT */
157 user_name = getenv ("USER");
158 #endif /* WINDOWSNT */
159 if (!user_name)
161 pw = getpwuid (geteuid ());
162 user_name = pw ? pw->pw_name : "unknown";
164 Vuser_login_name = build_string (user_name);
166 /* If the user name claimed in the environment vars differs from
167 the real uid, use the claimed name to find the full name. */
168 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
169 if (! NILP (tem))
170 tem = Vuser_login_name;
171 else
173 uid_t euid = geteuid ();
174 tem = make_fixnum_or_float (euid);
176 Vuser_full_name = Fuser_full_name (tem);
178 p = getenv ("NAME");
179 if (p)
180 Vuser_full_name = build_string (p);
181 else if (NILP (Vuser_full_name))
182 Vuser_full_name = build_string ("unknown");
184 #ifdef HAVE_SYS_UTSNAME_H
186 struct utsname uts;
187 uname (&uts);
188 Voperating_system_release = build_string (uts.release);
190 #else
191 Voperating_system_release = Qnil;
192 #endif
195 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
196 doc: /* Convert arg CHAR to a string containing that character.
197 usage: (char-to-string CHAR) */)
198 (Lisp_Object character)
200 int c, len;
201 unsigned char str[MAX_MULTIBYTE_LENGTH];
203 CHECK_CHARACTER (character);
204 c = XFASTINT (character);
206 len = CHAR_STRING (c, str);
207 return make_string_from_bytes ((char *) str, 1, len);
210 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
211 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
212 (Lisp_Object byte)
214 unsigned char b;
215 CHECK_NUMBER (byte);
216 if (XINT (byte) < 0 || XINT (byte) > 255)
217 error ("Invalid byte");
218 b = XINT (byte);
219 return make_string_from_bytes ((char *) &b, 1, 1);
222 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
223 doc: /* Return the first character in STRING. */)
224 (register Lisp_Object string)
226 register Lisp_Object val;
227 CHECK_STRING (string);
228 if (SCHARS (string))
230 if (STRING_MULTIBYTE (string))
231 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
232 else
233 XSETFASTINT (val, SREF (string, 0));
235 else
236 XSETFASTINT (val, 0);
237 return val;
240 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
241 doc: /* Return value of point, as an integer.
242 Beginning of buffer is position (point-min). */)
243 (void)
245 Lisp_Object temp;
246 XSETFASTINT (temp, PT);
247 return temp;
250 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
251 doc: /* Return value of point, as a marker object. */)
252 (void)
254 return build_marker (current_buffer, PT, PT_BYTE);
257 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
258 doc: /* Set point to POSITION, a number or marker.
259 Beginning of buffer is position (point-min), end is (point-max).
261 The return value is POSITION. */)
262 (register Lisp_Object position)
264 if (MARKERP (position))
265 set_point_from_marker (position);
266 else if (INTEGERP (position))
267 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
268 else
269 wrong_type_argument (Qinteger_or_marker_p, position);
270 return position;
274 /* Return the start or end position of the region.
275 BEGINNINGP means return the start.
276 If there is no region active, signal an error. */
278 static Lisp_Object
279 region_limit (bool beginningp)
281 Lisp_Object m;
283 if (!NILP (Vtransient_mark_mode)
284 && NILP (Vmark_even_if_inactive)
285 && NILP (BVAR (current_buffer, mark_active)))
286 xsignal0 (Qmark_inactive);
288 m = Fmarker_position (BVAR (current_buffer, mark));
289 if (NILP (m))
290 error ("The mark is not set now, so there is no region");
292 /* Clip to the current narrowing (bug#11770). */
293 return make_number ((PT < XFASTINT (m)) == beginningp
294 ? PT
295 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
298 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
299 doc: /* Return the integer value of point or mark, whichever is smaller. */)
300 (void)
302 return region_limit (1);
305 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
306 doc: /* Return the integer value of point or mark, whichever is larger. */)
307 (void)
309 return region_limit (0);
312 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
313 doc: /* Return this buffer's mark, as a marker object.
314 Watch out! Moving this marker changes the mark position.
315 If you set the marker not to point anywhere, the buffer will have no mark. */)
316 (void)
318 return BVAR (current_buffer, mark);
322 /* Find all the overlays in the current buffer that touch position POS.
323 Return the number found, and store them in a vector in VEC
324 of length LEN. */
326 static ptrdiff_t
327 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
329 Lisp_Object overlay, start, end;
330 struct Lisp_Overlay *tail;
331 ptrdiff_t startpos, endpos;
332 ptrdiff_t idx = 0;
334 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
336 XSETMISC (overlay, tail);
338 end = OVERLAY_END (overlay);
339 endpos = OVERLAY_POSITION (end);
340 if (endpos < pos)
341 break;
342 start = OVERLAY_START (overlay);
343 startpos = OVERLAY_POSITION (start);
344 if (startpos <= pos)
346 if (idx < len)
347 vec[idx] = overlay;
348 /* Keep counting overlays even if we can't return them all. */
349 idx++;
353 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
355 XSETMISC (overlay, tail);
357 start = OVERLAY_START (overlay);
358 startpos = OVERLAY_POSITION (start);
359 if (pos < startpos)
360 break;
361 end = OVERLAY_END (overlay);
362 endpos = OVERLAY_POSITION (end);
363 if (pos <= endpos)
365 if (idx < len)
366 vec[idx] = overlay;
367 idx++;
371 return idx;
374 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
375 doc: /* Return the value of POSITION's property PROP, in OBJECT.
376 Almost identical to `get-char-property' except for the following difference:
377 Whereas `get-char-property' returns the property of the char at (i.e. right
378 after) POSITION, this pays attention to properties's stickiness and overlays's
379 advancement settings, in order to find the property of POSITION itself,
380 i.e. the property that a char would inherit if it were inserted
381 at POSITION. */)
382 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
384 CHECK_NUMBER_COERCE_MARKER (position);
386 if (NILP (object))
387 XSETBUFFER (object, current_buffer);
388 else if (WINDOWP (object))
389 object = XWINDOW (object)->contents;
391 if (!BUFFERP (object))
392 /* pos-property only makes sense in buffers right now, since strings
393 have no overlays and no notion of insertion for which stickiness
394 could be obeyed. */
395 return Fget_text_property (position, prop, object);
396 else
398 EMACS_INT posn = XINT (position);
399 ptrdiff_t noverlays;
400 Lisp_Object *overlay_vec, tem;
401 struct buffer *obuf = current_buffer;
402 USE_SAFE_ALLOCA;
404 set_buffer_temp (XBUFFER (object));
406 /* First try with room for 40 overlays. */
407 Lisp_Object overlay_vecbuf[40];
408 noverlays = ARRAYELTS (overlay_vecbuf);
409 overlay_vec = overlay_vecbuf;
410 noverlays = overlays_around (posn, overlay_vec, noverlays);
412 /* If there are more than 40,
413 make enough space for all, and try again. */
414 if (ARRAYELTS (overlay_vecbuf) < noverlays)
416 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
417 noverlays = overlays_around (posn, overlay_vec, noverlays);
419 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
421 set_buffer_temp (obuf);
423 /* Now check the overlays in order of decreasing priority. */
424 while (--noverlays >= 0)
426 Lisp_Object ol = overlay_vec[noverlays];
427 tem = Foverlay_get (ol, prop);
428 if (!NILP (tem))
430 /* Check the overlay is indeed active at point. */
431 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
432 if ((OVERLAY_POSITION (start) == posn
433 && XMARKER (start)->insertion_type == 1)
434 || (OVERLAY_POSITION (finish) == posn
435 && XMARKER (finish)->insertion_type == 0))
436 ; /* The overlay will not cover a char inserted at point. */
437 else
439 SAFE_FREE ();
440 return tem;
444 SAFE_FREE ();
446 { /* Now check the text properties. */
447 int stickiness = text_property_stickiness (prop, position, object);
448 if (stickiness > 0)
449 return Fget_text_property (position, prop, object);
450 else if (stickiness < 0
451 && XINT (position) > BUF_BEGV (XBUFFER (object)))
452 return Fget_text_property (make_number (XINT (position) - 1),
453 prop, object);
454 else
455 return Qnil;
460 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
461 the value of point is used instead. If BEG or END is null,
462 means don't store the beginning or end of the field.
464 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
465 results; they do not effect boundary behavior.
467 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
468 position of a field, then the beginning of the previous field is
469 returned instead of the beginning of POS's field (since the end of a
470 field is actually also the beginning of the next input field, this
471 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
472 non-nil case, if two fields are separated by a field with the special
473 value `boundary', and POS lies within it, then the two separated
474 fields are considered to be adjacent, and POS between them, when
475 finding the beginning and ending of the "merged" field.
477 Either BEG or END may be 0, in which case the corresponding value
478 is not stored. */
480 static void
481 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
482 Lisp_Object beg_limit,
483 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
485 /* Fields right before and after the point. */
486 Lisp_Object before_field, after_field;
487 /* True if POS counts as the start of a field. */
488 bool at_field_start = 0;
489 /* True if POS counts as the end of a field. */
490 bool at_field_end = 0;
492 if (NILP (pos))
493 XSETFASTINT (pos, PT);
494 else
495 CHECK_NUMBER_COERCE_MARKER (pos);
497 after_field
498 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
499 before_field
500 = (XFASTINT (pos) > BEGV
501 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
502 Qfield, Qnil, NULL)
503 /* Using nil here would be a more obvious choice, but it would
504 fail when the buffer starts with a non-sticky field. */
505 : after_field);
507 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
508 and POS is at beginning of a field, which can also be interpreted
509 as the end of the previous field. Note that the case where if
510 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
511 more natural one; then we avoid treating the beginning of a field
512 specially. */
513 if (NILP (merge_at_boundary))
515 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
516 if (!EQ (field, after_field))
517 at_field_end = 1;
518 if (!EQ (field, before_field))
519 at_field_start = 1;
520 if (NILP (field) && at_field_start && at_field_end)
521 /* If an inserted char would have a nil field while the surrounding
522 text is non-nil, we're probably not looking at a
523 zero-length field, but instead at a non-nil field that's
524 not intended for editing (such as comint's prompts). */
525 at_field_end = at_field_start = 0;
528 /* Note about special `boundary' fields:
530 Consider the case where the point (`.') is between the fields `x' and `y':
532 xxxx.yyyy
534 In this situation, if merge_at_boundary is non-nil, consider the
535 `x' and `y' fields as forming one big merged field, and so the end
536 of the field is the end of `y'.
538 However, if `x' and `y' are separated by a special `boundary' field
539 (a field with a `field' char-property of 'boundary), then ignore
540 this special field when merging adjacent fields. Here's the same
541 situation, but with a `boundary' field between the `x' and `y' fields:
543 xxx.BBBByyyy
545 Here, if point is at the end of `x', the beginning of `y', or
546 anywhere in-between (within the `boundary' field), merge all
547 three fields and consider the beginning as being the beginning of
548 the `x' field, and the end as being the end of the `y' field. */
550 if (beg)
552 if (at_field_start)
553 /* POS is at the edge of a field, and we should consider it as
554 the beginning of the following field. */
555 *beg = XFASTINT (pos);
556 else
557 /* Find the previous field boundary. */
559 Lisp_Object p = pos;
560 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
561 /* Skip a `boundary' field. */
562 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
563 beg_limit);
565 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
566 beg_limit);
567 *beg = NILP (p) ? BEGV : XFASTINT (p);
571 if (end)
573 if (at_field_end)
574 /* POS is at the edge of a field, and we should consider it as
575 the end of the previous field. */
576 *end = XFASTINT (pos);
577 else
578 /* Find the next field boundary. */
580 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
581 /* Skip a `boundary' field. */
582 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
583 end_limit);
585 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
586 end_limit);
587 *end = NILP (pos) ? ZV : XFASTINT (pos);
593 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
594 doc: /* Delete the field surrounding POS.
595 A field is a region of text with the same `field' property.
596 If POS is nil, the value of point is used for POS. */)
597 (Lisp_Object pos)
599 ptrdiff_t beg, end;
600 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
601 if (beg != end)
602 del_range (beg, end);
603 return Qnil;
606 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
607 doc: /* Return the contents of the field surrounding POS as a string.
608 A field is a region of text with the same `field' property.
609 If POS is nil, the value of point is used for POS. */)
610 (Lisp_Object pos)
612 ptrdiff_t beg, end;
613 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
614 return make_buffer_string (beg, end, 1);
617 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
618 doc: /* Return the contents of the field around POS, without text properties.
619 A field is a region of text with the same `field' property.
620 If POS is nil, the value of point is used for POS. */)
621 (Lisp_Object pos)
623 ptrdiff_t beg, end;
624 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
625 return make_buffer_string (beg, end, 0);
628 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
629 doc: /* Return the beginning of the field surrounding POS.
630 A field is a region of text with the same `field' property.
631 If POS is nil, the value of point is used for POS.
632 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
633 field, then the beginning of the *previous* field is returned.
634 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
635 is before LIMIT, then LIMIT will be returned instead. */)
636 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
638 ptrdiff_t beg;
639 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
640 return make_number (beg);
643 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
644 doc: /* Return the end of the field surrounding POS.
645 A field is a region of text with the same `field' property.
646 If POS is nil, the value of point is used for POS.
647 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
648 then the end of the *following* field is returned.
649 If LIMIT is non-nil, it is a buffer position; if the end of the field
650 is after LIMIT, then LIMIT will be returned instead. */)
651 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
653 ptrdiff_t end;
654 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
655 return make_number (end);
658 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
659 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
660 A field is a region of text with the same `field' property.
662 If NEW-POS is nil, then use the current point instead, and move point
663 to the resulting constrained position, in addition to returning that
664 position.
666 If OLD-POS is at the boundary of two fields, then the allowable
667 positions for NEW-POS depends on the value of the optional argument
668 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
669 constrained to the field that has the same `field' char-property
670 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
671 is non-nil, NEW-POS is constrained to the union of the two adjacent
672 fields. Additionally, if two fields are separated by another field with
673 the special value `boundary', then any point within this special field is
674 also considered to be `on the boundary'.
676 If the optional argument ONLY-IN-LINE is non-nil and constraining
677 NEW-POS would move it to a different line, NEW-POS is returned
678 unconstrained. This is useful for commands that move by line, like
679 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
680 only in the case where they can still move to the right line.
682 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
683 a non-nil property of that name, then any field boundaries are ignored.
685 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
686 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
687 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
689 /* If non-zero, then the original point, before re-positioning. */
690 ptrdiff_t orig_point = 0;
691 bool fwd;
692 Lisp_Object prev_old, prev_new;
694 if (NILP (new_pos))
695 /* Use the current point, and afterwards, set it. */
697 orig_point = PT;
698 XSETFASTINT (new_pos, PT);
701 CHECK_NUMBER_COERCE_MARKER (new_pos);
702 CHECK_NUMBER_COERCE_MARKER (old_pos);
704 fwd = (XINT (new_pos) > XINT (old_pos));
706 prev_old = make_number (XINT (old_pos) - 1);
707 prev_new = make_number (XINT (new_pos) - 1);
709 if (NILP (Vinhibit_field_text_motion)
710 && !EQ (new_pos, old_pos)
711 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
712 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
713 /* To recognize field boundaries, we must also look at the
714 previous positions; we could use `Fget_pos_property'
715 instead, but in itself that would fail inside non-sticky
716 fields (like comint prompts). */
717 || (XFASTINT (new_pos) > BEGV
718 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
719 || (XFASTINT (old_pos) > BEGV
720 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
721 && (NILP (inhibit_capture_property)
722 /* Field boundaries are again a problem; but now we must
723 decide the case exactly, so we need to call
724 `get_pos_property' as well. */
725 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
726 && (XFASTINT (old_pos) <= BEGV
727 || NILP (Fget_char_property
728 (old_pos, inhibit_capture_property, Qnil))
729 || NILP (Fget_char_property
730 (prev_old, inhibit_capture_property, Qnil))))))
731 /* It is possible that NEW_POS is not within the same field as
732 OLD_POS; try to move NEW_POS so that it is. */
734 ptrdiff_t shortage;
735 Lisp_Object field_bound;
737 if (fwd)
738 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
739 else
740 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
742 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
743 other side of NEW_POS, which would mean that NEW_POS is
744 already acceptable, and it's not necessary to constrain it
745 to FIELD_BOUND. */
746 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
747 /* NEW_POS should be constrained, but only if either
748 ONLY_IN_LINE is nil (in which case any constraint is OK),
749 or NEW_POS and FIELD_BOUND are on the same line (in which
750 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
751 && (NILP (only_in_line)
752 /* This is the ONLY_IN_LINE case, check that NEW_POS and
753 FIELD_BOUND are on the same line by seeing whether
754 there's an intervening newline or not. */
755 || (find_newline (XFASTINT (new_pos), -1,
756 XFASTINT (field_bound), -1,
757 fwd ? -1 : 1, &shortage, NULL, 1),
758 shortage != 0)))
759 /* Constrain NEW_POS to FIELD_BOUND. */
760 new_pos = field_bound;
762 if (orig_point && XFASTINT (new_pos) != orig_point)
763 /* The NEW_POS argument was originally nil, so automatically set PT. */
764 SET_PT (XFASTINT (new_pos));
767 return new_pos;
771 DEFUN ("line-beginning-position",
772 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
773 doc: /* Return the character position of the first character on the current line.
774 With optional argument N, scan forward N - 1 lines first.
775 If the scan reaches the end of the buffer, return that position.
777 This function ignores text display directionality; it returns the
778 position of the first character in logical order, i.e. the smallest
779 character position on the line.
781 This function constrains the returned position to the current field
782 unless that position would be on a different line than the original,
783 unconstrained result. If N is nil or 1, and a front-sticky field
784 starts at point, the scan stops as soon as it starts. To ignore field
785 boundaries, bind `inhibit-field-text-motion' to t.
787 This function does not move point. */)
788 (Lisp_Object n)
790 ptrdiff_t charpos, bytepos;
792 if (NILP (n))
793 XSETFASTINT (n, 1);
794 else
795 CHECK_NUMBER (n);
797 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
799 /* Return END constrained to the current input field. */
800 return Fconstrain_to_field (make_number (charpos), make_number (PT),
801 XINT (n) != 1 ? Qt : Qnil,
802 Qt, Qnil);
805 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
806 doc: /* Return the character position of the last character on the current line.
807 With argument N not nil or 1, move forward N - 1 lines first.
808 If scan reaches end of buffer, return that position.
810 This function ignores text display directionality; it returns the
811 position of the last character in logical order, i.e. the largest
812 character position on the line.
814 This function constrains the returned position to the current field
815 unless that would be on a different line than the original,
816 unconstrained result. If N is nil or 1, and a rear-sticky field ends
817 at point, the scan stops as soon as it starts. To ignore field
818 boundaries bind `inhibit-field-text-motion' to t.
820 This function does not move point. */)
821 (Lisp_Object n)
823 ptrdiff_t clipped_n;
824 ptrdiff_t end_pos;
825 ptrdiff_t orig = PT;
827 if (NILP (n))
828 XSETFASTINT (n, 1);
829 else
830 CHECK_NUMBER (n);
832 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
833 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
834 NULL);
836 /* Return END_POS constrained to the current input field. */
837 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
838 Qnil, Qt, Qnil);
841 /* Save current buffer state for `save-excursion' special form.
842 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
843 offload some work from GC. */
845 Lisp_Object
846 save_excursion_save (void)
848 return make_save_obj_obj_obj_obj
849 (Fpoint_marker (),
850 /* Do not copy the mark if it points to nowhere. */
851 (XMARKER (BVAR (current_buffer, mark))->buffer
852 ? Fcopy_marker (BVAR (current_buffer, mark), Qnil)
853 : Qnil),
854 /* Selected window if current buffer is shown in it, nil otherwise. */
855 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
856 ? selected_window : Qnil),
857 BVAR (current_buffer, mark_active));
860 /* Restore saved buffer before leaving `save-excursion' special form. */
862 void
863 save_excursion_restore (Lisp_Object info)
865 Lisp_Object tem, tem1, omark, nmark;
866 struct gcpro gcpro1, gcpro2, gcpro3;
868 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
869 /* If we're unwinding to top level, saved buffer may be deleted. This
870 means that all of its markers are unchained and so tem is nil. */
871 if (NILP (tem))
872 goto out;
874 omark = nmark = Qnil;
875 GCPRO3 (info, omark, nmark);
877 Fset_buffer (tem);
879 /* Point marker. */
880 tem = XSAVE_OBJECT (info, 0);
881 Fgoto_char (tem);
882 unchain_marker (XMARKER (tem));
884 /* Mark marker. */
885 tem = XSAVE_OBJECT (info, 1);
886 omark = Fmarker_position (BVAR (current_buffer, mark));
887 if (NILP (tem))
888 unchain_marker (XMARKER (BVAR (current_buffer, mark)));
889 else
891 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
892 nmark = Fmarker_position (tem);
893 unchain_marker (XMARKER (tem));
896 /* Mark active. */
897 tem = XSAVE_OBJECT (info, 3);
898 tem1 = BVAR (current_buffer, mark_active);
899 bset_mark_active (current_buffer, tem);
901 /* If mark is active now, and either was not active
902 or was at a different place, run the activate hook. */
903 if (! NILP (tem))
905 if (! EQ (omark, nmark))
907 tem = intern ("activate-mark-hook");
908 Frun_hooks (1, &tem);
911 /* If mark has ceased to be active, run deactivate hook. */
912 else if (! NILP (tem1))
914 tem = intern ("deactivate-mark-hook");
915 Frun_hooks (1, &tem);
918 /* If buffer was visible in a window, and a different window was
919 selected, and the old selected window is still showing this
920 buffer, restore point in that window. */
921 tem = XSAVE_OBJECT (info, 2);
922 if (WINDOWP (tem)
923 && !EQ (tem, selected_window)
924 && (tem1 = XWINDOW (tem)->contents,
925 (/* Window is live... */
926 BUFFERP (tem1)
927 /* ...and it shows the current buffer. */
928 && XBUFFER (tem1) == current_buffer)))
929 Fset_window_point (tem, make_number (PT));
931 UNGCPRO;
933 out:
935 free_misc (info);
938 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
939 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
940 Executes BODY just like `progn'.
941 The values of point, mark and the current buffer are restored
942 even in case of abnormal exit (throw or error).
943 The state of activation of the mark is also restored.
945 This construct does not save `deactivate-mark', and therefore
946 functions that change the buffer will still cause deactivation
947 of the mark at the end of the command. To prevent that, bind
948 `deactivate-mark' with `let'.
950 If you only want to save the current buffer but not point nor mark,
951 then just use `save-current-buffer', or even `with-current-buffer'.
953 usage: (save-excursion &rest BODY) */)
954 (Lisp_Object args)
956 register Lisp_Object val;
957 ptrdiff_t count = SPECPDL_INDEX ();
959 record_unwind_protect (save_excursion_restore, save_excursion_save ());
961 val = Fprogn (args);
962 return unbind_to (count, val);
965 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
966 doc: /* Record which buffer is current; execute BODY; make that buffer current.
967 BODY is executed just like `progn'.
968 usage: (save-current-buffer &rest BODY) */)
969 (Lisp_Object args)
971 ptrdiff_t count = SPECPDL_INDEX ();
973 record_unwind_current_buffer ();
974 return unbind_to (count, Fprogn (args));
977 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
978 doc: /* Return the number of characters in the current buffer.
979 If BUFFER, return the number of characters in that buffer instead. */)
980 (Lisp_Object buffer)
982 if (NILP (buffer))
983 return make_number (Z - BEG);
984 else
986 CHECK_BUFFER (buffer);
987 return make_number (BUF_Z (XBUFFER (buffer))
988 - BUF_BEG (XBUFFER (buffer)));
992 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
993 doc: /* Return the minimum permissible value of point in the current buffer.
994 This is 1, unless narrowing (a buffer restriction) is in effect. */)
995 (void)
997 Lisp_Object temp;
998 XSETFASTINT (temp, BEGV);
999 return temp;
1002 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1003 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1004 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1005 (void)
1007 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1010 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1011 doc: /* Return the maximum permissible value of point in the current buffer.
1012 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1013 is in effect, in which case it is less. */)
1014 (void)
1016 Lisp_Object temp;
1017 XSETFASTINT (temp, ZV);
1018 return temp;
1021 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1022 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1023 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1024 is in effect, in which case it is less. */)
1025 (void)
1027 return build_marker (current_buffer, ZV, ZV_BYTE);
1030 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1031 doc: /* Return the position of the gap, in the current buffer.
1032 See also `gap-size'. */)
1033 (void)
1035 Lisp_Object temp;
1036 XSETFASTINT (temp, GPT);
1037 return temp;
1040 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1041 doc: /* Return the size of the current buffer's gap.
1042 See also `gap-position'. */)
1043 (void)
1045 Lisp_Object temp;
1046 XSETFASTINT (temp, GAP_SIZE);
1047 return temp;
1050 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1051 doc: /* Return the byte position for character position POSITION.
1052 If POSITION is out of range, the value is nil. */)
1053 (Lisp_Object position)
1055 CHECK_NUMBER_COERCE_MARKER (position);
1056 if (XINT (position) < BEG || XINT (position) > Z)
1057 return Qnil;
1058 return make_number (CHAR_TO_BYTE (XINT (position)));
1061 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1062 doc: /* Return the character position for byte position BYTEPOS.
1063 If BYTEPOS is out of range, the value is nil. */)
1064 (Lisp_Object bytepos)
1066 CHECK_NUMBER (bytepos);
1067 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1068 return Qnil;
1069 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1072 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1073 doc: /* Return the character following point, as a number.
1074 At the end of the buffer or accessible region, return 0. */)
1075 (void)
1077 Lisp_Object temp;
1078 if (PT >= ZV)
1079 XSETFASTINT (temp, 0);
1080 else
1081 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1082 return temp;
1085 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1086 doc: /* Return the character preceding point, as a number.
1087 At the beginning of the buffer or accessible region, return 0. */)
1088 (void)
1090 Lisp_Object temp;
1091 if (PT <= BEGV)
1092 XSETFASTINT (temp, 0);
1093 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1095 ptrdiff_t pos = PT_BYTE;
1096 DEC_POS (pos);
1097 XSETFASTINT (temp, FETCH_CHAR (pos));
1099 else
1100 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1101 return temp;
1104 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1105 doc: /* Return t if point is at the beginning of the buffer.
1106 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1107 (void)
1109 if (PT == BEGV)
1110 return Qt;
1111 return Qnil;
1114 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1115 doc: /* Return t if point is at the end of the buffer.
1116 If the buffer is narrowed, this means the end of the narrowed part. */)
1117 (void)
1119 if (PT == ZV)
1120 return Qt;
1121 return Qnil;
1124 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1125 doc: /* Return t if point is at the beginning of a line. */)
1126 (void)
1128 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1129 return Qt;
1130 return Qnil;
1133 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1134 doc: /* Return t if point is at the end of a line.
1135 `End of a line' includes point being at the end of the buffer. */)
1136 (void)
1138 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1139 return Qt;
1140 return Qnil;
1143 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1144 doc: /* Return character in current buffer at position POS.
1145 POS is an integer or a marker and defaults to point.
1146 If POS is out of range, the value is nil. */)
1147 (Lisp_Object pos)
1149 register ptrdiff_t pos_byte;
1151 if (NILP (pos))
1153 pos_byte = PT_BYTE;
1154 XSETFASTINT (pos, PT);
1157 if (MARKERP (pos))
1159 pos_byte = marker_byte_position (pos);
1160 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1161 return Qnil;
1163 else
1165 CHECK_NUMBER_COERCE_MARKER (pos);
1166 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1167 return Qnil;
1169 pos_byte = CHAR_TO_BYTE (XINT (pos));
1172 return make_number (FETCH_CHAR (pos_byte));
1175 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1176 doc: /* Return character in current buffer preceding position POS.
1177 POS is an integer or a marker and defaults to point.
1178 If POS is out of range, the value is nil. */)
1179 (Lisp_Object pos)
1181 register Lisp_Object val;
1182 register ptrdiff_t pos_byte;
1184 if (NILP (pos))
1186 pos_byte = PT_BYTE;
1187 XSETFASTINT (pos, PT);
1190 if (MARKERP (pos))
1192 pos_byte = marker_byte_position (pos);
1194 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1195 return Qnil;
1197 else
1199 CHECK_NUMBER_COERCE_MARKER (pos);
1201 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1202 return Qnil;
1204 pos_byte = CHAR_TO_BYTE (XINT (pos));
1207 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1209 DEC_POS (pos_byte);
1210 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1212 else
1214 pos_byte--;
1215 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1217 return val;
1220 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1221 doc: /* Return the name under which the user logged in, as a string.
1222 This is based on the effective uid, not the real uid.
1223 Also, if the environment variables LOGNAME or USER are set,
1224 that determines the value of this function.
1226 If optional argument UID is an integer or a float, return the login name
1227 of the user with that uid, or nil if there is no such user. */)
1228 (Lisp_Object uid)
1230 struct passwd *pw;
1231 uid_t id;
1233 /* Set up the user name info if we didn't do it before.
1234 (That can happen if Emacs is dumpable
1235 but you decide to run `temacs -l loadup' and not dump. */
1236 if (INTEGERP (Vuser_login_name))
1237 init_editfns ();
1239 if (NILP (uid))
1240 return Vuser_login_name;
1242 CONS_TO_INTEGER (uid, uid_t, id);
1243 block_input ();
1244 pw = getpwuid (id);
1245 unblock_input ();
1246 return (pw ? build_string (pw->pw_name) : Qnil);
1249 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1250 0, 0, 0,
1251 doc: /* Return the name of the user's real uid, as a string.
1252 This ignores the environment variables LOGNAME and USER, so it differs from
1253 `user-login-name' when running under `su'. */)
1254 (void)
1256 /* Set up the user name info if we didn't do it before.
1257 (That can happen if Emacs is dumpable
1258 but you decide to run `temacs -l loadup' and not dump. */
1259 if (INTEGERP (Vuser_login_name))
1260 init_editfns ();
1261 return Vuser_real_login_name;
1264 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1265 doc: /* Return the effective uid of Emacs.
1266 Value is an integer or a float, depending on the value. */)
1267 (void)
1269 uid_t euid = geteuid ();
1270 return make_fixnum_or_float (euid);
1273 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1274 doc: /* Return the real uid of Emacs.
1275 Value is an integer or a float, depending on the value. */)
1276 (void)
1278 uid_t uid = getuid ();
1279 return make_fixnum_or_float (uid);
1282 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1283 doc: /* Return the effective gid of Emacs.
1284 Value is an integer or a float, depending on the value. */)
1285 (void)
1287 gid_t egid = getegid ();
1288 return make_fixnum_or_float (egid);
1291 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1292 doc: /* Return the real gid of Emacs.
1293 Value is an integer or a float, depending on the value. */)
1294 (void)
1296 gid_t gid = getgid ();
1297 return make_fixnum_or_float (gid);
1300 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1301 doc: /* Return the full name of the user logged in, as a string.
1302 If the full name corresponding to Emacs's userid is not known,
1303 return "unknown".
1305 If optional argument UID is an integer or float, return the full name
1306 of the user with that uid, or nil if there is no such user.
1307 If UID is a string, return the full name of the user with that login
1308 name, or nil if there is no such user. */)
1309 (Lisp_Object uid)
1311 struct passwd *pw;
1312 register char *p, *q;
1313 Lisp_Object full;
1315 if (NILP (uid))
1316 return Vuser_full_name;
1317 else if (NUMBERP (uid))
1319 uid_t u;
1320 CONS_TO_INTEGER (uid, uid_t, u);
1321 block_input ();
1322 pw = getpwuid (u);
1323 unblock_input ();
1325 else if (STRINGP (uid))
1327 block_input ();
1328 pw = getpwnam (SSDATA (uid));
1329 unblock_input ();
1331 else
1332 error ("Invalid UID specification");
1334 if (!pw)
1335 return Qnil;
1337 p = USER_FULL_NAME;
1338 /* Chop off everything after the first comma. */
1339 q = strchr (p, ',');
1340 full = make_string (p, q ? q - p : strlen (p));
1342 #ifdef AMPERSAND_FULL_NAME
1343 p = SSDATA (full);
1344 q = strchr (p, '&');
1345 /* Substitute the login name for the &, upcasing the first character. */
1346 if (q)
1348 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1349 USE_SAFE_ALLOCA;
1350 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1351 memcpy (r, p, q - p);
1352 r[q - p] = 0;
1353 strcat (r, SSDATA (login));
1354 r[q - p] = upcase ((unsigned char) r[q - p]);
1355 strcat (r, q + 1);
1356 full = build_string (r);
1357 SAFE_FREE ();
1359 #endif /* AMPERSAND_FULL_NAME */
1361 return full;
1364 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1365 doc: /* Return the host name of the machine you are running on, as a string. */)
1366 (void)
1368 return Vsystem_name;
1371 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1372 doc: /* Return the process ID of Emacs, as a number. */)
1373 (void)
1375 pid_t pid = getpid ();
1376 return make_fixnum_or_float (pid);
1381 #ifndef TIME_T_MIN
1382 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1383 #endif
1384 #ifndef TIME_T_MAX
1385 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1386 #endif
1388 /* Report that a time value is out of range for Emacs. */
1389 void
1390 time_overflow (void)
1392 error ("Specified time is not representable");
1395 /* A substitute for mktime_z on platforms that lack it. It's not
1396 thread-safe, but should be good enough for Emacs in typical use. */
1397 #ifndef HAVE_TZALLOC
1398 time_t
1399 mktime_z (timezone_t tz, struct tm *tm)
1401 char *oldtz = getenv ("TZ");
1402 USE_SAFE_ALLOCA;
1403 if (oldtz)
1405 size_t oldtzsize = strlen (oldtz) + 1;
1406 char *oldtzcopy = SAFE_ALLOCA (oldtzsize);
1407 oldtz = strcpy (oldtzcopy, oldtz);
1409 block_input ();
1410 set_time_zone_rule (tz);
1411 time_t t = mktime (tm);
1412 set_time_zone_rule (oldtz);
1413 unblock_input ();
1414 SAFE_FREE ();
1415 return t;
1417 #endif
1419 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1420 static EMACS_INT
1421 hi_time (time_t t)
1423 time_t hi = t >> 16;
1425 /* Check for overflow, helping the compiler for common cases where
1426 no runtime check is needed, and taking care not to convert
1427 negative numbers to unsigned before comparing them. */
1428 if (! ((! TYPE_SIGNED (time_t)
1429 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1430 || MOST_NEGATIVE_FIXNUM <= hi)
1431 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1432 || hi <= MOST_POSITIVE_FIXNUM)))
1433 time_overflow ();
1435 return hi;
1438 /* Return the bottom 16 bits of the time T. */
1439 static int
1440 lo_time (time_t t)
1442 return t & ((1 << 16) - 1);
1445 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1446 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1447 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1448 HIGH has the most significant bits of the seconds, while LOW has the
1449 least significant 16 bits. USEC and PSEC are the microsecond and
1450 picosecond counts. */)
1451 (void)
1453 return make_lisp_time (current_timespec ());
1456 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1457 0, 0, 0,
1458 doc: /* Return the current run time used by Emacs.
1459 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1460 style as (current-time).
1462 On systems that can't determine the run time, `get-internal-run-time'
1463 does the same thing as `current-time'. */)
1464 (void)
1466 #ifdef HAVE_GETRUSAGE
1467 struct rusage usage;
1468 time_t secs;
1469 int usecs;
1471 if (getrusage (RUSAGE_SELF, &usage) < 0)
1472 /* This shouldn't happen. What action is appropriate? */
1473 xsignal0 (Qerror);
1475 /* Sum up user time and system time. */
1476 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1477 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1478 if (usecs >= 1000000)
1480 usecs -= 1000000;
1481 secs++;
1483 return make_lisp_time (make_timespec (secs, usecs * 1000));
1484 #else /* ! HAVE_GETRUSAGE */
1485 #ifdef WINDOWSNT
1486 return w32_get_internal_run_time ();
1487 #else /* ! WINDOWSNT */
1488 return Fcurrent_time ();
1489 #endif /* WINDOWSNT */
1490 #endif /* HAVE_GETRUSAGE */
1494 /* Make a Lisp list that represents the time T with fraction TAIL. */
1495 static Lisp_Object
1496 make_time_tail (time_t t, Lisp_Object tail)
1498 return Fcons (make_number (hi_time (t)),
1499 Fcons (make_number (lo_time (t)), tail));
1502 /* Make a Lisp list that represents the system time T. */
1503 static Lisp_Object
1504 make_time (time_t t)
1506 return make_time_tail (t, Qnil);
1509 /* Make a Lisp list that represents the Emacs time T. T may be an
1510 invalid time, with a slightly negative tv_nsec value such as
1511 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1512 correspondingly negative picosecond count. */
1513 Lisp_Object
1514 make_lisp_time (struct timespec t)
1516 int ns = t.tv_nsec;
1517 return make_time_tail (t.tv_sec, list2i (ns / 1000, ns % 1000 * 1000));
1520 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1521 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1522 Return true if successful. */
1523 static bool
1524 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1525 Lisp_Object *plow, Lisp_Object *pusec,
1526 Lisp_Object *ppsec)
1528 if (CONSP (specified_time))
1530 Lisp_Object low = XCDR (specified_time);
1531 Lisp_Object usec = make_number (0);
1532 Lisp_Object psec = make_number (0);
1533 if (CONSP (low))
1535 Lisp_Object low_tail = XCDR (low);
1536 low = XCAR (low);
1537 if (CONSP (low_tail))
1539 usec = XCAR (low_tail);
1540 low_tail = XCDR (low_tail);
1541 if (CONSP (low_tail))
1542 psec = XCAR (low_tail);
1544 else if (!NILP (low_tail))
1545 usec = low_tail;
1548 *phigh = XCAR (specified_time);
1549 *plow = low;
1550 *pusec = usec;
1551 *ppsec = psec;
1552 return 1;
1555 return 0;
1558 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1559 list, generate the corresponding time value.
1561 If RESULT is not null, store into *RESULT the converted time;
1562 if the converted time does not fit into struct timespec,
1563 store an invalid timespec to indicate the overflow.
1564 If *DRESULT is not null, store into *DRESULT the number of
1565 seconds since the start of the POSIX Epoch.
1567 Return true if successful. */
1568 bool
1569 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1570 Lisp_Object psec,
1571 struct timespec *result, double *dresult)
1573 EMACS_INT hi, lo, us, ps;
1574 if (! (INTEGERP (high) && INTEGERP (low)
1575 && INTEGERP (usec) && INTEGERP (psec)))
1576 return false;
1577 hi = XINT (high);
1578 lo = XINT (low);
1579 us = XINT (usec);
1580 ps = XINT (psec);
1582 /* Normalize out-of-range lower-order components by carrying
1583 each overflow into the next higher-order component. */
1584 us += ps / 1000000 - (ps % 1000000 < 0);
1585 lo += us / 1000000 - (us % 1000000 < 0);
1586 hi += lo >> 16;
1587 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1588 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1589 lo &= (1 << 16) - 1;
1591 if (result)
1593 if ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> 16 <= hi : 0 <= hi)
1594 && hi <= TIME_T_MAX >> 16)
1596 /* Return the greatest representable time that is not greater
1597 than the requested time. */
1598 time_t sec = hi;
1599 *result = make_timespec ((sec << 16) + lo, us * 1000 + ps / 1000);
1601 else
1602 *result = invalid_timespec ();
1605 if (dresult)
1606 *dresult = (us * 1e6 + ps) / 1e12 + lo + hi * 65536.0;
1608 return true;
1611 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1612 If SPECIFIED_TIME is nil, use the current time.
1614 Round the time down to the nearest struct timespec value.
1615 Return seconds since the Epoch.
1616 Signal an error if unsuccessful. */
1617 struct timespec
1618 lisp_time_argument (Lisp_Object specified_time)
1620 if (NILP (specified_time))
1621 return current_timespec ();
1622 else
1624 Lisp_Object high, low, usec, psec;
1625 struct timespec t;
1626 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1627 && decode_time_components (high, low, usec, psec, &t, 0)))
1628 error ("Invalid time specification");
1629 if (! timespec_valid_p (t))
1630 time_overflow ();
1631 return t;
1635 /* Like lisp_time_argument, except decode only the seconds part,
1636 and do not check the subseconds part. */
1637 static time_t
1638 lisp_seconds_argument (Lisp_Object specified_time)
1640 if (NILP (specified_time))
1641 return time (NULL);
1642 else
1644 Lisp_Object high, low, usec, psec;
1645 struct timespec t;
1646 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1647 && decode_time_components (high, low, make_number (0),
1648 make_number (0), &t, 0)))
1649 error ("Invalid time specification");
1650 if (! timespec_valid_p (t))
1651 time_overflow ();
1652 return t.tv_sec;
1656 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1657 doc: /* Return the current time, as a float number of seconds since the epoch.
1658 If SPECIFIED-TIME is given, it is the time to convert to float
1659 instead of the current time. The argument should have the form
1660 (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1661 you can use times from `current-time' and from `file-attributes'.
1662 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1663 considered obsolete.
1665 WARNING: Since the result is floating point, it may not be exact.
1666 If precise time stamps are required, use either `current-time',
1667 or (if you need time as a string) `format-time-string'. */)
1668 (Lisp_Object specified_time)
1670 double t;
1671 if (NILP (specified_time))
1673 struct timespec now = current_timespec ();
1674 t = now.tv_sec + now.tv_nsec / 1e9;
1676 else
1678 Lisp_Object high, low, usec, psec;
1679 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1680 && decode_time_components (high, low, usec, psec, 0, &t)))
1681 error ("Invalid time specification");
1683 return make_float (t);
1686 /* Write information into buffer S of size MAXSIZE, according to the
1687 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1688 Default to Universal Time if UT, local time otherwise.
1689 Use NS as the number of nanoseconds in the %N directive.
1690 Return the number of bytes written, not including the terminating
1691 '\0'. If S is NULL, nothing will be written anywhere; so to
1692 determine how many bytes would be written, use NULL for S and
1693 ((size_t) -1) for MAXSIZE.
1695 This function behaves like nstrftime, except it allows null
1696 bytes in FORMAT and it does not support nanoseconds. */
1697 static size_t
1698 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1699 size_t format_len, const struct tm *tp, bool ut, int ns)
1701 size_t total = 0;
1703 /* Loop through all the null-terminated strings in the format
1704 argument. Normally there's just one null-terminated string, but
1705 there can be arbitrarily many, concatenated together, if the
1706 format contains '\0' bytes. nstrftime stops at the first
1707 '\0' byte so we must invoke it separately for each such string. */
1708 for (;;)
1710 size_t len;
1711 size_t result;
1713 if (s)
1714 s[0] = '\1';
1716 result = nstrftime (s, maxsize, format, tp, ut, ns);
1718 if (s)
1720 if (result == 0 && s[0] != '\0')
1721 return 0;
1722 s += result + 1;
1725 maxsize -= result + 1;
1726 total += result;
1727 len = strlen (format);
1728 if (len == format_len)
1729 return total;
1730 total++;
1731 format += len + 1;
1732 format_len -= len + 1;
1736 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1737 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1738 TIME is specified as (HIGH LOW USEC PSEC), as returned by
1739 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1740 is also still accepted.
1741 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1742 as Universal Time; nil means describe TIME in the local time zone.
1743 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1744 by text that describes the specified date and time in TIME:
1746 %Y is the year, %y within the century, %C the century.
1747 %G is the year corresponding to the ISO week, %g within the century.
1748 %m is the numeric month.
1749 %b and %h are the locale's abbreviated month name, %B the full name.
1750 (%h is not supported on MS-Windows.)
1751 %d is the day of the month, zero-padded, %e is blank-padded.
1752 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1753 %a is the locale's abbreviated name of the day of week, %A the full name.
1754 %U is the week number starting on Sunday, %W starting on Monday,
1755 %V according to ISO 8601.
1756 %j is the day of the year.
1758 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1759 only blank-padded, %l is like %I blank-padded.
1760 %p is the locale's equivalent of either AM or PM.
1761 %M is the minute.
1762 %S is the second.
1763 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1764 %Z is the time zone name, %z is the numeric form.
1765 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1767 %c is the locale's date and time format.
1768 %x is the locale's "preferred" date format.
1769 %D is like "%m/%d/%y".
1770 %F is the ISO 8601 date format (like "%Y-%m-%d").
1772 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1773 %X is the locale's "preferred" time format.
1775 Finally, %n is a newline, %t is a tab, %% is a literal %.
1777 Certain flags and modifiers are available with some format controls.
1778 The flags are `_', `-', `^' and `#'. For certain characters X,
1779 %_X is like %X, but padded with blanks; %-X is like %X,
1780 but without padding. %^X is like %X, but with all textual
1781 characters up-cased; %#X is like %X, but with letter-case of
1782 all textual characters reversed.
1783 %NX (where N stands for an integer) is like %X,
1784 but takes up at least N (a number) positions.
1785 The modifiers are `E' and `O'. For certain characters X,
1786 %EX is a locale's alternative version of %X;
1787 %OX is like %X, but uses the locale's number symbols.
1789 For example, to produce full ISO 8601 format, use "%FT%T%z".
1791 usage: (format-time-string FORMAT-STRING &optional TIME UNIVERSAL) */)
1792 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1794 struct timespec t = lisp_time_argument (timeval);
1795 struct tm tm;
1797 CHECK_STRING (format_string);
1798 format_string = code_convert_string_norecord (format_string,
1799 Vlocale_coding_system, 1);
1800 return format_time_string (SSDATA (format_string), SBYTES (format_string),
1801 t, ! NILP (universal), &tm);
1804 static Lisp_Object
1805 format_time_string (char const *format, ptrdiff_t formatlen,
1806 struct timespec t, bool ut, struct tm *tmp)
1808 char buffer[4000];
1809 char *buf = buffer;
1810 ptrdiff_t size = sizeof buffer;
1811 size_t len;
1812 Lisp_Object bufstring;
1813 int ns = t.tv_nsec;
1814 USE_SAFE_ALLOCA;
1816 tmp = ut ? gmtime_r (&t.tv_sec, tmp) : localtime_r (&t.tv_sec, tmp);
1817 if (! tmp)
1818 time_overflow ();
1819 synchronize_system_time_locale ();
1821 while (true)
1823 buf[0] = '\1';
1824 len = emacs_nmemftime (buf, size, format, formatlen, tmp, ut, ns);
1825 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
1826 break;
1828 /* Buffer was too small, so make it bigger and try again. */
1829 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, ut, ns);
1830 if (STRING_BYTES_BOUND <= len)
1831 string_overflow ();
1832 size = len + 1;
1833 buf = SAFE_ALLOCA (size);
1836 bufstring = make_unibyte_string (buf, len);
1837 SAFE_FREE ();
1838 return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
1841 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1842 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1843 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1844 as from `current-time' and `file-attributes', or nil to use the
1845 current time. The obsolete form (HIGH . LOW) is also still accepted.
1846 The list has the following nine members: SEC is an integer between 0
1847 and 60; SEC is 60 for a leap second, which only some operating systems
1848 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1849 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1850 integer between 1 and 12. YEAR is an integer indicating the
1851 four-digit year. DOW is the day of week, an integer between 0 and 6,
1852 where 0 is Sunday. DST is t if daylight saving time is in effect,
1853 otherwise nil. ZONE is an integer indicating the number of seconds
1854 east of Greenwich. (Note that Common Lisp has different meanings for
1855 DOW and ZONE.) */)
1856 (Lisp_Object specified_time)
1858 time_t time_spec = lisp_seconds_argument (specified_time);
1859 struct tm local_tm, gmt_tm;
1861 if (! (localtime_r (&time_spec, &local_tm)
1862 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
1863 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1864 time_overflow ();
1866 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
1867 EMACS_INT tm_year_base = TM_YEAR_BASE;
1869 return Flist (9, ((Lisp_Object [])
1870 {make_number (local_tm.tm_sec),
1871 make_number (local_tm.tm_min),
1872 make_number (local_tm.tm_hour),
1873 make_number (local_tm.tm_mday),
1874 make_number (local_tm.tm_mon + 1),
1875 make_number (local_tm.tm_year + tm_year_base),
1876 make_number (local_tm.tm_wday),
1877 local_tm.tm_isdst ? Qt : Qnil,
1878 (HAVE_TM_GMTOFF
1879 ? make_number (tm_gmtoff (&local_tm))
1880 : gmtime_r (&time_spec, &gmt_tm)
1881 ? make_number (tm_diff (&local_tm, &gmt_tm))
1882 : Qnil)}));
1885 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1886 the result is representable as an int. Assume OFFSET is small and
1887 nonnegative. */
1888 static int
1889 check_tm_member (Lisp_Object obj, int offset)
1891 EMACS_INT n;
1892 CHECK_NUMBER (obj);
1893 n = XINT (obj);
1894 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1895 time_overflow ();
1896 return n - offset;
1899 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1900 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1901 This is the reverse operation of `decode-time', which see.
1902 ZONE defaults to the current time zone rule. This can
1903 be a string or t (as from `set-time-zone-rule'), or it can be a list
1904 \(as from `current-time-zone') or an integer (as from `decode-time')
1905 applied without consideration for daylight saving time.
1907 You can pass more than 7 arguments; then the first six arguments
1908 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1909 The intervening arguments are ignored.
1910 This feature lets (apply 'encode-time (decode-time ...)) work.
1912 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1913 for example, a DAY of 0 means the day preceding the given month.
1914 Year numbers less than 100 are treated just like other year numbers.
1915 If you want them to stand for years in this century, you must do that yourself.
1917 Years before 1970 are not guaranteed to work. On some systems,
1918 year values as low as 1901 do work.
1920 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1921 (ptrdiff_t nargs, Lisp_Object *args)
1923 time_t value;
1924 struct tm tm;
1925 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1927 tm.tm_sec = check_tm_member (args[0], 0);
1928 tm.tm_min = check_tm_member (args[1], 0);
1929 tm.tm_hour = check_tm_member (args[2], 0);
1930 tm.tm_mday = check_tm_member (args[3], 0);
1931 tm.tm_mon = check_tm_member (args[4], 1);
1932 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1933 tm.tm_isdst = -1;
1935 if (CONSP (zone))
1936 zone = XCAR (zone);
1937 if (NILP (zone))
1938 value = mktime (&tm);
1939 else
1941 static char const tzbuf_format[] = "XXX%s%"pI"d:%02d:%02d";
1942 char tzbuf[sizeof tzbuf_format + INT_STRLEN_BOUND (EMACS_INT)];
1943 const char *tzstring;
1945 if (EQ (zone, Qt))
1946 tzstring = "UTC0";
1947 else if (STRINGP (zone))
1948 tzstring = SSDATA (zone);
1949 else if (INTEGERP (zone))
1951 EMACS_INT abszone = eabs (XINT (zone));
1952 EMACS_INT zone_hr = abszone / (60*60);
1953 int zone_min = (abszone/60) % 60;
1954 int zone_sec = abszone % 60;
1955 sprintf (tzbuf, tzbuf_format, &"-"[XINT (zone) < 0],
1956 zone_hr, zone_min, zone_sec);
1957 tzstring = tzbuf;
1959 else
1960 tzstring = 0;
1962 timezone_t tz = tzstring ? tzalloc (tzstring) : 0;
1963 if (! tz)
1964 error ("Invalid time zone specification");
1965 value = mktime_z (tz, &tm);
1966 tzfree (tz);
1969 if (value == (time_t) -1)
1970 time_overflow ();
1972 return make_time (value);
1975 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1976 doc: /* Return the current local time, as a human-readable string.
1977 Programs can use this function to decode a time,
1978 since the number of columns in each field is fixed
1979 if the year is in the range 1000-9999.
1980 The format is `Sun Sep 16 01:03:52 1973'.
1981 However, see also the functions `decode-time' and `format-time-string'
1982 which provide a much more powerful and general facility.
1984 If SPECIFIED-TIME is given, it is a time to format instead of the
1985 current time. The argument should have the form (HIGH LOW . IGNORED).
1986 Thus, you can use times obtained from `current-time' and from
1987 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1988 but this is considered obsolete. */)
1989 (Lisp_Object specified_time)
1991 time_t value = lisp_seconds_argument (specified_time);
1993 /* Convert to a string in ctime format, except without the trailing
1994 newline, and without the 4-digit year limit. Don't use asctime
1995 or ctime, as they might dump core if the year is outside the
1996 range -999 .. 9999. */
1997 struct tm tm;
1998 if (! localtime_r (&value, &tm))
1999 time_overflow ();
2001 static char const wday_name[][4] =
2002 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2003 static char const mon_name[][4] =
2004 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2005 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2006 printmax_t year_base = TM_YEAR_BASE;
2007 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2008 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2009 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2010 tm.tm_hour, tm.tm_min, tm.tm_sec,
2011 tm.tm_year + year_base);
2013 return make_unibyte_string (buf, len);
2016 /* Yield A - B, measured in seconds.
2017 This function is copied from the GNU C Library. */
2018 static int
2019 tm_diff (struct tm *a, struct tm *b)
2021 /* Compute intervening leap days correctly even if year is negative.
2022 Take care to avoid int overflow in leap day calculations,
2023 but it's OK to assume that A and B are close to each other. */
2024 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2025 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2026 int a100 = a4 / 25 - (a4 % 25 < 0);
2027 int b100 = b4 / 25 - (b4 % 25 < 0);
2028 int a400 = a100 >> 2;
2029 int b400 = b100 >> 2;
2030 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2031 int years = a->tm_year - b->tm_year;
2032 int days = (365 * years + intervening_leap_days
2033 + (a->tm_yday - b->tm_yday));
2034 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2035 + (a->tm_min - b->tm_min))
2036 + (a->tm_sec - b->tm_sec));
2039 /* Yield A's UTC offset, or an unspecified value if unknown. */
2040 static long int
2041 tm_gmtoff (struct tm *a)
2043 #if HAVE_TM_GMTOFF
2044 return a->tm_gmtoff;
2045 #else
2046 return 0;
2047 #endif
2050 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2051 doc: /* Return the offset and name for the local time zone.
2052 This returns a list of the form (OFFSET NAME).
2053 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2054 A negative value means west of Greenwich.
2055 NAME is a string giving the name of the time zone.
2056 If SPECIFIED-TIME is given, the time zone offset is determined from it
2057 instead of using the current time. The argument should have the form
2058 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2059 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2060 have the form (HIGH . LOW), but this is considered obsolete.
2062 Some operating systems cannot provide all this information to Emacs;
2063 in this case, `current-time-zone' returns a list containing nil for
2064 the data it can't find. */)
2065 (Lisp_Object specified_time)
2067 struct timespec value;
2068 struct tm local_tm, gmt_tm;
2069 Lisp_Object zone_offset, zone_name;
2071 zone_offset = Qnil;
2072 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2073 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value, 0, &local_tm);
2075 if (HAVE_TM_GMTOFF || gmtime_r (&value.tv_sec, &gmt_tm))
2077 long int offset = (HAVE_TM_GMTOFF
2078 ? tm_gmtoff (&local_tm)
2079 : tm_diff (&local_tm, &gmt_tm));
2080 zone_offset = make_number (offset);
2081 if (SCHARS (zone_name) == 0)
2083 /* No local time zone name is available; use "+-NNNN" instead. */
2084 long int m = offset / 60;
2085 long int am = offset < 0 ? - m : m;
2086 long int hour = am / 60;
2087 int min = am % 60;
2088 char buf[sizeof "+00" + INT_STRLEN_BOUND (long int)];
2089 zone_name = make_formatted_string (buf, "%c%02ld%02d",
2090 (offset < 0 ? '-' : '+'),
2091 hour, min);
2095 return list2 (zone_offset, zone_name);
2098 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2099 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2100 If TZ is nil, use implementation-defined default time zone information.
2101 If TZ is t, use Universal Time.
2103 Instead of calling this function, you typically want (setenv "TZ" TZ).
2104 That changes both the environment of the Emacs process and the
2105 variable `process-environment', whereas `set-time-zone-rule' affects
2106 only the former. */)
2107 (Lisp_Object tz)
2109 const char *tzstring;
2111 if (! (NILP (tz) || EQ (tz, Qt)))
2112 CHECK_STRING (tz);
2114 if (NILP (tz))
2115 tzstring = initial_tz;
2116 else if (EQ (tz, Qt))
2117 tzstring = "UTC0";
2118 else
2119 tzstring = SSDATA (tz);
2121 block_input ();
2122 set_time_zone_rule (tzstring);
2123 unblock_input ();
2125 return Qnil;
2128 /* Set the local time zone rule to TZSTRING.
2130 This function is not thread-safe, in theory because putenv is not,
2131 but mostly because of the static storage it updates. Other threads
2132 that invoke localtime etc. may be adversely affected while this
2133 function is executing. */
2135 static void
2136 set_time_zone_rule (const char *tzstring)
2138 /* A buffer holding a string of the form "TZ=value", intended
2139 to be part of the environment. */
2140 static char *tzvalbuf;
2141 static ptrdiff_t tzvalbufsize;
2143 int tzeqlen = sizeof "TZ=" - 1;
2144 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2145 char *tzval = tzvalbuf;
2146 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2148 if (new_tzvalbuf)
2150 /* Do not attempt to free the old tzvalbuf, since another thread
2151 may be using it. In practice, the first allocation is large
2152 enough and memory does not leak. */
2153 tzval = xpalloc (NULL, &tzvalbufsize,
2154 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2155 tzvalbuf = tzval;
2156 tzval[1] = 'Z';
2157 tzval[2] = '=';
2160 if (tzstring)
2162 /* Modify TZVAL in place. Although this is dicey in a
2163 multithreaded environment, we know of no portable alternative.
2164 Calling putenv or setenv could crash some other thread. */
2165 tzval[0] = 'T';
2166 strcpy (tzval + tzeqlen, tzstring);
2168 else
2170 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2171 Although this is also dicey, calling unsetenv here can crash Emacs.
2172 See Bug#8705. */
2173 tzval[0] = 't';
2174 tzval[tzeqlen] = 0;
2177 if (new_tzvalbuf)
2179 /* Although this is not thread-safe, in practice this runs only
2180 on startup when there is only one thread. */
2181 xputenv (tzval);
2184 #ifdef HAVE_TZSET
2185 tzset ();
2186 #endif
2189 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2190 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2191 type of object is Lisp_String). INHERIT is passed to
2192 INSERT_FROM_STRING_FUNC as the last argument. */
2194 static void
2195 general_insert_function (void (*insert_func)
2196 (const char *, ptrdiff_t),
2197 void (*insert_from_string_func)
2198 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2199 ptrdiff_t, ptrdiff_t, bool),
2200 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2202 ptrdiff_t argnum;
2203 Lisp_Object val;
2205 for (argnum = 0; argnum < nargs; argnum++)
2207 val = args[argnum];
2208 if (CHARACTERP (val))
2210 int c = XFASTINT (val);
2211 unsigned char str[MAX_MULTIBYTE_LENGTH];
2212 int len;
2214 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2215 len = CHAR_STRING (c, str);
2216 else
2218 str[0] = CHAR_TO_BYTE8 (c);
2219 len = 1;
2221 (*insert_func) ((char *) str, len);
2223 else if (STRINGP (val))
2225 (*insert_from_string_func) (val, 0, 0,
2226 SCHARS (val),
2227 SBYTES (val),
2228 inherit);
2230 else
2231 wrong_type_argument (Qchar_or_string_p, val);
2235 void
2236 insert1 (Lisp_Object arg)
2238 Finsert (1, &arg);
2242 /* Callers passing one argument to Finsert need not gcpro the
2243 argument "array", since the only element of the array will
2244 not be used after calling insert or insert_from_string, so
2245 we don't care if it gets trashed. */
2247 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2248 doc: /* Insert the arguments, either strings or characters, at point.
2249 Point and before-insertion markers move forward to end up
2250 after the inserted text.
2251 Any other markers at the point of insertion remain before the text.
2253 If the current buffer is multibyte, unibyte strings are converted
2254 to multibyte for insertion (see `string-make-multibyte').
2255 If the current buffer is unibyte, multibyte strings are converted
2256 to unibyte for insertion (see `string-make-unibyte').
2258 When operating on binary data, it may be necessary to preserve the
2259 original bytes of a unibyte string when inserting it into a multibyte
2260 buffer; to accomplish this, apply `string-as-multibyte' to the string
2261 and insert the result.
2263 usage: (insert &rest ARGS) */)
2264 (ptrdiff_t nargs, Lisp_Object *args)
2266 general_insert_function (insert, insert_from_string, 0, nargs, args);
2267 return Qnil;
2270 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2271 0, MANY, 0,
2272 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2273 Point and before-insertion markers move forward to end up
2274 after the inserted text.
2275 Any other markers at the point of insertion remain before the text.
2277 If the current buffer is multibyte, unibyte strings are converted
2278 to multibyte for insertion (see `unibyte-char-to-multibyte').
2279 If the current buffer is unibyte, multibyte strings are converted
2280 to unibyte for insertion.
2282 usage: (insert-and-inherit &rest ARGS) */)
2283 (ptrdiff_t nargs, Lisp_Object *args)
2285 general_insert_function (insert_and_inherit, insert_from_string, 1,
2286 nargs, args);
2287 return Qnil;
2290 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2291 doc: /* Insert strings or characters at point, relocating markers after the text.
2292 Point and markers move forward to end up after the inserted text.
2294 If the current buffer is multibyte, unibyte strings are converted
2295 to multibyte for insertion (see `unibyte-char-to-multibyte').
2296 If the current buffer is unibyte, multibyte strings are converted
2297 to unibyte for insertion.
2299 If an overlay begins at the insertion point, the inserted text falls
2300 outside the overlay; if a nonempty overlay ends at the insertion
2301 point, the inserted text falls inside that overlay.
2303 usage: (insert-before-markers &rest ARGS) */)
2304 (ptrdiff_t nargs, Lisp_Object *args)
2306 general_insert_function (insert_before_markers,
2307 insert_from_string_before_markers, 0,
2308 nargs, args);
2309 return Qnil;
2312 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2313 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2314 doc: /* Insert text at point, relocating markers and inheriting properties.
2315 Point and markers move forward to end up after the inserted text.
2317 If the current buffer is multibyte, unibyte strings are converted
2318 to multibyte for insertion (see `unibyte-char-to-multibyte').
2319 If the current buffer is unibyte, multibyte strings are converted
2320 to unibyte for insertion.
2322 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2323 (ptrdiff_t nargs, Lisp_Object *args)
2325 general_insert_function (insert_before_markers_and_inherit,
2326 insert_from_string_before_markers, 1,
2327 nargs, args);
2328 return Qnil;
2331 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2332 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2333 (prefix-numeric-value current-prefix-arg)\
2334 t))",
2335 doc: /* Insert COUNT copies of CHARACTER.
2336 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2337 of these ways:
2339 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2340 Completion is available; if you type a substring of the name
2341 preceded by an asterisk `*', Emacs shows all names which include
2342 that substring, not necessarily at the beginning of the name.
2344 - As a hexadecimal code point, e.g. 263A. Note that code points in
2345 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2346 the Unicode code space).
2348 - As a code point with a radix specified with #, e.g. #o21430
2349 (octal), #x2318 (hex), or #10r8984 (decimal).
2351 If called interactively, COUNT is given by the prefix argument. If
2352 omitted or nil, it defaults to 1.
2354 Inserting the character(s) relocates point and before-insertion
2355 markers in the same ways as the function `insert'.
2357 The optional third argument INHERIT, if non-nil, says to inherit text
2358 properties from adjoining text, if those properties are sticky. If
2359 called interactively, INHERIT is t. */)
2360 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2362 int i, stringlen;
2363 register ptrdiff_t n;
2364 int c, len;
2365 unsigned char str[MAX_MULTIBYTE_LENGTH];
2366 char string[4000];
2368 CHECK_CHARACTER (character);
2369 if (NILP (count))
2370 XSETFASTINT (count, 1);
2371 CHECK_NUMBER (count);
2372 c = XFASTINT (character);
2374 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2375 len = CHAR_STRING (c, str);
2376 else
2377 str[0] = c, len = 1;
2378 if (XINT (count) <= 0)
2379 return Qnil;
2380 if (BUF_BYTES_MAX / len < XINT (count))
2381 buffer_overflow ();
2382 n = XINT (count) * len;
2383 stringlen = min (n, sizeof string - sizeof string % len);
2384 for (i = 0; i < stringlen; i++)
2385 string[i] = str[i % len];
2386 while (n > stringlen)
2388 QUIT;
2389 if (!NILP (inherit))
2390 insert_and_inherit (string, stringlen);
2391 else
2392 insert (string, stringlen);
2393 n -= stringlen;
2395 if (!NILP (inherit))
2396 insert_and_inherit (string, n);
2397 else
2398 insert (string, n);
2399 return Qnil;
2402 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2403 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2404 Both arguments are required.
2405 BYTE is a number of the range 0..255.
2407 If BYTE is 128..255 and the current buffer is multibyte, the
2408 corresponding eight-bit character is inserted.
2410 Point, and before-insertion markers, are relocated as in the function `insert'.
2411 The optional third arg INHERIT, if non-nil, says to inherit text properties
2412 from adjoining text, if those properties are sticky. */)
2413 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2415 CHECK_NUMBER (byte);
2416 if (XINT (byte) < 0 || XINT (byte) > 255)
2417 args_out_of_range_3 (byte, make_number (0), make_number (255));
2418 if (XINT (byte) >= 128
2419 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2420 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2421 return Finsert_char (byte, count, inherit);
2425 /* Making strings from buffer contents. */
2427 /* Return a Lisp_String containing the text of the current buffer from
2428 START to END. If text properties are in use and the current buffer
2429 has properties in the range specified, the resulting string will also
2430 have them, if PROPS is true.
2432 We don't want to use plain old make_string here, because it calls
2433 make_uninit_string, which can cause the buffer arena to be
2434 compacted. make_string has no way of knowing that the data has
2435 been moved, and thus copies the wrong data into the string. This
2436 doesn't effect most of the other users of make_string, so it should
2437 be left as is. But we should use this function when conjuring
2438 buffer substrings. */
2440 Lisp_Object
2441 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2443 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2444 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2446 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2449 /* Return a Lisp_String containing the text of the current buffer from
2450 START / START_BYTE to END / END_BYTE.
2452 If text properties are in use and the current buffer
2453 has properties in the range specified, the resulting string will also
2454 have them, if PROPS is true.
2456 We don't want to use plain old make_string here, because it calls
2457 make_uninit_string, which can cause the buffer arena to be
2458 compacted. make_string has no way of knowing that the data has
2459 been moved, and thus copies the wrong data into the string. This
2460 doesn't effect most of the other users of make_string, so it should
2461 be left as is. But we should use this function when conjuring
2462 buffer substrings. */
2464 Lisp_Object
2465 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2466 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2468 Lisp_Object result, tem, tem1;
2470 if (start < GPT && GPT < end)
2471 move_gap_both (start, start_byte);
2473 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2474 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2475 else
2476 result = make_uninit_string (end - start);
2477 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2479 /* If desired, update and copy the text properties. */
2480 if (props)
2482 update_buffer_properties (start, end);
2484 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2485 tem1 = Ftext_properties_at (make_number (start), Qnil);
2487 if (XINT (tem) != end || !NILP (tem1))
2488 copy_intervals_to_string (result, current_buffer, start,
2489 end - start);
2492 return result;
2495 /* Call Vbuffer_access_fontify_functions for the range START ... END
2496 in the current buffer, if necessary. */
2498 static void
2499 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2501 /* If this buffer has some access functions,
2502 call them, specifying the range of the buffer being accessed. */
2503 if (!NILP (Vbuffer_access_fontify_functions))
2505 Lisp_Object args[3];
2506 Lisp_Object tem;
2508 args[0] = Qbuffer_access_fontify_functions;
2509 XSETINT (args[1], start);
2510 XSETINT (args[2], end);
2512 /* But don't call them if we can tell that the work
2513 has already been done. */
2514 if (!NILP (Vbuffer_access_fontified_property))
2516 tem = Ftext_property_any (args[1], args[2],
2517 Vbuffer_access_fontified_property,
2518 Qnil, Qnil);
2519 if (! NILP (tem))
2520 Frun_hook_with_args (3, args);
2522 else
2523 Frun_hook_with_args (3, args);
2527 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2528 doc: /* Return the contents of part of the current buffer as a string.
2529 The two arguments START and END are character positions;
2530 they can be in either order.
2531 The string returned is multibyte if the buffer is multibyte.
2533 This function copies the text properties of that part of the buffer
2534 into the result string; if you don't want the text properties,
2535 use `buffer-substring-no-properties' instead. */)
2536 (Lisp_Object start, Lisp_Object end)
2538 register ptrdiff_t b, e;
2540 validate_region (&start, &end);
2541 b = XINT (start);
2542 e = XINT (end);
2544 return make_buffer_string (b, e, 1);
2547 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2548 Sbuffer_substring_no_properties, 2, 2, 0,
2549 doc: /* Return the characters of part of the buffer, without the text properties.
2550 The two arguments START and END are character positions;
2551 they can be in either order. */)
2552 (Lisp_Object start, Lisp_Object end)
2554 register ptrdiff_t b, e;
2556 validate_region (&start, &end);
2557 b = XINT (start);
2558 e = XINT (end);
2560 return make_buffer_string (b, e, 0);
2563 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2564 doc: /* Return the contents of the current buffer as a string.
2565 If narrowing is in effect, this function returns only the visible part
2566 of the buffer. */)
2567 (void)
2569 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2572 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2573 1, 3, 0,
2574 doc: /* Insert before point a substring of the contents of BUFFER.
2575 BUFFER may be a buffer or a buffer name.
2576 Arguments START and END are character positions specifying the substring.
2577 They default to the values of (point-min) and (point-max) in BUFFER. */)
2578 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2580 register EMACS_INT b, e, temp;
2581 register struct buffer *bp, *obuf;
2582 Lisp_Object buf;
2584 buf = Fget_buffer (buffer);
2585 if (NILP (buf))
2586 nsberror (buffer);
2587 bp = XBUFFER (buf);
2588 if (!BUFFER_LIVE_P (bp))
2589 error ("Selecting deleted buffer");
2591 if (NILP (start))
2592 b = BUF_BEGV (bp);
2593 else
2595 CHECK_NUMBER_COERCE_MARKER (start);
2596 b = XINT (start);
2598 if (NILP (end))
2599 e = BUF_ZV (bp);
2600 else
2602 CHECK_NUMBER_COERCE_MARKER (end);
2603 e = XINT (end);
2606 if (b > e)
2607 temp = b, b = e, e = temp;
2609 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2610 args_out_of_range (start, end);
2612 obuf = current_buffer;
2613 set_buffer_internal_1 (bp);
2614 update_buffer_properties (b, e);
2615 set_buffer_internal_1 (obuf);
2617 insert_from_buffer (bp, b, e - b, 0);
2618 return Qnil;
2621 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2622 6, 6, 0,
2623 doc: /* Compare two substrings of two buffers; return result as number.
2624 Return -N if first string is less after N-1 chars, +N if first string is
2625 greater after N-1 chars, or 0 if strings match. Each substring is
2626 represented as three arguments: BUFFER, START and END. That makes six
2627 args in all, three for each substring.
2629 The value of `case-fold-search' in the current buffer
2630 determines whether case is significant or ignored. */)
2631 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2633 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2634 register struct buffer *bp1, *bp2;
2635 register Lisp_Object trt
2636 = (!NILP (BVAR (current_buffer, case_fold_search))
2637 ? BVAR (current_buffer, case_canon_table) : Qnil);
2638 ptrdiff_t chars = 0;
2639 ptrdiff_t i1, i2, i1_byte, i2_byte;
2641 /* Find the first buffer and its substring. */
2643 if (NILP (buffer1))
2644 bp1 = current_buffer;
2645 else
2647 Lisp_Object buf1;
2648 buf1 = Fget_buffer (buffer1);
2649 if (NILP (buf1))
2650 nsberror (buffer1);
2651 bp1 = XBUFFER (buf1);
2652 if (!BUFFER_LIVE_P (bp1))
2653 error ("Selecting deleted buffer");
2656 if (NILP (start1))
2657 begp1 = BUF_BEGV (bp1);
2658 else
2660 CHECK_NUMBER_COERCE_MARKER (start1);
2661 begp1 = XINT (start1);
2663 if (NILP (end1))
2664 endp1 = BUF_ZV (bp1);
2665 else
2667 CHECK_NUMBER_COERCE_MARKER (end1);
2668 endp1 = XINT (end1);
2671 if (begp1 > endp1)
2672 temp = begp1, begp1 = endp1, endp1 = temp;
2674 if (!(BUF_BEGV (bp1) <= begp1
2675 && begp1 <= endp1
2676 && endp1 <= BUF_ZV (bp1)))
2677 args_out_of_range (start1, end1);
2679 /* Likewise for second substring. */
2681 if (NILP (buffer2))
2682 bp2 = current_buffer;
2683 else
2685 Lisp_Object buf2;
2686 buf2 = Fget_buffer (buffer2);
2687 if (NILP (buf2))
2688 nsberror (buffer2);
2689 bp2 = XBUFFER (buf2);
2690 if (!BUFFER_LIVE_P (bp2))
2691 error ("Selecting deleted buffer");
2694 if (NILP (start2))
2695 begp2 = BUF_BEGV (bp2);
2696 else
2698 CHECK_NUMBER_COERCE_MARKER (start2);
2699 begp2 = XINT (start2);
2701 if (NILP (end2))
2702 endp2 = BUF_ZV (bp2);
2703 else
2705 CHECK_NUMBER_COERCE_MARKER (end2);
2706 endp2 = XINT (end2);
2709 if (begp2 > endp2)
2710 temp = begp2, begp2 = endp2, endp2 = temp;
2712 if (!(BUF_BEGV (bp2) <= begp2
2713 && begp2 <= endp2
2714 && endp2 <= BUF_ZV (bp2)))
2715 args_out_of_range (start2, end2);
2717 i1 = begp1;
2718 i2 = begp2;
2719 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2720 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2722 while (i1 < endp1 && i2 < endp2)
2724 /* When we find a mismatch, we must compare the
2725 characters, not just the bytes. */
2726 int c1, c2;
2728 QUIT;
2730 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2732 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2733 BUF_INC_POS (bp1, i1_byte);
2734 i1++;
2736 else
2738 c1 = BUF_FETCH_BYTE (bp1, i1);
2739 MAKE_CHAR_MULTIBYTE (c1);
2740 i1++;
2743 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2745 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2746 BUF_INC_POS (bp2, i2_byte);
2747 i2++;
2749 else
2751 c2 = BUF_FETCH_BYTE (bp2, i2);
2752 MAKE_CHAR_MULTIBYTE (c2);
2753 i2++;
2756 if (!NILP (trt))
2758 c1 = char_table_translate (trt, c1);
2759 c2 = char_table_translate (trt, c2);
2761 if (c1 < c2)
2762 return make_number (- 1 - chars);
2763 if (c1 > c2)
2764 return make_number (chars + 1);
2766 chars++;
2769 /* The strings match as far as they go.
2770 If one is shorter, that one is less. */
2771 if (chars < endp1 - begp1)
2772 return make_number (chars + 1);
2773 else if (chars < endp2 - begp2)
2774 return make_number (- chars - 1);
2776 /* Same length too => they are equal. */
2777 return make_number (0);
2780 static void
2781 subst_char_in_region_unwind (Lisp_Object arg)
2783 bset_undo_list (current_buffer, arg);
2786 static void
2787 subst_char_in_region_unwind_1 (Lisp_Object arg)
2789 bset_filename (current_buffer, arg);
2792 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2793 Ssubst_char_in_region, 4, 5, 0,
2794 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2795 If optional arg NOUNDO is non-nil, don't record this change for undo
2796 and don't mark the buffer as really changed.
2797 Both characters must have the same length of multi-byte form. */)
2798 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2800 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
2801 /* Keep track of the first change in the buffer:
2802 if 0 we haven't found it yet.
2803 if < 0 we've found it and we've run the before-change-function.
2804 if > 0 we've actually performed it and the value is its position. */
2805 ptrdiff_t changed = 0;
2806 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2807 unsigned char *p;
2808 ptrdiff_t count = SPECPDL_INDEX ();
2809 #define COMBINING_NO 0
2810 #define COMBINING_BEFORE 1
2811 #define COMBINING_AFTER 2
2812 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2813 int maybe_byte_combining = COMBINING_NO;
2814 ptrdiff_t last_changed = 0;
2815 bool multibyte_p
2816 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2817 int fromc, toc;
2819 restart:
2821 validate_region (&start, &end);
2822 CHECK_CHARACTER (fromchar);
2823 CHECK_CHARACTER (tochar);
2824 fromc = XFASTINT (fromchar);
2825 toc = XFASTINT (tochar);
2827 if (multibyte_p)
2829 len = CHAR_STRING (fromc, fromstr);
2830 if (CHAR_STRING (toc, tostr) != len)
2831 error ("Characters in `subst-char-in-region' have different byte-lengths");
2832 if (!ASCII_CHAR_P (*tostr))
2834 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2835 complete multibyte character, it may be combined with the
2836 after bytes. If it is in the range 0xA0..0xFF, it may be
2837 combined with the before and after bytes. */
2838 if (!CHAR_HEAD_P (*tostr))
2839 maybe_byte_combining = COMBINING_BOTH;
2840 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2841 maybe_byte_combining = COMBINING_AFTER;
2844 else
2846 len = 1;
2847 fromstr[0] = fromc;
2848 tostr[0] = toc;
2851 pos = XINT (start);
2852 pos_byte = CHAR_TO_BYTE (pos);
2853 stop = CHAR_TO_BYTE (XINT (end));
2854 end_byte = stop;
2856 /* If we don't want undo, turn off putting stuff on the list.
2857 That's faster than getting rid of things,
2858 and it prevents even the entry for a first change.
2859 Also inhibit locking the file. */
2860 if (!changed && !NILP (noundo))
2862 record_unwind_protect (subst_char_in_region_unwind,
2863 BVAR (current_buffer, undo_list));
2864 bset_undo_list (current_buffer, Qt);
2865 /* Don't do file-locking. */
2866 record_unwind_protect (subst_char_in_region_unwind_1,
2867 BVAR (current_buffer, filename));
2868 bset_filename (current_buffer, Qnil);
2871 if (pos_byte < GPT_BYTE)
2872 stop = min (stop, GPT_BYTE);
2873 while (1)
2875 ptrdiff_t pos_byte_next = pos_byte;
2877 if (pos_byte >= stop)
2879 if (pos_byte >= end_byte) break;
2880 stop = end_byte;
2882 p = BYTE_POS_ADDR (pos_byte);
2883 if (multibyte_p)
2884 INC_POS (pos_byte_next);
2885 else
2886 ++pos_byte_next;
2887 if (pos_byte_next - pos_byte == len
2888 && p[0] == fromstr[0]
2889 && (len == 1
2890 || (p[1] == fromstr[1]
2891 && (len == 2 || (p[2] == fromstr[2]
2892 && (len == 3 || p[3] == fromstr[3]))))))
2894 if (changed < 0)
2895 /* We've already seen this and run the before-change-function;
2896 this time we only need to record the actual position. */
2897 changed = pos;
2898 else if (!changed)
2900 changed = -1;
2901 modify_text (pos, XINT (end));
2903 if (! NILP (noundo))
2905 if (MODIFF - 1 == SAVE_MODIFF)
2906 SAVE_MODIFF++;
2907 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2908 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2911 /* The before-change-function may have moved the gap
2912 or even modified the buffer so we should start over. */
2913 goto restart;
2916 /* Take care of the case where the new character
2917 combines with neighboring bytes. */
2918 if (maybe_byte_combining
2919 && (maybe_byte_combining == COMBINING_AFTER
2920 ? (pos_byte_next < Z_BYTE
2921 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2922 : ((pos_byte_next < Z_BYTE
2923 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2924 || (pos_byte > BEG_BYTE
2925 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
2927 Lisp_Object tem, string;
2929 struct gcpro gcpro1;
2931 tem = BVAR (current_buffer, undo_list);
2932 GCPRO1 (tem);
2934 /* Make a multibyte string containing this single character. */
2935 string = make_multibyte_string ((char *) tostr, 1, len);
2936 /* replace_range is less efficient, because it moves the gap,
2937 but it handles combining correctly. */
2938 replace_range (pos, pos + 1, string,
2939 0, 0, 1);
2940 pos_byte_next = CHAR_TO_BYTE (pos);
2941 if (pos_byte_next > pos_byte)
2942 /* Before combining happened. We should not increment
2943 POS. So, to cancel the later increment of POS,
2944 decrease it now. */
2945 pos--;
2946 else
2947 INC_POS (pos_byte_next);
2949 if (! NILP (noundo))
2950 bset_undo_list (current_buffer, tem);
2952 UNGCPRO;
2954 else
2956 if (NILP (noundo))
2957 record_change (pos, 1);
2958 for (i = 0; i < len; i++) *p++ = tostr[i];
2960 last_changed = pos + 1;
2962 pos_byte = pos_byte_next;
2963 pos++;
2966 if (changed > 0)
2968 signal_after_change (changed,
2969 last_changed - changed, last_changed - changed);
2970 update_compositions (changed, last_changed, CHECK_ALL);
2973 unbind_to (count, Qnil);
2974 return Qnil;
2978 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
2979 Lisp_Object);
2981 /* Helper function for Ftranslate_region_internal.
2983 Check if a character sequence at POS (POS_BYTE) matches an element
2984 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2985 element is found, return it. Otherwise return Qnil. */
2987 static Lisp_Object
2988 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
2989 Lisp_Object val)
2991 int initial_buf[16];
2992 int *buf = initial_buf;
2993 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
2994 int *bufalloc = 0;
2995 ptrdiff_t buf_used = 0;
2996 Lisp_Object result = Qnil;
2998 for (; CONSP (val); val = XCDR (val))
3000 Lisp_Object elt;
3001 ptrdiff_t len, i;
3003 elt = XCAR (val);
3004 if (! CONSP (elt))
3005 continue;
3006 elt = XCAR (elt);
3007 if (! VECTORP (elt))
3008 continue;
3009 len = ASIZE (elt);
3010 if (len <= end - pos)
3012 for (i = 0; i < len; i++)
3014 if (buf_used <= i)
3016 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3017 int len1;
3019 if (buf_used == buf_size)
3021 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3022 sizeof *bufalloc);
3023 if (buf == initial_buf)
3024 memcpy (bufalloc, buf, sizeof initial_buf);
3025 buf = bufalloc;
3027 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3028 pos_byte += len1;
3030 if (XINT (AREF (elt, i)) != buf[i])
3031 break;
3033 if (i == len)
3035 result = XCAR (val);
3036 break;
3041 xfree (bufalloc);
3042 return result;
3046 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3047 Stranslate_region_internal, 3, 3, 0,
3048 doc: /* Internal use only.
3049 From START to END, translate characters according to TABLE.
3050 TABLE is a string or a char-table; the Nth character in it is the
3051 mapping for the character with code N.
3052 It returns the number of characters changed. */)
3053 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3055 register unsigned char *tt; /* Trans table. */
3056 register int nc; /* New character. */
3057 int cnt; /* Number of changes made. */
3058 ptrdiff_t size; /* Size of translate table. */
3059 ptrdiff_t pos, pos_byte, end_pos;
3060 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3061 bool string_multibyte IF_LINT (= 0);
3063 validate_region (&start, &end);
3064 if (CHAR_TABLE_P (table))
3066 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3067 error ("Not a translation table");
3068 size = MAX_CHAR;
3069 tt = NULL;
3071 else
3073 CHECK_STRING (table);
3075 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3076 table = string_make_unibyte (table);
3077 string_multibyte = SCHARS (table) < SBYTES (table);
3078 size = SBYTES (table);
3079 tt = SDATA (table);
3082 pos = XINT (start);
3083 pos_byte = CHAR_TO_BYTE (pos);
3084 end_pos = XINT (end);
3085 modify_text (pos, end_pos);
3087 cnt = 0;
3088 for (; pos < end_pos; )
3090 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3091 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3092 int len, str_len;
3093 int oc;
3094 Lisp_Object val;
3096 if (multibyte)
3097 oc = STRING_CHAR_AND_LENGTH (p, len);
3098 else
3099 oc = *p, len = 1;
3100 if (oc < size)
3102 if (tt)
3104 /* Reload as signal_after_change in last iteration may GC. */
3105 tt = SDATA (table);
3106 if (string_multibyte)
3108 str = tt + string_char_to_byte (table, oc);
3109 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3111 else
3113 nc = tt[oc];
3114 if (! ASCII_CHAR_P (nc) && multibyte)
3116 str_len = BYTE8_STRING (nc, buf);
3117 str = buf;
3119 else
3121 str_len = 1;
3122 str = tt + oc;
3126 else
3128 nc = oc;
3129 val = CHAR_TABLE_REF (table, oc);
3130 if (CHARACTERP (val))
3132 nc = XFASTINT (val);
3133 str_len = CHAR_STRING (nc, buf);
3134 str = buf;
3136 else if (VECTORP (val) || (CONSP (val)))
3138 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3139 where TO is TO-CHAR or [TO-CHAR ...]. */
3140 nc = -1;
3144 if (nc != oc && nc >= 0)
3146 /* Simple one char to one char translation. */
3147 if (len != str_len)
3149 Lisp_Object string;
3151 /* This is less efficient, because it moves the gap,
3152 but it should handle multibyte characters correctly. */
3153 string = make_multibyte_string ((char *) str, 1, str_len);
3154 replace_range (pos, pos + 1, string, 1, 0, 1);
3155 len = str_len;
3157 else
3159 record_change (pos, 1);
3160 while (str_len-- > 0)
3161 *p++ = *str++;
3162 signal_after_change (pos, 1, 1);
3163 update_compositions (pos, pos + 1, CHECK_BORDER);
3165 ++cnt;
3167 else if (nc < 0)
3169 Lisp_Object string;
3171 if (CONSP (val))
3173 val = check_translation (pos, pos_byte, end_pos, val);
3174 if (NILP (val))
3176 pos_byte += len;
3177 pos++;
3178 continue;
3180 /* VAL is ([FROM-CHAR ...] . TO). */
3181 len = ASIZE (XCAR (val));
3182 val = XCDR (val);
3184 else
3185 len = 1;
3187 if (VECTORP (val))
3189 string = Fconcat (1, &val);
3191 else
3193 string = Fmake_string (make_number (1), val);
3195 replace_range (pos, pos + len, string, 1, 0, 1);
3196 pos_byte += SBYTES (string);
3197 pos += SCHARS (string);
3198 cnt += SCHARS (string);
3199 end_pos += SCHARS (string) - len;
3200 continue;
3203 pos_byte += len;
3204 pos++;
3207 return make_number (cnt);
3210 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3211 doc: /* Delete the text between START and END.
3212 If called interactively, delete the region between point and mark.
3213 This command deletes buffer text without modifying the kill ring. */)
3214 (Lisp_Object start, Lisp_Object end)
3216 validate_region (&start, &end);
3217 del_range (XINT (start), XINT (end));
3218 return Qnil;
3221 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3222 Sdelete_and_extract_region, 2, 2, 0,
3223 doc: /* Delete the text between START and END and return it. */)
3224 (Lisp_Object start, Lisp_Object end)
3226 validate_region (&start, &end);
3227 if (XINT (start) == XINT (end))
3228 return empty_unibyte_string;
3229 return del_range_1 (XINT (start), XINT (end), 1, 1);
3232 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3233 doc: /* Remove restrictions (narrowing) from current buffer.
3234 This allows the buffer's full text to be seen and edited. */)
3235 (void)
3237 if (BEG != BEGV || Z != ZV)
3238 current_buffer->clip_changed = 1;
3239 BEGV = BEG;
3240 BEGV_BYTE = BEG_BYTE;
3241 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3242 /* Changing the buffer bounds invalidates any recorded current column. */
3243 invalidate_current_column ();
3244 return Qnil;
3247 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3248 doc: /* Restrict editing in this buffer to the current region.
3249 The rest of the text becomes temporarily invisible and untouchable
3250 but is not deleted; if you save the buffer in a file, the invisible
3251 text is included in the file. \\[widen] makes all visible again.
3252 See also `save-restriction'.
3254 When calling from a program, pass two arguments; positions (integers
3255 or markers) bounding the text that should remain visible. */)
3256 (register Lisp_Object start, Lisp_Object end)
3258 CHECK_NUMBER_COERCE_MARKER (start);
3259 CHECK_NUMBER_COERCE_MARKER (end);
3261 if (XINT (start) > XINT (end))
3263 Lisp_Object tem;
3264 tem = start; start = end; end = tem;
3267 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3268 args_out_of_range (start, end);
3270 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3271 current_buffer->clip_changed = 1;
3273 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3274 SET_BUF_ZV (current_buffer, XFASTINT (end));
3275 if (PT < XFASTINT (start))
3276 SET_PT (XFASTINT (start));
3277 if (PT > XFASTINT (end))
3278 SET_PT (XFASTINT (end));
3279 /* Changing the buffer bounds invalidates any recorded current column. */
3280 invalidate_current_column ();
3281 return Qnil;
3284 Lisp_Object
3285 save_restriction_save (void)
3287 if (BEGV == BEG && ZV == Z)
3288 /* The common case that the buffer isn't narrowed.
3289 We return just the buffer object, which save_restriction_restore
3290 recognizes as meaning `no restriction'. */
3291 return Fcurrent_buffer ();
3292 else
3293 /* We have to save a restriction, so return a pair of markers, one
3294 for the beginning and one for the end. */
3296 Lisp_Object beg, end;
3298 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3299 end = build_marker (current_buffer, ZV, ZV_BYTE);
3301 /* END must move forward if text is inserted at its exact location. */
3302 XMARKER (end)->insertion_type = 1;
3304 return Fcons (beg, end);
3308 void
3309 save_restriction_restore (Lisp_Object data)
3311 struct buffer *cur = NULL;
3312 struct buffer *buf = (CONSP (data)
3313 ? XMARKER (XCAR (data))->buffer
3314 : XBUFFER (data));
3316 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3317 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3318 is the case if it is or has an indirect buffer), then make
3319 sure it is current before we update BEGV, so
3320 set_buffer_internal takes care of managing those markers. */
3321 cur = current_buffer;
3322 set_buffer_internal (buf);
3325 if (CONSP (data))
3326 /* A pair of marks bounding a saved restriction. */
3328 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3329 struct Lisp_Marker *end = XMARKER (XCDR (data));
3330 eassert (buf == end->buffer);
3332 if (buf /* Verify marker still points to a buffer. */
3333 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3334 /* The restriction has changed from the saved one, so restore
3335 the saved restriction. */
3337 ptrdiff_t pt = BUF_PT (buf);
3339 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3340 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3342 if (pt < beg->charpos || pt > end->charpos)
3343 /* The point is outside the new visible range, move it inside. */
3344 SET_BUF_PT_BOTH (buf,
3345 clip_to_bounds (beg->charpos, pt, end->charpos),
3346 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3347 end->bytepos));
3349 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3351 /* These aren't needed anymore, so don't wait for GC. */
3352 free_marker (XCAR (data));
3353 free_marker (XCDR (data));
3354 free_cons (XCONS (data));
3356 else
3357 /* A buffer, which means that there was no old restriction. */
3359 if (buf /* Verify marker still points to a buffer. */
3360 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3361 /* The buffer has been narrowed, get rid of the narrowing. */
3363 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3364 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3366 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3370 /* Changing the buffer bounds invalidates any recorded current column. */
3371 invalidate_current_column ();
3373 if (cur)
3374 set_buffer_internal (cur);
3377 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3378 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3379 The buffer's restrictions make parts of the beginning and end invisible.
3380 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3381 This special form, `save-restriction', saves the current buffer's restrictions
3382 when it is entered, and restores them when it is exited.
3383 So any `narrow-to-region' within BODY lasts only until the end of the form.
3384 The old restrictions settings are restored
3385 even in case of abnormal exit (throw or error).
3387 The value returned is the value of the last form in BODY.
3389 Note: if you are using both `save-excursion' and `save-restriction',
3390 use `save-excursion' outermost:
3391 (save-excursion (save-restriction ...))
3393 usage: (save-restriction &rest BODY) */)
3394 (Lisp_Object body)
3396 register Lisp_Object val;
3397 ptrdiff_t count = SPECPDL_INDEX ();
3399 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3400 val = Fprogn (body);
3401 return unbind_to (count, val);
3404 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3405 doc: /* Display a message at the bottom of the screen.
3406 The message also goes into the `*Messages*' buffer, if `message-log-max'
3407 is non-nil. (In keyboard macros, that's all it does.)
3408 Return the message.
3410 In batch mode, the message is printed to the standard error stream,
3411 followed by a newline.
3413 The first argument is a format control string, and the rest are data
3414 to be formatted under control of the string. See `format' for details.
3416 Note: Use (message "%s" VALUE) to print the value of expressions and
3417 variables to avoid accidentally interpreting `%' as format specifiers.
3419 If the first argument is nil or the empty string, the function clears
3420 any existing message; this lets the minibuffer contents show. See
3421 also `current-message'.
3423 usage: (message FORMAT-STRING &rest ARGS) */)
3424 (ptrdiff_t nargs, Lisp_Object *args)
3426 if (NILP (args[0])
3427 || (STRINGP (args[0])
3428 && SBYTES (args[0]) == 0))
3430 message1 (0);
3431 return args[0];
3433 else
3435 register Lisp_Object val;
3436 val = Fformat (nargs, args);
3437 message3 (val);
3438 return val;
3442 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3443 doc: /* Display a message, in a dialog box if possible.
3444 If a dialog box is not available, use the echo area.
3445 The first argument is a format control string, and the rest are data
3446 to be formatted under control of the string. See `format' for details.
3448 If the first argument is nil or the empty string, clear any existing
3449 message; let the minibuffer contents show.
3451 usage: (message-box FORMAT-STRING &rest ARGS) */)
3452 (ptrdiff_t nargs, Lisp_Object *args)
3454 if (NILP (args[0]))
3456 message1 (0);
3457 return Qnil;
3459 else
3461 Lisp_Object val = Fformat (nargs, args);
3462 Lisp_Object pane, menu;
3463 struct gcpro gcpro1;
3465 pane = list1 (Fcons (build_string ("OK"), Qt));
3466 GCPRO1 (pane);
3467 menu = Fcons (val, pane);
3468 Fx_popup_dialog (Qt, menu, Qt);
3469 UNGCPRO;
3470 return val;
3474 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3475 doc: /* Display a message in a dialog box or in the echo area.
3476 If this command was invoked with the mouse, use a dialog box if
3477 `use-dialog-box' is non-nil.
3478 Otherwise, use the echo area.
3479 The first argument is a format control string, and the rest are data
3480 to be formatted under control of the string. See `format' for details.
3482 If the first argument is nil or the empty string, clear any existing
3483 message; let the minibuffer contents show.
3485 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3486 (ptrdiff_t nargs, Lisp_Object *args)
3488 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3489 && use_dialog_box)
3490 return Fmessage_box (nargs, args);
3491 return Fmessage (nargs, args);
3494 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3495 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3496 (void)
3498 return current_message ();
3502 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3503 doc: /* Return a copy of STRING with text properties added.
3504 First argument is the string to copy.
3505 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3506 properties to add to the result.
3507 usage: (propertize STRING &rest PROPERTIES) */)
3508 (ptrdiff_t nargs, Lisp_Object *args)
3510 Lisp_Object properties, string;
3511 struct gcpro gcpro1, gcpro2;
3512 ptrdiff_t i;
3514 /* Number of args must be odd. */
3515 if ((nargs & 1) == 0)
3516 error ("Wrong number of arguments");
3518 properties = string = Qnil;
3519 GCPRO2 (properties, string);
3521 /* First argument must be a string. */
3522 CHECK_STRING (args[0]);
3523 string = Fcopy_sequence (args[0]);
3525 for (i = 1; i < nargs; i += 2)
3526 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3528 Fadd_text_properties (make_number (0),
3529 make_number (SCHARS (string)),
3530 properties, string);
3531 RETURN_UNGCPRO (string);
3534 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3535 doc: /* Format a string out of a format-string and arguments.
3536 The first argument is a format control string.
3537 The other arguments are substituted into it to make the result, a string.
3539 The format control string may contain %-sequences meaning to substitute
3540 the next available argument:
3542 %s means print a string argument. Actually, prints any object, with `princ'.
3543 %d means print as number in decimal (%o octal, %x hex).
3544 %X is like %x, but uses upper case.
3545 %e means print a number in exponential notation.
3546 %f means print a number in decimal-point notation.
3547 %g means print a number in exponential notation
3548 or decimal-point notation, whichever uses fewer characters.
3549 %c means print a number as a single character.
3550 %S means print any object as an s-expression (using `prin1').
3552 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3553 Use %% to put a single % into the output.
3555 A %-sequence may contain optional flag, width, and precision
3556 specifiers, as follows:
3558 %<flags><width><precision>character
3560 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3562 The + flag character inserts a + before any positive number, while a
3563 space inserts a space before any positive number; these flags only
3564 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3565 The - and 0 flags affect the width specifier, as described below.
3567 The # flag means to use an alternate display form for %o, %x, %X, %e,
3568 %f, and %g sequences: for %o, it ensures that the result begins with
3569 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3570 for %e, %f, and %g, it causes a decimal point to be included even if
3571 the precision is zero.
3573 The width specifier supplies a lower limit for the length of the
3574 printed representation. The padding, if any, normally goes on the
3575 left, but it goes on the right if the - flag is present. The padding
3576 character is normally a space, but it is 0 if the 0 flag is present.
3577 The 0 flag is ignored if the - flag is present, or the format sequence
3578 is something other than %d, %e, %f, and %g.
3580 For %e, %f, and %g sequences, the number after the "." in the
3581 precision specifier says how many decimal places to show; if zero, the
3582 decimal point itself is omitted. For %s and %S, the precision
3583 specifier truncates the string to the given width.
3585 usage: (format STRING &rest OBJECTS) */)
3586 (ptrdiff_t nargs, Lisp_Object *args)
3588 ptrdiff_t n; /* The number of the next arg to substitute. */
3589 char initial_buffer[4000];
3590 char *buf = initial_buffer;
3591 ptrdiff_t bufsize = sizeof initial_buffer;
3592 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3593 char *p;
3594 ptrdiff_t buf_save_value_index IF_LINT (= 0);
3595 char *format, *end, *format_start;
3596 ptrdiff_t formatlen, nchars;
3597 /* True if the format is multibyte. */
3598 bool multibyte_format = 0;
3599 /* True if the output should be a multibyte string,
3600 which is true if any of the inputs is one. */
3601 bool multibyte = 0;
3602 /* When we make a multibyte string, we must pay attention to the
3603 byte combining problem, i.e., a byte may be combined with a
3604 multibyte character of the previous string. This flag tells if we
3605 must consider such a situation or not. */
3606 bool maybe_combine_byte;
3607 Lisp_Object val;
3608 bool arg_intervals = 0;
3609 USE_SAFE_ALLOCA;
3611 /* discarded[I] is 1 if byte I of the format
3612 string was not copied into the output.
3613 It is 2 if byte I was not the first byte of its character. */
3614 char *discarded;
3616 /* Each element records, for one argument,
3617 the start and end bytepos in the output string,
3618 whether the argument has been converted to string (e.g., due to "%S"),
3619 and whether the argument is a string with intervals.
3620 info[0] is unused. Unused elements have -1 for start. */
3621 struct info
3623 ptrdiff_t start, end;
3624 bool_bf converted_to_string : 1;
3625 bool_bf intervals : 1;
3626 } *info = 0;
3628 /* It should not be necessary to GCPRO ARGS, because
3629 the caller in the interpreter should take care of that. */
3631 CHECK_STRING (args[0]);
3632 format_start = SSDATA (args[0]);
3633 formatlen = SBYTES (args[0]);
3635 /* Allocate the info and discarded tables. */
3637 ptrdiff_t i;
3638 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3639 memory_full (SIZE_MAX);
3640 info = SAFE_ALLOCA ((nargs + 1) * sizeof *info + formatlen);
3641 discarded = (char *) &info[nargs + 1];
3642 for (i = 0; i < nargs + 1; i++)
3644 info[i].start = -1;
3645 info[i].intervals = info[i].converted_to_string = 0;
3647 memset (discarded, 0, formatlen);
3650 /* Try to determine whether the result should be multibyte.
3651 This is not always right; sometimes the result needs to be multibyte
3652 because of an object that we will pass through prin1,
3653 and in that case, we won't know it here. */
3654 multibyte_format = STRING_MULTIBYTE (args[0]);
3655 multibyte = multibyte_format;
3656 for (n = 1; !multibyte && n < nargs; n++)
3657 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3658 multibyte = 1;
3660 /* If we start out planning a unibyte result,
3661 then discover it has to be multibyte, we jump back to retry. */
3662 retry:
3664 p = buf;
3665 nchars = 0;
3666 n = 0;
3668 /* Scan the format and store result in BUF. */
3669 format = format_start;
3670 end = format + formatlen;
3671 maybe_combine_byte = 0;
3673 while (format != end)
3675 /* The values of N and FORMAT when the loop body is entered. */
3676 ptrdiff_t n0 = n;
3677 char *format0 = format;
3679 /* Bytes needed to represent the output of this conversion. */
3680 ptrdiff_t convbytes;
3682 if (*format == '%')
3684 /* General format specifications look like
3686 '%' [flags] [field-width] [precision] format
3688 where
3690 flags ::= [-+0# ]+
3691 field-width ::= [0-9]+
3692 precision ::= '.' [0-9]*
3694 If a field-width is specified, it specifies to which width
3695 the output should be padded with blanks, if the output
3696 string is shorter than field-width.
3698 If precision is specified, it specifies the number of
3699 digits to print after the '.' for floats, or the max.
3700 number of chars to print from a string. */
3702 bool minus_flag = 0;
3703 bool plus_flag = 0;
3704 bool space_flag = 0;
3705 bool sharp_flag = 0;
3706 bool zero_flag = 0;
3707 ptrdiff_t field_width;
3708 bool precision_given;
3709 uintmax_t precision = UINTMAX_MAX;
3710 char *num_end;
3711 char conversion;
3713 while (1)
3715 switch (*++format)
3717 case '-': minus_flag = 1; continue;
3718 case '+': plus_flag = 1; continue;
3719 case ' ': space_flag = 1; continue;
3720 case '#': sharp_flag = 1; continue;
3721 case '0': zero_flag = 1; continue;
3723 break;
3726 /* Ignore flags when sprintf ignores them. */
3727 space_flag &= ~ plus_flag;
3728 zero_flag &= ~ minus_flag;
3731 uintmax_t w = strtoumax (format, &num_end, 10);
3732 if (max_bufsize <= w)
3733 string_overflow ();
3734 field_width = w;
3736 precision_given = *num_end == '.';
3737 if (precision_given)
3738 precision = strtoumax (num_end + 1, &num_end, 10);
3739 format = num_end;
3741 if (format == end)
3742 error ("Format string ends in middle of format specifier");
3744 memset (&discarded[format0 - format_start], 1, format - format0);
3745 conversion = *format;
3746 if (conversion == '%')
3747 goto copy_char;
3748 discarded[format - format_start] = 1;
3749 format++;
3751 ++n;
3752 if (! (n < nargs))
3753 error ("Not enough arguments for format string");
3755 /* For 'S', prin1 the argument, and then treat like 's'.
3756 For 's', princ any argument that is not a string or
3757 symbol. But don't do this conversion twice, which might
3758 happen after retrying. */
3759 if ((conversion == 'S'
3760 || (conversion == 's'
3761 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3763 if (! info[n].converted_to_string)
3765 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3766 args[n] = Fprin1_to_string (args[n], noescape);
3767 info[n].converted_to_string = 1;
3768 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3770 multibyte = 1;
3771 goto retry;
3774 conversion = 's';
3776 else if (conversion == 'c')
3778 if (FLOATP (args[n]))
3780 double d = XFLOAT_DATA (args[n]);
3781 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3784 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3786 if (!multibyte)
3788 multibyte = 1;
3789 goto retry;
3791 args[n] = Fchar_to_string (args[n]);
3792 info[n].converted_to_string = 1;
3795 if (info[n].converted_to_string)
3796 conversion = 's';
3797 zero_flag = 0;
3800 if (SYMBOLP (args[n]))
3802 args[n] = SYMBOL_NAME (args[n]);
3803 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3805 multibyte = 1;
3806 goto retry;
3810 if (conversion == 's')
3812 /* handle case (precision[n] >= 0) */
3814 ptrdiff_t width, padding, nbytes;
3815 ptrdiff_t nchars_string;
3817 ptrdiff_t prec = -1;
3818 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
3819 prec = precision;
3821 /* lisp_string_width ignores a precision of 0, but GNU
3822 libc functions print 0 characters when the precision
3823 is 0. Imitate libc behavior here. Changing
3824 lisp_string_width is the right thing, and will be
3825 done, but meanwhile we work with it. */
3827 if (prec == 0)
3828 width = nchars_string = nbytes = 0;
3829 else
3831 ptrdiff_t nch, nby;
3832 width = lisp_string_width (args[n], prec, &nch, &nby);
3833 if (prec < 0)
3835 nchars_string = SCHARS (args[n]);
3836 nbytes = SBYTES (args[n]);
3838 else
3840 nchars_string = nch;
3841 nbytes = nby;
3845 convbytes = nbytes;
3846 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
3847 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
3849 padding = width < field_width ? field_width - width : 0;
3851 if (max_bufsize - padding <= convbytes)
3852 string_overflow ();
3853 convbytes += padding;
3854 if (convbytes <= buf + bufsize - p)
3856 if (! minus_flag)
3858 memset (p, ' ', padding);
3859 p += padding;
3860 nchars += padding;
3863 if (p > buf
3864 && multibyte
3865 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
3866 && STRING_MULTIBYTE (args[n])
3867 && !CHAR_HEAD_P (SREF (args[n], 0)))
3868 maybe_combine_byte = 1;
3870 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3871 nbytes,
3872 STRING_MULTIBYTE (args[n]), multibyte);
3874 info[n].start = nchars;
3875 nchars += nchars_string;
3876 info[n].end = nchars;
3878 if (minus_flag)
3880 memset (p, ' ', padding);
3881 p += padding;
3882 nchars += padding;
3885 /* If this argument has text properties, record where
3886 in the result string it appears. */
3887 if (string_intervals (args[n]))
3888 info[n].intervals = arg_intervals = 1;
3890 continue;
3893 else if (! (conversion == 'c' || conversion == 'd'
3894 || conversion == 'e' || conversion == 'f'
3895 || conversion == 'g' || conversion == 'i'
3896 || conversion == 'o' || conversion == 'x'
3897 || conversion == 'X'))
3898 error ("Invalid format operation %%%c",
3899 STRING_CHAR ((unsigned char *) format - 1));
3900 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
3901 error ("Format specifier doesn't match argument type");
3902 else
3904 enum
3906 /* Maximum precision for a %f conversion such that the
3907 trailing output digit might be nonzero. Any precision
3908 larger than this will not yield useful information. */
3909 USEFUL_PRECISION_MAX =
3910 ((1 - DBL_MIN_EXP)
3911 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
3912 : FLT_RADIX == 16 ? 4
3913 : -1)),
3915 /* Maximum number of bytes generated by any format, if
3916 precision is no more than USEFUL_PRECISION_MAX.
3917 On all practical hosts, %f is the worst case. */
3918 SPRINTF_BUFSIZE =
3919 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
3921 /* Length of pM (that is, of pMd without the
3922 trailing "d"). */
3923 pMlen = sizeof pMd - 2
3925 verify (USEFUL_PRECISION_MAX > 0);
3927 int prec;
3928 ptrdiff_t padding, sprintf_bytes;
3929 uintmax_t excess_precision, numwidth;
3930 uintmax_t leading_zeros = 0, trailing_zeros = 0;
3932 char sprintf_buf[SPRINTF_BUFSIZE];
3934 /* Copy of conversion specification, modified somewhat.
3935 At most three flags F can be specified at once. */
3936 char convspec[sizeof "%FFF.*d" + pMlen];
3938 /* Avoid undefined behavior in underlying sprintf. */
3939 if (conversion == 'd' || conversion == 'i')
3940 sharp_flag = 0;
3942 /* Create the copy of the conversion specification, with
3943 any width and precision removed, with ".*" inserted,
3944 and with pM inserted for integer formats. */
3946 char *f = convspec;
3947 *f++ = '%';
3948 *f = '-'; f += minus_flag;
3949 *f = '+'; f += plus_flag;
3950 *f = ' '; f += space_flag;
3951 *f = '#'; f += sharp_flag;
3952 *f = '0'; f += zero_flag;
3953 *f++ = '.';
3954 *f++ = '*';
3955 if (conversion == 'd' || conversion == 'i'
3956 || conversion == 'o' || conversion == 'x'
3957 || conversion == 'X')
3959 memcpy (f, pMd, pMlen);
3960 f += pMlen;
3961 zero_flag &= ~ precision_given;
3963 *f++ = conversion;
3964 *f = '\0';
3967 prec = -1;
3968 if (precision_given)
3969 prec = min (precision, USEFUL_PRECISION_MAX);
3971 /* Use sprintf to format this number into sprintf_buf. Omit
3972 padding and excess precision, though, because sprintf limits
3973 output length to INT_MAX.
3975 There are four types of conversion: double, unsigned
3976 char (passed as int), wide signed int, and wide
3977 unsigned int. Treat them separately because the
3978 sprintf ABI is sensitive to which type is passed. Be
3979 careful about integer overflow, NaNs, infinities, and
3980 conversions; for example, the min and max macros are
3981 not suitable here. */
3982 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
3984 double x = (INTEGERP (args[n])
3985 ? XINT (args[n])
3986 : XFLOAT_DATA (args[n]));
3987 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
3989 else if (conversion == 'c')
3991 /* Don't use sprintf here, as it might mishandle prec. */
3992 sprintf_buf[0] = XINT (args[n]);
3993 sprintf_bytes = prec != 0;
3995 else if (conversion == 'd')
3997 /* For float, maybe we should use "%1.0f"
3998 instead so it also works for values outside
3999 the integer range. */
4000 printmax_t x;
4001 if (INTEGERP (args[n]))
4002 x = XINT (args[n]);
4003 else
4005 double d = XFLOAT_DATA (args[n]);
4006 if (d < 0)
4008 x = TYPE_MINIMUM (printmax_t);
4009 if (x < d)
4010 x = d;
4012 else
4014 x = TYPE_MAXIMUM (printmax_t);
4015 if (d < x)
4016 x = d;
4019 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4021 else
4023 /* Don't sign-extend for octal or hex printing. */
4024 uprintmax_t x;
4025 if (INTEGERP (args[n]))
4026 x = XUINT (args[n]);
4027 else
4029 double d = XFLOAT_DATA (args[n]);
4030 if (d < 0)
4031 x = 0;
4032 else
4034 x = TYPE_MAXIMUM (uprintmax_t);
4035 if (d < x)
4036 x = d;
4039 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4042 /* Now the length of the formatted item is known, except it omits
4043 padding and excess precision. Deal with excess precision
4044 first. This happens only when the format specifies
4045 ridiculously large precision. */
4046 excess_precision = precision - prec;
4047 if (excess_precision)
4049 if (conversion == 'e' || conversion == 'f'
4050 || conversion == 'g')
4052 if ((conversion == 'g' && ! sharp_flag)
4053 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4054 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4055 excess_precision = 0;
4056 else
4058 if (conversion == 'g')
4060 char *dot = strchr (sprintf_buf, '.');
4061 if (!dot)
4062 excess_precision = 0;
4065 trailing_zeros = excess_precision;
4067 else
4068 leading_zeros = excess_precision;
4071 /* Compute the total bytes needed for this item, including
4072 excess precision and padding. */
4073 numwidth = sprintf_bytes + excess_precision;
4074 padding = numwidth < field_width ? field_width - numwidth : 0;
4075 if (max_bufsize - sprintf_bytes <= excess_precision
4076 || max_bufsize - padding <= numwidth)
4077 string_overflow ();
4078 convbytes = numwidth + padding;
4080 if (convbytes <= buf + bufsize - p)
4082 /* Copy the formatted item from sprintf_buf into buf,
4083 inserting padding and excess-precision zeros. */
4085 char *src = sprintf_buf;
4086 char src0 = src[0];
4087 int exponent_bytes = 0;
4088 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4089 int significand_bytes;
4090 if (zero_flag
4091 && ((src[signedp] >= '0' && src[signedp] <= '9')
4092 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4093 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4095 leading_zeros += padding;
4096 padding = 0;
4099 if (excess_precision
4100 && (conversion == 'e' || conversion == 'g'))
4102 char *e = strchr (src, 'e');
4103 if (e)
4104 exponent_bytes = src + sprintf_bytes - e;
4107 if (! minus_flag)
4109 memset (p, ' ', padding);
4110 p += padding;
4111 nchars += padding;
4114 *p = src0;
4115 src += signedp;
4116 p += signedp;
4117 memset (p, '0', leading_zeros);
4118 p += leading_zeros;
4119 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4120 memcpy (p, src, significand_bytes);
4121 p += significand_bytes;
4122 src += significand_bytes;
4123 memset (p, '0', trailing_zeros);
4124 p += trailing_zeros;
4125 memcpy (p, src, exponent_bytes);
4126 p += exponent_bytes;
4128 info[n].start = nchars;
4129 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4130 info[n].end = nchars;
4132 if (minus_flag)
4134 memset (p, ' ', padding);
4135 p += padding;
4136 nchars += padding;
4139 continue;
4143 else
4144 copy_char:
4146 /* Copy a single character from format to buf. */
4148 char *src = format;
4149 unsigned char str[MAX_MULTIBYTE_LENGTH];
4151 if (multibyte_format)
4153 /* Copy a whole multibyte character. */
4154 if (p > buf
4155 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4156 && !CHAR_HEAD_P (*format))
4157 maybe_combine_byte = 1;
4160 format++;
4161 while (! CHAR_HEAD_P (*format));
4163 convbytes = format - src;
4164 memset (&discarded[src + 1 - format_start], 2, convbytes - 1);
4166 else
4168 unsigned char uc = *format++;
4169 if (! multibyte || ASCII_CHAR_P (uc))
4170 convbytes = 1;
4171 else
4173 int c = BYTE8_TO_CHAR (uc);
4174 convbytes = CHAR_STRING (c, str);
4175 src = (char *) str;
4179 if (convbytes <= buf + bufsize - p)
4181 memcpy (p, src, convbytes);
4182 p += convbytes;
4183 nchars++;
4184 continue;
4188 /* There wasn't enough room to store this conversion or single
4189 character. CONVBYTES says how much room is needed. Allocate
4190 enough room (and then some) and do it again. */
4192 ptrdiff_t used = p - buf;
4194 if (max_bufsize - used < convbytes)
4195 string_overflow ();
4196 bufsize = used + convbytes;
4197 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4199 if (buf == initial_buffer)
4201 buf = xmalloc (bufsize);
4202 sa_must_free = true;
4203 buf_save_value_index = SPECPDL_INDEX ();
4204 record_unwind_protect_ptr (xfree, buf);
4205 memcpy (buf, initial_buffer, used);
4207 else
4209 buf = xrealloc (buf, bufsize);
4210 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4213 p = buf + used;
4216 format = format0;
4217 n = n0;
4220 if (bufsize < p - buf)
4221 emacs_abort ();
4223 if (maybe_combine_byte)
4224 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4225 val = make_specified_string (buf, nchars, p - buf, multibyte);
4227 /* If we allocated BUF with malloc, free it too. */
4228 SAFE_FREE ();
4230 /* If the format string has text properties, or any of the string
4231 arguments has text properties, set up text properties of the
4232 result string. */
4234 if (string_intervals (args[0]) || arg_intervals)
4236 Lisp_Object len, new_len, props;
4237 struct gcpro gcpro1;
4239 /* Add text properties from the format string. */
4240 len = make_number (SCHARS (args[0]));
4241 props = text_property_list (args[0], make_number (0), len, Qnil);
4242 GCPRO1 (props);
4244 if (CONSP (props))
4246 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4247 ptrdiff_t argn = 1;
4248 Lisp_Object list;
4250 /* Adjust the bounds of each text property
4251 to the proper start and end in the output string. */
4253 /* Put the positions in PROPS in increasing order, so that
4254 we can do (effectively) one scan through the position
4255 space of the format string. */
4256 props = Fnreverse (props);
4258 /* BYTEPOS is the byte position in the format string,
4259 POSITION is the untranslated char position in it,
4260 TRANSLATED is the translated char position in BUF,
4261 and ARGN is the number of the next arg we will come to. */
4262 for (list = props; CONSP (list); list = XCDR (list))
4264 Lisp_Object item;
4265 ptrdiff_t pos;
4267 item = XCAR (list);
4269 /* First adjust the property start position. */
4270 pos = XINT (XCAR (item));
4272 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4273 up to this position. */
4274 for (; position < pos; bytepos++)
4276 if (! discarded[bytepos])
4277 position++, translated++;
4278 else if (discarded[bytepos] == 1)
4280 position++;
4281 if (translated == info[argn].start)
4283 translated += info[argn].end - info[argn].start;
4284 argn++;
4289 XSETCAR (item, make_number (translated));
4291 /* Likewise adjust the property end position. */
4292 pos = XINT (XCAR (XCDR (item)));
4294 for (; position < pos; bytepos++)
4296 if (! discarded[bytepos])
4297 position++, translated++;
4298 else if (discarded[bytepos] == 1)
4300 position++;
4301 if (translated == info[argn].start)
4303 translated += info[argn].end - info[argn].start;
4304 argn++;
4309 XSETCAR (XCDR (item), make_number (translated));
4312 add_text_properties_from_list (val, props, make_number (0));
4315 /* Add text properties from arguments. */
4316 if (arg_intervals)
4317 for (n = 1; n < nargs; ++n)
4318 if (info[n].intervals)
4320 len = make_number (SCHARS (args[n]));
4321 new_len = make_number (info[n].end - info[n].start);
4322 props = text_property_list (args[n], make_number (0), len, Qnil);
4323 props = extend_property_ranges (props, new_len);
4324 /* If successive arguments have properties, be sure that
4325 the value of `composition' property be the copy. */
4326 if (n > 1 && info[n - 1].end)
4327 make_composition_value_copy (props);
4328 add_text_properties_from_list (val, props,
4329 make_number (info[n].start));
4332 UNGCPRO;
4335 return val;
4338 Lisp_Object
4339 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4341 AUTO_STRING (format, string1);
4342 return Fformat (3, (Lisp_Object []) {format, arg0, arg1});
4345 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4346 doc: /* Return t if two characters match, optionally ignoring case.
4347 Both arguments must be characters (i.e. integers).
4348 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4349 (register Lisp_Object c1, Lisp_Object c2)
4351 int i1, i2;
4352 /* Check they're chars, not just integers, otherwise we could get array
4353 bounds violations in downcase. */
4354 CHECK_CHARACTER (c1);
4355 CHECK_CHARACTER (c2);
4357 if (XINT (c1) == XINT (c2))
4358 return Qt;
4359 if (NILP (BVAR (current_buffer, case_fold_search)))
4360 return Qnil;
4362 i1 = XFASTINT (c1);
4363 i2 = XFASTINT (c2);
4365 /* FIXME: It is possible to compare multibyte characters even when
4366 the current buffer is unibyte. Unfortunately this is ambiguous
4367 for characters between 128 and 255, as they could be either
4368 eight-bit raw bytes or Latin-1 characters. Assume the former for
4369 now. See Bug#17011, and also see casefiddle.c's casify_object,
4370 which has a similar problem. */
4371 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4373 if (SINGLE_BYTE_CHAR_P (i1))
4374 i1 = UNIBYTE_TO_CHAR (i1);
4375 if (SINGLE_BYTE_CHAR_P (i2))
4376 i2 = UNIBYTE_TO_CHAR (i2);
4379 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4382 /* Transpose the markers in two regions of the current buffer, and
4383 adjust the ones between them if necessary (i.e.: if the regions
4384 differ in size).
4386 START1, END1 are the character positions of the first region.
4387 START1_BYTE, END1_BYTE are the byte positions.
4388 START2, END2 are the character positions of the second region.
4389 START2_BYTE, END2_BYTE are the byte positions.
4391 Traverses the entire marker list of the buffer to do so, adding an
4392 appropriate amount to some, subtracting from some, and leaving the
4393 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4395 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4397 static void
4398 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4399 ptrdiff_t start2, ptrdiff_t end2,
4400 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4401 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4403 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4404 register struct Lisp_Marker *marker;
4406 /* Update point as if it were a marker. */
4407 if (PT < start1)
4409 else if (PT < end1)
4410 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4411 PT_BYTE + (end2_byte - end1_byte));
4412 else if (PT < start2)
4413 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4414 (PT_BYTE + (end2_byte - start2_byte)
4415 - (end1_byte - start1_byte)));
4416 else if (PT < end2)
4417 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4418 PT_BYTE - (start2_byte - start1_byte));
4420 /* We used to adjust the endpoints here to account for the gap, but that
4421 isn't good enough. Even if we assume the caller has tried to move the
4422 gap out of our way, it might still be at start1 exactly, for example;
4423 and that places it `inside' the interval, for our purposes. The amount
4424 of adjustment is nontrivial if there's a `denormalized' marker whose
4425 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4426 the dirty work to Fmarker_position, below. */
4428 /* The difference between the region's lengths */
4429 diff = (end2 - start2) - (end1 - start1);
4430 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4432 /* For shifting each marker in a region by the length of the other
4433 region plus the distance between the regions. */
4434 amt1 = (end2 - start2) + (start2 - end1);
4435 amt2 = (end1 - start1) + (start2 - end1);
4436 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4437 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4439 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4441 mpos = marker->bytepos;
4442 if (mpos >= start1_byte && mpos < end2_byte)
4444 if (mpos < end1_byte)
4445 mpos += amt1_byte;
4446 else if (mpos < start2_byte)
4447 mpos += diff_byte;
4448 else
4449 mpos -= amt2_byte;
4450 marker->bytepos = mpos;
4452 mpos = marker->charpos;
4453 if (mpos >= start1 && mpos < end2)
4455 if (mpos < end1)
4456 mpos += amt1;
4457 else if (mpos < start2)
4458 mpos += diff;
4459 else
4460 mpos -= amt2;
4462 marker->charpos = mpos;
4466 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4467 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4468 The regions should not be overlapping, because the size of the buffer is
4469 never changed in a transposition.
4471 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4472 any markers that happen to be located in the regions.
4474 Transposing beyond buffer boundaries is an error. */)
4475 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4477 register ptrdiff_t start1, end1, start2, end2;
4478 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4479 ptrdiff_t gap, len1, len_mid, len2;
4480 unsigned char *start1_addr, *start2_addr, *temp;
4482 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4483 Lisp_Object buf;
4485 XSETBUFFER (buf, current_buffer);
4486 cur_intv = buffer_intervals (current_buffer);
4488 validate_region (&startr1, &endr1);
4489 validate_region (&startr2, &endr2);
4491 start1 = XFASTINT (startr1);
4492 end1 = XFASTINT (endr1);
4493 start2 = XFASTINT (startr2);
4494 end2 = XFASTINT (endr2);
4495 gap = GPT;
4497 /* Swap the regions if they're reversed. */
4498 if (start2 < end1)
4500 register ptrdiff_t glumph = start1;
4501 start1 = start2;
4502 start2 = glumph;
4503 glumph = end1;
4504 end1 = end2;
4505 end2 = glumph;
4508 len1 = end1 - start1;
4509 len2 = end2 - start2;
4511 if (start2 < end1)
4512 error ("Transposed regions overlap");
4513 /* Nothing to change for adjacent regions with one being empty */
4514 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4515 return Qnil;
4517 /* The possibilities are:
4518 1. Adjacent (contiguous) regions, or separate but equal regions
4519 (no, really equal, in this case!), or
4520 2. Separate regions of unequal size.
4522 The worst case is usually No. 2. It means that (aside from
4523 potential need for getting the gap out of the way), there also
4524 needs to be a shifting of the text between the two regions. So
4525 if they are spread far apart, we are that much slower... sigh. */
4527 /* It must be pointed out that the really studly thing to do would
4528 be not to move the gap at all, but to leave it in place and work
4529 around it if necessary. This would be extremely efficient,
4530 especially considering that people are likely to do
4531 transpositions near where they are working interactively, which
4532 is exactly where the gap would be found. However, such code
4533 would be much harder to write and to read. So, if you are
4534 reading this comment and are feeling squirrely, by all means have
4535 a go! I just didn't feel like doing it, so I will simply move
4536 the gap the minimum distance to get it out of the way, and then
4537 deal with an unbroken array. */
4539 start1_byte = CHAR_TO_BYTE (start1);
4540 end2_byte = CHAR_TO_BYTE (end2);
4542 /* Make sure the gap won't interfere, by moving it out of the text
4543 we will operate on. */
4544 if (start1 < gap && gap < end2)
4546 if (gap - start1 < end2 - gap)
4547 move_gap_both (start1, start1_byte);
4548 else
4549 move_gap_both (end2, end2_byte);
4552 start2_byte = CHAR_TO_BYTE (start2);
4553 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4554 len2_byte = end2_byte - start2_byte;
4556 #ifdef BYTE_COMBINING_DEBUG
4557 if (end1 == start2)
4559 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4560 len2_byte, start1, start1_byte)
4561 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4562 len1_byte, end2, start2_byte + len2_byte)
4563 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4564 len1_byte, end2, start2_byte + len2_byte))
4565 emacs_abort ();
4567 else
4569 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4570 len2_byte, start1, start1_byte)
4571 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4572 len1_byte, start2, start2_byte)
4573 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4574 len2_byte, end1, start1_byte + len1_byte)
4575 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4576 len1_byte, end2, start2_byte + len2_byte))
4577 emacs_abort ();
4579 #endif
4581 /* Hmmm... how about checking to see if the gap is large
4582 enough to use as the temporary storage? That would avoid an
4583 allocation... interesting. Later, don't fool with it now. */
4585 /* Working without memmove, for portability (sigh), so must be
4586 careful of overlapping subsections of the array... */
4588 if (end1 == start2) /* adjacent regions */
4590 modify_text (start1, end2);
4591 record_change (start1, len1 + len2);
4593 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4594 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4595 /* Don't use Fset_text_properties: that can cause GC, which can
4596 clobber objects stored in the tmp_intervals. */
4597 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4598 if (tmp_interval3)
4599 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4601 USE_SAFE_ALLOCA;
4603 /* First region smaller than second. */
4604 if (len1_byte < len2_byte)
4606 temp = SAFE_ALLOCA (len2_byte);
4608 /* Don't precompute these addresses. We have to compute them
4609 at the last minute, because the relocating allocator might
4610 have moved the buffer around during the xmalloc. */
4611 start1_addr = BYTE_POS_ADDR (start1_byte);
4612 start2_addr = BYTE_POS_ADDR (start2_byte);
4614 memcpy (temp, start2_addr, len2_byte);
4615 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4616 memcpy (start1_addr, temp, len2_byte);
4618 else
4619 /* First region not smaller than second. */
4621 temp = SAFE_ALLOCA (len1_byte);
4622 start1_addr = BYTE_POS_ADDR (start1_byte);
4623 start2_addr = BYTE_POS_ADDR (start2_byte);
4624 memcpy (temp, start1_addr, len1_byte);
4625 memcpy (start1_addr, start2_addr, len2_byte);
4626 memcpy (start1_addr + len2_byte, temp, len1_byte);
4629 SAFE_FREE ();
4630 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4631 len1, current_buffer, 0);
4632 graft_intervals_into_buffer (tmp_interval2, start1,
4633 len2, current_buffer, 0);
4634 update_compositions (start1, start1 + len2, CHECK_BORDER);
4635 update_compositions (start1 + len2, end2, CHECK_TAIL);
4637 /* Non-adjacent regions, because end1 != start2, bleagh... */
4638 else
4640 len_mid = start2_byte - (start1_byte + len1_byte);
4642 if (len1_byte == len2_byte)
4643 /* Regions are same size, though, how nice. */
4645 USE_SAFE_ALLOCA;
4647 modify_text (start1, end1);
4648 modify_text (start2, end2);
4649 record_change (start1, len1);
4650 record_change (start2, len2);
4651 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4652 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4654 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4655 if (tmp_interval3)
4656 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4658 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4659 if (tmp_interval3)
4660 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4662 temp = SAFE_ALLOCA (len1_byte);
4663 start1_addr = BYTE_POS_ADDR (start1_byte);
4664 start2_addr = BYTE_POS_ADDR (start2_byte);
4665 memcpy (temp, start1_addr, len1_byte);
4666 memcpy (start1_addr, start2_addr, len2_byte);
4667 memcpy (start2_addr, temp, len1_byte);
4668 SAFE_FREE ();
4670 graft_intervals_into_buffer (tmp_interval1, start2,
4671 len1, current_buffer, 0);
4672 graft_intervals_into_buffer (tmp_interval2, start1,
4673 len2, current_buffer, 0);
4676 else if (len1_byte < len2_byte) /* Second region larger than first */
4677 /* Non-adjacent & unequal size, area between must also be shifted. */
4679 USE_SAFE_ALLOCA;
4681 modify_text (start1, end2);
4682 record_change (start1, (end2 - start1));
4683 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4684 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4685 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4687 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4688 if (tmp_interval3)
4689 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4691 /* holds region 2 */
4692 temp = SAFE_ALLOCA (len2_byte);
4693 start1_addr = BYTE_POS_ADDR (start1_byte);
4694 start2_addr = BYTE_POS_ADDR (start2_byte);
4695 memcpy (temp, start2_addr, len2_byte);
4696 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4697 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4698 memcpy (start1_addr, temp, len2_byte);
4699 SAFE_FREE ();
4701 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4702 len1, current_buffer, 0);
4703 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4704 len_mid, current_buffer, 0);
4705 graft_intervals_into_buffer (tmp_interval2, start1,
4706 len2, current_buffer, 0);
4708 else
4709 /* Second region smaller than first. */
4711 USE_SAFE_ALLOCA;
4713 record_change (start1, (end2 - start1));
4714 modify_text (start1, end2);
4716 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4717 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4718 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4720 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4721 if (tmp_interval3)
4722 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4724 /* holds region 1 */
4725 temp = SAFE_ALLOCA (len1_byte);
4726 start1_addr = BYTE_POS_ADDR (start1_byte);
4727 start2_addr = BYTE_POS_ADDR (start2_byte);
4728 memcpy (temp, start1_addr, len1_byte);
4729 memcpy (start1_addr, start2_addr, len2_byte);
4730 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4731 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4732 SAFE_FREE ();
4734 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4735 len1, current_buffer, 0);
4736 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4737 len_mid, current_buffer, 0);
4738 graft_intervals_into_buffer (tmp_interval2, start1,
4739 len2, current_buffer, 0);
4742 update_compositions (start1, start1 + len2, CHECK_BORDER);
4743 update_compositions (end2 - len1, end2, CHECK_BORDER);
4746 /* When doing multiple transpositions, it might be nice
4747 to optimize this. Perhaps the markers in any one buffer
4748 should be organized in some sorted data tree. */
4749 if (NILP (leave_markers))
4751 transpose_markers (start1, end1, start2, end2,
4752 start1_byte, start1_byte + len1_byte,
4753 start2_byte, start2_byte + len2_byte);
4754 fix_start_end_in_overlays (start1, end2);
4757 signal_after_change (start1, end2 - start1, end2 - start1);
4758 return Qnil;
4762 void
4763 syms_of_editfns (void)
4765 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4767 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4768 doc: /* Non-nil means text motion commands don't notice fields. */);
4769 Vinhibit_field_text_motion = Qnil;
4771 DEFVAR_LISP ("buffer-access-fontify-functions",
4772 Vbuffer_access_fontify_functions,
4773 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4774 Each function is called with two arguments which specify the range
4775 of the buffer being accessed. */);
4776 Vbuffer_access_fontify_functions = Qnil;
4779 Lisp_Object obuf;
4780 obuf = Fcurrent_buffer ();
4781 /* Do this here, because init_buffer_once is too early--it won't work. */
4782 Fset_buffer (Vprin1_to_string_buffer);
4783 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4784 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4785 Qnil);
4786 Fset_buffer (obuf);
4789 DEFVAR_LISP ("buffer-access-fontified-property",
4790 Vbuffer_access_fontified_property,
4791 doc: /* Property which (if non-nil) indicates text has been fontified.
4792 `buffer-substring' need not call the `buffer-access-fontify-functions'
4793 functions if all the text being accessed has this property. */);
4794 Vbuffer_access_fontified_property = Qnil;
4796 DEFVAR_LISP ("system-name", Vsystem_name,
4797 doc: /* The host name of the machine Emacs is running on. */);
4799 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4800 doc: /* The full name of the user logged in. */);
4802 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4803 doc: /* The user's name, taken from environment variables if possible. */);
4805 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4806 doc: /* The user's name, based upon the real uid only. */);
4808 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4809 doc: /* The release of the operating system Emacs is running on. */);
4811 defsubr (&Spropertize);
4812 defsubr (&Schar_equal);
4813 defsubr (&Sgoto_char);
4814 defsubr (&Sstring_to_char);
4815 defsubr (&Schar_to_string);
4816 defsubr (&Sbyte_to_string);
4817 defsubr (&Sbuffer_substring);
4818 defsubr (&Sbuffer_substring_no_properties);
4819 defsubr (&Sbuffer_string);
4820 defsubr (&Sget_pos_property);
4822 defsubr (&Spoint_marker);
4823 defsubr (&Smark_marker);
4824 defsubr (&Spoint);
4825 defsubr (&Sregion_beginning);
4826 defsubr (&Sregion_end);
4828 DEFSYM (Qfield, "field");
4829 DEFSYM (Qboundary, "boundary");
4830 defsubr (&Sfield_beginning);
4831 defsubr (&Sfield_end);
4832 defsubr (&Sfield_string);
4833 defsubr (&Sfield_string_no_properties);
4834 defsubr (&Sdelete_field);
4835 defsubr (&Sconstrain_to_field);
4837 defsubr (&Sline_beginning_position);
4838 defsubr (&Sline_end_position);
4840 defsubr (&Ssave_excursion);
4841 defsubr (&Ssave_current_buffer);
4843 defsubr (&Sbuffer_size);
4844 defsubr (&Spoint_max);
4845 defsubr (&Spoint_min);
4846 defsubr (&Spoint_min_marker);
4847 defsubr (&Spoint_max_marker);
4848 defsubr (&Sgap_position);
4849 defsubr (&Sgap_size);
4850 defsubr (&Sposition_bytes);
4851 defsubr (&Sbyte_to_position);
4853 defsubr (&Sbobp);
4854 defsubr (&Seobp);
4855 defsubr (&Sbolp);
4856 defsubr (&Seolp);
4857 defsubr (&Sfollowing_char);
4858 defsubr (&Sprevious_char);
4859 defsubr (&Schar_after);
4860 defsubr (&Schar_before);
4861 defsubr (&Sinsert);
4862 defsubr (&Sinsert_before_markers);
4863 defsubr (&Sinsert_and_inherit);
4864 defsubr (&Sinsert_and_inherit_before_markers);
4865 defsubr (&Sinsert_char);
4866 defsubr (&Sinsert_byte);
4868 defsubr (&Suser_login_name);
4869 defsubr (&Suser_real_login_name);
4870 defsubr (&Suser_uid);
4871 defsubr (&Suser_real_uid);
4872 defsubr (&Sgroup_gid);
4873 defsubr (&Sgroup_real_gid);
4874 defsubr (&Suser_full_name);
4875 defsubr (&Semacs_pid);
4876 defsubr (&Scurrent_time);
4877 defsubr (&Sget_internal_run_time);
4878 defsubr (&Sformat_time_string);
4879 defsubr (&Sfloat_time);
4880 defsubr (&Sdecode_time);
4881 defsubr (&Sencode_time);
4882 defsubr (&Scurrent_time_string);
4883 defsubr (&Scurrent_time_zone);
4884 defsubr (&Sset_time_zone_rule);
4885 defsubr (&Ssystem_name);
4886 defsubr (&Smessage);
4887 defsubr (&Smessage_box);
4888 defsubr (&Smessage_or_box);
4889 defsubr (&Scurrent_message);
4890 defsubr (&Sformat);
4892 defsubr (&Sinsert_buffer_substring);
4893 defsubr (&Scompare_buffer_substrings);
4894 defsubr (&Ssubst_char_in_region);
4895 defsubr (&Stranslate_region_internal);
4896 defsubr (&Sdelete_region);
4897 defsubr (&Sdelete_and_extract_region);
4898 defsubr (&Swiden);
4899 defsubr (&Snarrow_to_region);
4900 defsubr (&Ssave_restriction);
4901 defsubr (&Stranspose_regions);