Auto-commit of generated files.
[emacs.git] / src / editfns.c
blob5e1dcce027544271fa6aa2936e08fda892be0560
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2011 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>
24 #include <setjmp.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.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 <ctype.h>
48 #include <limits.h>
49 #include <intprops.h>
50 #include <strftime.h>
52 #include "intervals.h"
53 #include "buffer.h"
54 #include "character.h"
55 #include "coding.h"
56 #include "frame.h"
57 #include "window.h"
58 #include "blockinput.h"
60 #ifdef STDC_HEADERS
61 #include <float.h>
62 #define MAX_10_EXP DBL_MAX_10_EXP
63 #else
64 #define MAX_10_EXP 310
65 #endif
67 #ifndef NULL
68 #define NULL 0
69 #endif
71 #ifndef USER_FULL_NAME
72 #define USER_FULL_NAME pw->pw_gecos
73 #endif
75 #ifndef USE_CRT_DLL
76 extern char **environ;
77 #endif
79 #define TM_YEAR_BASE 1900
81 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
82 asctime to have well-defined behavior. */
83 #ifndef TM_YEAR_IN_ASCTIME_RANGE
84 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
85 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
86 #endif
88 #ifdef WINDOWSNT
89 extern Lisp_Object w32_get_internal_run_time (void);
90 #endif
92 static void time_overflow (void) NO_RETURN;
93 static int tm_diff (struct tm *, struct tm *);
94 static void find_field (Lisp_Object, Lisp_Object, Lisp_Object,
95 EMACS_INT *, Lisp_Object, EMACS_INT *);
96 static void update_buffer_properties (EMACS_INT, EMACS_INT);
97 static Lisp_Object region_limit (int);
98 static size_t emacs_nmemftime (char *, size_t, const char *,
99 size_t, const struct tm *, int, int);
100 static void general_insert_function (void (*) (const char *, EMACS_INT),
101 void (*) (Lisp_Object, EMACS_INT,
102 EMACS_INT, EMACS_INT,
103 EMACS_INT, int),
104 int, size_t, Lisp_Object *);
105 static Lisp_Object subst_char_in_region_unwind (Lisp_Object);
106 static Lisp_Object subst_char_in_region_unwind_1 (Lisp_Object);
107 static void transpose_markers (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT,
108 EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT);
110 static Lisp_Object Qbuffer_access_fontify_functions;
111 static Lisp_Object Fuser_full_name (Lisp_Object);
113 /* Symbol for the text property used to mark fields. */
115 Lisp_Object Qfield;
117 /* A special value for Qfield properties. */
119 static Lisp_Object Qboundary;
122 void
123 init_editfns (void)
125 const char *user_name;
126 register char *p;
127 struct passwd *pw; /* password entry for the current user */
128 Lisp_Object tem;
130 /* Set up system_name even when dumping. */
131 init_system_name ();
133 #ifndef CANNOT_DUMP
134 /* Don't bother with this on initial start when just dumping out */
135 if (!initialized)
136 return;
137 #endif /* not CANNOT_DUMP */
139 pw = getpwuid (getuid ());
140 #ifdef MSDOS
141 /* We let the real user name default to "root" because that's quite
142 accurate on MSDOG and because it lets Emacs find the init file.
143 (The DVX libraries override the Djgpp libraries here.) */
144 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
145 #else
146 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
147 #endif
149 /* Get the effective user name, by consulting environment variables,
150 or the effective uid if those are unset. */
151 user_name = getenv ("LOGNAME");
152 if (!user_name)
153 #ifdef WINDOWSNT
154 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
155 #else /* WINDOWSNT */
156 user_name = getenv ("USER");
157 #endif /* WINDOWSNT */
158 if (!user_name)
160 pw = getpwuid (geteuid ());
161 user_name = pw ? pw->pw_name : "unknown";
163 Vuser_login_name = build_string (user_name);
165 /* If the user name claimed in the environment vars differs from
166 the real uid, use the claimed name to find the full name. */
167 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
168 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
169 : Vuser_login_name);
171 p = getenv ("NAME");
172 if (p)
173 Vuser_full_name = build_string (p);
174 else if (NILP (Vuser_full_name))
175 Vuser_full_name = build_string ("unknown");
177 #ifdef HAVE_SYS_UTSNAME_H
179 struct utsname uts;
180 uname (&uts);
181 Voperating_system_release = build_string (uts.release);
183 #else
184 Voperating_system_release = Qnil;
185 #endif
188 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
189 doc: /* Convert arg CHAR to a string containing that character.
190 usage: (char-to-string CHAR) */)
191 (Lisp_Object character)
193 int len;
194 unsigned char str[MAX_MULTIBYTE_LENGTH];
196 CHECK_CHARACTER (character);
198 len = CHAR_STRING (XFASTINT (character), str);
199 return make_string_from_bytes ((char *) str, 1, len);
202 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
203 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
204 (Lisp_Object byte)
206 unsigned char b;
207 CHECK_NUMBER (byte);
208 if (XINT (byte) < 0 || XINT (byte) > 255)
209 error ("Invalid byte");
210 b = XINT (byte);
211 return make_string_from_bytes ((char *) &b, 1, 1);
214 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
215 doc: /* Convert arg STRING to a character, the first character of that string.
216 A multibyte character is handled correctly. */)
217 (register Lisp_Object string)
219 register Lisp_Object val;
220 CHECK_STRING (string);
221 if (SCHARS (string))
223 if (STRING_MULTIBYTE (string))
224 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
225 else
226 XSETFASTINT (val, SREF (string, 0));
228 else
229 XSETFASTINT (val, 0);
230 return val;
233 static Lisp_Object
234 buildmark (EMACS_INT charpos, EMACS_INT bytepos)
236 register Lisp_Object mark;
237 mark = Fmake_marker ();
238 set_marker_both (mark, Qnil, charpos, bytepos);
239 return mark;
242 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
243 doc: /* Return value of point, as an integer.
244 Beginning of buffer is position (point-min). */)
245 (void)
247 Lisp_Object temp;
248 XSETFASTINT (temp, PT);
249 return temp;
252 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
253 doc: /* Return value of point, as a marker object. */)
254 (void)
256 return buildmark (PT, PT_BYTE);
259 EMACS_INT
260 clip_to_bounds (EMACS_INT lower, EMACS_INT num, EMACS_INT upper)
262 if (num < lower)
263 return lower;
264 else if (num > upper)
265 return upper;
266 else
267 return num;
270 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
271 doc: /* Set point to POSITION, a number or marker.
272 Beginning of buffer is position (point-min), end is (point-max).
274 The return value is POSITION. */)
275 (register Lisp_Object position)
277 EMACS_INT pos;
279 if (MARKERP (position)
280 && current_buffer == XMARKER (position)->buffer)
282 pos = marker_position (position);
283 if (pos < BEGV)
284 SET_PT_BOTH (BEGV, BEGV_BYTE);
285 else if (pos > ZV)
286 SET_PT_BOTH (ZV, ZV_BYTE);
287 else
288 SET_PT_BOTH (pos, marker_byte_position (position));
290 return position;
293 CHECK_NUMBER_COERCE_MARKER (position);
295 pos = clip_to_bounds (BEGV, XINT (position), ZV);
296 SET_PT (pos);
297 return position;
301 /* Return the start or end position of the region.
302 BEGINNINGP non-zero means return the start.
303 If there is no region active, signal an error. */
305 static Lisp_Object
306 region_limit (int beginningp)
308 Lisp_Object m;
310 if (!NILP (Vtransient_mark_mode)
311 && NILP (Vmark_even_if_inactive)
312 && NILP (BVAR (current_buffer, mark_active)))
313 xsignal0 (Qmark_inactive);
315 m = Fmarker_position (BVAR (current_buffer, mark));
316 if (NILP (m))
317 error ("The mark is not set now, so there is no region");
319 if ((PT < XFASTINT (m)) == (beginningp != 0))
320 m = make_number (PT);
321 return m;
324 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
325 doc: /* Return the integer value of point or mark, whichever is smaller. */)
326 (void)
328 return region_limit (1);
331 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
332 doc: /* Return the integer value of point or mark, whichever is larger. */)
333 (void)
335 return region_limit (0);
338 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
339 doc: /* Return this buffer's mark, as a marker object.
340 Watch out! Moving this marker changes the mark position.
341 If you set the marker not to point anywhere, the buffer will have no mark. */)
342 (void)
344 return BVAR (current_buffer, mark);
348 /* Find all the overlays in the current buffer that touch position POS.
349 Return the number found, and store them in a vector in VEC
350 of length LEN. */
352 static int
353 overlays_around (EMACS_INT pos, Lisp_Object *vec, int len)
355 Lisp_Object overlay, start, end;
356 struct Lisp_Overlay *tail;
357 EMACS_INT startpos, endpos;
358 int idx = 0;
360 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
362 XSETMISC (overlay, tail);
364 end = OVERLAY_END (overlay);
365 endpos = OVERLAY_POSITION (end);
366 if (endpos < pos)
367 break;
368 start = OVERLAY_START (overlay);
369 startpos = OVERLAY_POSITION (start);
370 if (startpos <= pos)
372 if (idx < len)
373 vec[idx] = overlay;
374 /* Keep counting overlays even if we can't return them all. */
375 idx++;
379 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
381 XSETMISC (overlay, tail);
383 start = OVERLAY_START (overlay);
384 startpos = OVERLAY_POSITION (start);
385 if (pos < startpos)
386 break;
387 end = OVERLAY_END (overlay);
388 endpos = OVERLAY_POSITION (end);
389 if (pos <= endpos)
391 if (idx < len)
392 vec[idx] = overlay;
393 idx++;
397 return idx;
400 /* Return the value of property PROP, in OBJECT at POSITION.
401 It's the value of PROP that a char inserted at POSITION would get.
402 OBJECT is optional and defaults to the current buffer.
403 If OBJECT is a buffer, then overlay properties are considered as well as
404 text properties.
405 If OBJECT is a window, then that window's buffer is used, but
406 window-specific overlays are considered only if they are associated
407 with OBJECT. */
408 Lisp_Object
409 get_pos_property (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
411 CHECK_NUMBER_COERCE_MARKER (position);
413 if (NILP (object))
414 XSETBUFFER (object, current_buffer);
415 else if (WINDOWP (object))
416 object = XWINDOW (object)->buffer;
418 if (!BUFFERP (object))
419 /* pos-property only makes sense in buffers right now, since strings
420 have no overlays and no notion of insertion for which stickiness
421 could be obeyed. */
422 return Fget_text_property (position, prop, object);
423 else
425 EMACS_INT posn = XINT (position);
426 int noverlays;
427 Lisp_Object *overlay_vec, tem;
428 struct buffer *obuf = current_buffer;
430 set_buffer_temp (XBUFFER (object));
432 /* First try with room for 40 overlays. */
433 noverlays = 40;
434 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
435 noverlays = overlays_around (posn, overlay_vec, noverlays);
437 /* If there are more than 40,
438 make enough space for all, and try again. */
439 if (noverlays > 40)
441 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
442 noverlays = overlays_around (posn, overlay_vec, noverlays);
444 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
446 set_buffer_temp (obuf);
448 /* Now check the overlays in order of decreasing priority. */
449 while (--noverlays >= 0)
451 Lisp_Object ol = overlay_vec[noverlays];
452 tem = Foverlay_get (ol, prop);
453 if (!NILP (tem))
455 /* Check the overlay is indeed active at point. */
456 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
457 if ((OVERLAY_POSITION (start) == posn
458 && XMARKER (start)->insertion_type == 1)
459 || (OVERLAY_POSITION (finish) == posn
460 && XMARKER (finish)->insertion_type == 0))
461 ; /* The overlay will not cover a char inserted at point. */
462 else
464 return tem;
469 { /* Now check the text properties. */
470 int stickiness = text_property_stickiness (prop, position, object);
471 if (stickiness > 0)
472 return Fget_text_property (position, prop, object);
473 else if (stickiness < 0
474 && XINT (position) > BUF_BEGV (XBUFFER (object)))
475 return Fget_text_property (make_number (XINT (position) - 1),
476 prop, object);
477 else
478 return Qnil;
483 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
484 the value of point is used instead. If BEG or END is null,
485 means don't store the beginning or end of the field.
487 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
488 results; they do not effect boundary behavior.
490 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
491 position of a field, then the beginning of the previous field is
492 returned instead of the beginning of POS's field (since the end of a
493 field is actually also the beginning of the next input field, this
494 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
495 true case, if two fields are separated by a field with the special
496 value `boundary', and POS lies within it, then the two separated
497 fields are considered to be adjacent, and POS between them, when
498 finding the beginning and ending of the "merged" field.
500 Either BEG or END may be 0, in which case the corresponding value
501 is not stored. */
503 static void
504 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
505 Lisp_Object beg_limit,
506 EMACS_INT *beg, Lisp_Object end_limit, EMACS_INT *end)
508 /* Fields right before and after the point. */
509 Lisp_Object before_field, after_field;
510 /* 1 if POS counts as the start of a field. */
511 int at_field_start = 0;
512 /* 1 if POS counts as the end of a field. */
513 int at_field_end = 0;
515 if (NILP (pos))
516 XSETFASTINT (pos, PT);
517 else
518 CHECK_NUMBER_COERCE_MARKER (pos);
520 after_field
521 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
522 before_field
523 = (XFASTINT (pos) > BEGV
524 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
525 Qfield, Qnil, NULL)
526 /* Using nil here would be a more obvious choice, but it would
527 fail when the buffer starts with a non-sticky field. */
528 : after_field);
530 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
531 and POS is at beginning of a field, which can also be interpreted
532 as the end of the previous field. Note that the case where if
533 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
534 more natural one; then we avoid treating the beginning of a field
535 specially. */
536 if (NILP (merge_at_boundary))
538 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
539 if (!EQ (field, after_field))
540 at_field_end = 1;
541 if (!EQ (field, before_field))
542 at_field_start = 1;
543 if (NILP (field) && at_field_start && at_field_end)
544 /* If an inserted char would have a nil field while the surrounding
545 text is non-nil, we're probably not looking at a
546 zero-length field, but instead at a non-nil field that's
547 not intended for editing (such as comint's prompts). */
548 at_field_end = at_field_start = 0;
551 /* Note about special `boundary' fields:
553 Consider the case where the point (`.') is between the fields `x' and `y':
555 xxxx.yyyy
557 In this situation, if merge_at_boundary is true, we consider the
558 `x' and `y' fields as forming one big merged field, and so the end
559 of the field is the end of `y'.
561 However, if `x' and `y' are separated by a special `boundary' field
562 (a field with a `field' char-property of 'boundary), then we ignore
563 this special field when merging adjacent fields. Here's the same
564 situation, but with a `boundary' field between the `x' and `y' fields:
566 xxx.BBBByyyy
568 Here, if point is at the end of `x', the beginning of `y', or
569 anywhere in-between (within the `boundary' field), we merge all
570 three fields and consider the beginning as being the beginning of
571 the `x' field, and the end as being the end of the `y' field. */
573 if (beg)
575 if (at_field_start)
576 /* POS is at the edge of a field, and we should consider it as
577 the beginning of the following field. */
578 *beg = XFASTINT (pos);
579 else
580 /* Find the previous field boundary. */
582 Lisp_Object p = pos;
583 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
584 /* Skip a `boundary' field. */
585 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
586 beg_limit);
588 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
589 beg_limit);
590 *beg = NILP (p) ? BEGV : XFASTINT (p);
594 if (end)
596 if (at_field_end)
597 /* POS is at the edge of a field, and we should consider it as
598 the end of the previous field. */
599 *end = XFASTINT (pos);
600 else
601 /* Find the next field boundary. */
603 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
604 /* Skip a `boundary' field. */
605 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
606 end_limit);
608 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
609 end_limit);
610 *end = NILP (pos) ? ZV : XFASTINT (pos);
616 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
617 doc: /* Delete the field surrounding POS.
618 A field is a region of text with the same `field' property.
619 If POS is nil, the value of point is used for POS. */)
620 (Lisp_Object pos)
622 EMACS_INT beg, end;
623 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
624 if (beg != end)
625 del_range (beg, end);
626 return Qnil;
629 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
630 doc: /* Return the contents of the field surrounding POS as a string.
631 A field is a region of text with the same `field' property.
632 If POS is nil, the value of point is used for POS. */)
633 (Lisp_Object pos)
635 EMACS_INT beg, end;
636 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
637 return make_buffer_string (beg, end, 1);
640 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
641 doc: /* Return the contents of the field around POS, without text properties.
642 A field is a region of text with the same `field' property.
643 If POS is nil, the value of point is used for POS. */)
644 (Lisp_Object pos)
646 EMACS_INT beg, end;
647 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
648 return make_buffer_string (beg, end, 0);
651 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
652 doc: /* Return the beginning of the field surrounding POS.
653 A field is a region of text with the same `field' property.
654 If POS is nil, the value of point is used for POS.
655 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
656 field, then the beginning of the *previous* field is returned.
657 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
658 is before LIMIT, then LIMIT will be returned instead. */)
659 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
661 EMACS_INT beg;
662 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
663 return make_number (beg);
666 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
667 doc: /* Return the end of the field surrounding POS.
668 A field is a region of text with the same `field' property.
669 If POS is nil, the value of point is used for POS.
670 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
671 then the end of the *following* field is returned.
672 If LIMIT is non-nil, it is a buffer position; if the end of the field
673 is after LIMIT, then LIMIT will be returned instead. */)
674 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
676 EMACS_INT end;
677 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
678 return make_number (end);
681 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
682 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
684 A field is a region of text with the same `field' property.
685 If NEW-POS is nil, then the current point is used instead, and set to the
686 constrained position if that is different.
688 If OLD-POS is at the boundary of two fields, then the allowable
689 positions for NEW-POS depends on the value of the optional argument
690 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
691 constrained to the field that has the same `field' char-property
692 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
693 is non-nil, NEW-POS is constrained to the union of the two adjacent
694 fields. Additionally, if two fields are separated by another field with
695 the special value `boundary', then any point within this special field is
696 also considered to be `on the boundary'.
698 If the optional argument ONLY-IN-LINE is non-nil and constraining
699 NEW-POS would move it to a different line, NEW-POS is returned
700 unconstrained. This useful for commands that move by line, like
701 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
702 only in the case where they can still move to the right line.
704 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
705 a non-nil property of that name, then any field boundaries are ignored.
707 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
708 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
710 /* If non-zero, then the original point, before re-positioning. */
711 EMACS_INT orig_point = 0;
712 int fwd;
713 Lisp_Object prev_old, prev_new;
715 if (NILP (new_pos))
716 /* Use the current point, and afterwards, set it. */
718 orig_point = PT;
719 XSETFASTINT (new_pos, PT);
722 CHECK_NUMBER_COERCE_MARKER (new_pos);
723 CHECK_NUMBER_COERCE_MARKER (old_pos);
725 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
727 prev_old = make_number (XFASTINT (old_pos) - 1);
728 prev_new = make_number (XFASTINT (new_pos) - 1);
730 if (NILP (Vinhibit_field_text_motion)
731 && !EQ (new_pos, old_pos)
732 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
733 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
734 /* To recognize field boundaries, we must also look at the
735 previous positions; we could use `get_pos_property'
736 instead, but in itself that would fail inside non-sticky
737 fields (like comint prompts). */
738 || (XFASTINT (new_pos) > BEGV
739 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
740 || (XFASTINT (old_pos) > BEGV
741 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
742 && (NILP (inhibit_capture_property)
743 /* Field boundaries are again a problem; but now we must
744 decide the case exactly, so we need to call
745 `get_pos_property' as well. */
746 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
747 && (XFASTINT (old_pos) <= BEGV
748 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
749 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
750 /* It is possible that NEW_POS is not within the same field as
751 OLD_POS; try to move NEW_POS so that it is. */
753 EMACS_INT shortage;
754 Lisp_Object field_bound;
756 if (fwd)
757 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
758 else
759 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
761 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
762 other side of NEW_POS, which would mean that NEW_POS is
763 already acceptable, and it's not necessary to constrain it
764 to FIELD_BOUND. */
765 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
766 /* NEW_POS should be constrained, but only if either
767 ONLY_IN_LINE is nil (in which case any constraint is OK),
768 or NEW_POS and FIELD_BOUND are on the same line (in which
769 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
770 && (NILP (only_in_line)
771 /* This is the ONLY_IN_LINE case, check that NEW_POS and
772 FIELD_BOUND are on the same line by seeing whether
773 there's an intervening newline or not. */
774 || (scan_buffer ('\n',
775 XFASTINT (new_pos), XFASTINT (field_bound),
776 fwd ? -1 : 1, &shortage, 1),
777 shortage != 0)))
778 /* Constrain NEW_POS to FIELD_BOUND. */
779 new_pos = field_bound;
781 if (orig_point && XFASTINT (new_pos) != orig_point)
782 /* The NEW_POS argument was originally nil, so automatically set PT. */
783 SET_PT (XFASTINT (new_pos));
786 return new_pos;
790 DEFUN ("line-beginning-position",
791 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
792 doc: /* Return the character position of the first character on the current line.
793 With argument N not nil or 1, move forward N - 1 lines first.
794 If scan reaches end of buffer, return that position.
796 The returned position is of the first character in the logical order,
797 i.e. the one that has the smallest character position.
799 This function constrains the returned position to the current field
800 unless that would be on a different line than the original,
801 unconstrained result. If N is nil or 1, and a front-sticky field
802 starts at point, the scan stops as soon as it starts. To ignore field
803 boundaries bind `inhibit-field-text-motion' to t.
805 This function does not move point. */)
806 (Lisp_Object n)
808 EMACS_INT orig, orig_byte, end;
809 int count = SPECPDL_INDEX ();
810 specbind (Qinhibit_point_motion_hooks, Qt);
812 if (NILP (n))
813 XSETFASTINT (n, 1);
814 else
815 CHECK_NUMBER (n);
817 orig = PT;
818 orig_byte = PT_BYTE;
819 Fforward_line (make_number (XINT (n) - 1));
820 end = PT;
822 SET_PT_BOTH (orig, orig_byte);
824 unbind_to (count, Qnil);
826 /* Return END constrained to the current input field. */
827 return Fconstrain_to_field (make_number (end), make_number (orig),
828 XINT (n) != 1 ? Qt : Qnil,
829 Qt, Qnil);
832 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
833 doc: /* Return the character position of the last character on the current line.
834 With argument N not nil or 1, move forward N - 1 lines first.
835 If scan reaches end of buffer, return that position.
837 The returned position is of the last character in the logical order,
838 i.e. the character whose buffer position is the largest one.
840 This function constrains the returned position to the current field
841 unless that would be on a different line than the original,
842 unconstrained result. If N is nil or 1, and a rear-sticky field ends
843 at point, the scan stops as soon as it starts. To ignore field
844 boundaries bind `inhibit-field-text-motion' to t.
846 This function does not move point. */)
847 (Lisp_Object n)
849 EMACS_INT end_pos;
850 EMACS_INT orig = PT;
852 if (NILP (n))
853 XSETFASTINT (n, 1);
854 else
855 CHECK_NUMBER (n);
857 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
859 /* Return END_POS constrained to the current input field. */
860 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
861 Qnil, Qt, Qnil);
865 Lisp_Object
866 save_excursion_save (void)
868 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
869 == current_buffer);
871 return Fcons (Fpoint_marker (),
872 Fcons (Fcopy_marker (BVAR (current_buffer, mark), Qnil),
873 Fcons (visible ? Qt : Qnil,
874 Fcons (BVAR (current_buffer, mark_active),
875 selected_window))));
878 Lisp_Object
879 save_excursion_restore (Lisp_Object info)
881 Lisp_Object tem, tem1, omark, nmark;
882 struct gcpro gcpro1, gcpro2, gcpro3;
883 int visible_p;
885 tem = Fmarker_buffer (XCAR (info));
886 /* If buffer being returned to is now deleted, avoid error */
887 /* Otherwise could get error here while unwinding to top level
888 and crash */
889 /* In that case, Fmarker_buffer returns nil now. */
890 if (NILP (tem))
891 return Qnil;
893 omark = nmark = Qnil;
894 GCPRO3 (info, omark, nmark);
896 Fset_buffer (tem);
898 /* Point marker. */
899 tem = XCAR (info);
900 Fgoto_char (tem);
901 unchain_marker (XMARKER (tem));
903 /* Mark marker. */
904 info = XCDR (info);
905 tem = XCAR (info);
906 omark = Fmarker_position (BVAR (current_buffer, mark));
907 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
908 nmark = Fmarker_position (tem);
909 unchain_marker (XMARKER (tem));
911 /* visible */
912 info = XCDR (info);
913 visible_p = !NILP (XCAR (info));
915 #if 0 /* We used to make the current buffer visible in the selected window
916 if that was true previously. That avoids some anomalies.
917 But it creates others, and it wasn't documented, and it is simpler
918 and cleaner never to alter the window/buffer connections. */
919 tem1 = Fcar (tem);
920 if (!NILP (tem1)
921 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
922 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
923 #endif /* 0 */
925 /* Mark active */
926 info = XCDR (info);
927 tem = XCAR (info);
928 tem1 = BVAR (current_buffer, mark_active);
929 BVAR (current_buffer, mark_active) = tem;
931 /* If mark is active now, and either was not active
932 or was at a different place, run the activate hook. */
933 if (! NILP (tem))
935 if (! EQ (omark, nmark))
937 tem = intern ("activate-mark-hook");
938 Frun_hooks (1, &tem);
941 /* If mark has ceased to be active, run deactivate hook. */
942 else if (! NILP (tem1))
944 tem = intern ("deactivate-mark-hook");
945 Frun_hooks (1, &tem);
948 /* If buffer was visible in a window, and a different window was
949 selected, and the old selected window is still showing this
950 buffer, restore point in that window. */
951 tem = XCDR (info);
952 if (visible_p
953 && !EQ (tem, selected_window)
954 && (tem1 = XWINDOW (tem)->buffer,
955 (/* Window is live... */
956 BUFFERP (tem1)
957 /* ...and it shows the current buffer. */
958 && XBUFFER (tem1) == current_buffer)))
959 Fset_window_point (tem, make_number (PT));
961 UNGCPRO;
962 return Qnil;
965 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
966 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
967 Executes BODY just like `progn'.
968 The values of point, mark and the current buffer are restored
969 even in case of abnormal exit (throw or error).
970 The state of activation of the mark is also restored.
972 This construct does not save `deactivate-mark', and therefore
973 functions that change the buffer will still cause deactivation
974 of the mark at the end of the command. To prevent that, bind
975 `deactivate-mark' with `let'.
977 If you only want to save the current buffer but not point nor mark,
978 then just use `save-current-buffer', or even `with-current-buffer'.
980 usage: (save-excursion &rest BODY) */)
981 (Lisp_Object args)
983 register Lisp_Object val;
984 int count = SPECPDL_INDEX ();
986 record_unwind_protect (save_excursion_restore, save_excursion_save ());
988 val = Fprogn (args);
989 return unbind_to (count, val);
992 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
993 doc: /* Save the current buffer; execute BODY; restore the current buffer.
994 Executes BODY just like `progn'.
995 usage: (save-current-buffer &rest BODY) */)
996 (Lisp_Object args)
998 Lisp_Object val;
999 int count = SPECPDL_INDEX ();
1001 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
1003 val = Fprogn (args);
1004 return unbind_to (count, val);
1007 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1008 doc: /* Return the number of characters in the current buffer.
1009 If BUFFER, return the number of characters in that buffer instead. */)
1010 (Lisp_Object buffer)
1012 if (NILP (buffer))
1013 return make_number (Z - BEG);
1014 else
1016 CHECK_BUFFER (buffer);
1017 return make_number (BUF_Z (XBUFFER (buffer))
1018 - BUF_BEG (XBUFFER (buffer)));
1022 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1023 doc: /* Return the minimum permissible value of point in the current buffer.
1024 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1025 (void)
1027 Lisp_Object temp;
1028 XSETFASTINT (temp, BEGV);
1029 return temp;
1032 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1033 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1034 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1035 (void)
1037 return buildmark (BEGV, BEGV_BYTE);
1040 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1041 doc: /* Return the maximum permissible value of point in the current buffer.
1042 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1043 is in effect, in which case it is less. */)
1044 (void)
1046 Lisp_Object temp;
1047 XSETFASTINT (temp, ZV);
1048 return temp;
1051 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1052 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1053 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1054 is in effect, in which case it is less. */)
1055 (void)
1057 return buildmark (ZV, ZV_BYTE);
1060 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1061 doc: /* Return the position of the gap, in the current buffer.
1062 See also `gap-size'. */)
1063 (void)
1065 Lisp_Object temp;
1066 XSETFASTINT (temp, GPT);
1067 return temp;
1070 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1071 doc: /* Return the size of the current buffer's gap.
1072 See also `gap-position'. */)
1073 (void)
1075 Lisp_Object temp;
1076 XSETFASTINT (temp, GAP_SIZE);
1077 return temp;
1080 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1081 doc: /* Return the byte position for character position POSITION.
1082 If POSITION is out of range, the value is nil. */)
1083 (Lisp_Object position)
1085 CHECK_NUMBER_COERCE_MARKER (position);
1086 if (XINT (position) < BEG || XINT (position) > Z)
1087 return Qnil;
1088 return make_number (CHAR_TO_BYTE (XINT (position)));
1091 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1092 doc: /* Return the character position for byte position BYTEPOS.
1093 If BYTEPOS is out of range, the value is nil. */)
1094 (Lisp_Object bytepos)
1096 CHECK_NUMBER (bytepos);
1097 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1098 return Qnil;
1099 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1102 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1103 doc: /* Return the character following point, as a number.
1104 At the end of the buffer or accessible region, return 0. */)
1105 (void)
1107 Lisp_Object temp;
1108 if (PT >= ZV)
1109 XSETFASTINT (temp, 0);
1110 else
1111 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1112 return temp;
1115 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1116 doc: /* Return the character preceding point, as a number.
1117 At the beginning of the buffer or accessible region, return 0. */)
1118 (void)
1120 Lisp_Object temp;
1121 if (PT <= BEGV)
1122 XSETFASTINT (temp, 0);
1123 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1125 EMACS_INT pos = PT_BYTE;
1126 DEC_POS (pos);
1127 XSETFASTINT (temp, FETCH_CHAR (pos));
1129 else
1130 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1131 return temp;
1134 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1135 doc: /* Return t if point is at the beginning of the buffer.
1136 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1137 (void)
1139 if (PT == BEGV)
1140 return Qt;
1141 return Qnil;
1144 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1145 doc: /* Return t if point is at the end of the buffer.
1146 If the buffer is narrowed, this means the end of the narrowed part. */)
1147 (void)
1149 if (PT == ZV)
1150 return Qt;
1151 return Qnil;
1154 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1155 doc: /* Return t if point is at the beginning of a line. */)
1156 (void)
1158 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1159 return Qt;
1160 return Qnil;
1163 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1164 doc: /* Return t if point is at the end of a line.
1165 `End of a line' includes point being at the end of the buffer. */)
1166 (void)
1168 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1169 return Qt;
1170 return Qnil;
1173 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1174 doc: /* Return character in current buffer at position POS.
1175 POS is an integer or a marker and defaults to point.
1176 If POS is out of range, the value is nil. */)
1177 (Lisp_Object pos)
1179 register EMACS_INT pos_byte;
1181 if (NILP (pos))
1183 pos_byte = PT_BYTE;
1184 XSETFASTINT (pos, PT);
1187 if (MARKERP (pos))
1189 pos_byte = marker_byte_position (pos);
1190 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1191 return Qnil;
1193 else
1195 CHECK_NUMBER_COERCE_MARKER (pos);
1196 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1197 return Qnil;
1199 pos_byte = CHAR_TO_BYTE (XINT (pos));
1202 return make_number (FETCH_CHAR (pos_byte));
1205 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1206 doc: /* Return character in current buffer preceding position POS.
1207 POS is an integer or a marker and defaults to point.
1208 If POS is out of range, the value is nil. */)
1209 (Lisp_Object pos)
1211 register Lisp_Object val;
1212 register EMACS_INT pos_byte;
1214 if (NILP (pos))
1216 pos_byte = PT_BYTE;
1217 XSETFASTINT (pos, PT);
1220 if (MARKERP (pos))
1222 pos_byte = marker_byte_position (pos);
1224 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1225 return Qnil;
1227 else
1229 CHECK_NUMBER_COERCE_MARKER (pos);
1231 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1232 return Qnil;
1234 pos_byte = CHAR_TO_BYTE (XINT (pos));
1237 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1239 DEC_POS (pos_byte);
1240 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1242 else
1244 pos_byte--;
1245 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1247 return val;
1250 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1251 doc: /* Return the name under which the user logged in, as a string.
1252 This is based on the effective uid, not the real uid.
1253 Also, if the environment variables LOGNAME or USER are set,
1254 that determines the value of this function.
1256 If optional argument UID is an integer or a float, return the login name
1257 of the user with that uid, or nil if there is no such user. */)
1258 (Lisp_Object uid)
1260 struct passwd *pw;
1261 uid_t id;
1263 /* Set up the user name info if we didn't do it before.
1264 (That can happen if Emacs is dumpable
1265 but you decide to run `temacs -l loadup' and not dump. */
1266 if (INTEGERP (Vuser_login_name))
1267 init_editfns ();
1269 if (NILP (uid))
1270 return Vuser_login_name;
1272 id = XFLOATINT (uid);
1273 BLOCK_INPUT;
1274 pw = getpwuid (id);
1275 UNBLOCK_INPUT;
1276 return (pw ? build_string (pw->pw_name) : Qnil);
1279 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1280 0, 0, 0,
1281 doc: /* Return the name of the user's real uid, as a string.
1282 This ignores the environment variables LOGNAME and USER, so it differs from
1283 `user-login-name' when running under `su'. */)
1284 (void)
1286 /* Set up the user name info if we didn't do it before.
1287 (That can happen if Emacs is dumpable
1288 but you decide to run `temacs -l loadup' and not dump. */
1289 if (INTEGERP (Vuser_login_name))
1290 init_editfns ();
1291 return Vuser_real_login_name;
1294 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1295 doc: /* Return the effective uid of Emacs.
1296 Value is an integer or a float, depending on the value. */)
1297 (void)
1299 /* Assignment to EMACS_INT stops GCC whining about limited range of
1300 data type. */
1301 EMACS_INT euid = geteuid ();
1303 /* Make sure we don't produce a negative UID due to signed integer
1304 overflow. */
1305 if (euid < 0)
1306 return make_float (geteuid ());
1307 return make_fixnum_or_float (euid);
1310 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1311 doc: /* Return the real uid of Emacs.
1312 Value is an integer or a float, depending on the value. */)
1313 (void)
1315 /* Assignment to EMACS_INT stops GCC whining about limited range of
1316 data type. */
1317 EMACS_INT uid = getuid ();
1319 /* Make sure we don't produce a negative UID due to signed integer
1320 overflow. */
1321 if (uid < 0)
1322 return make_float (getuid ());
1323 return make_fixnum_or_float (uid);
1326 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1327 doc: /* Return the full name of the user logged in, as a string.
1328 If the full name corresponding to Emacs's userid is not known,
1329 return "unknown".
1331 If optional argument UID is an integer or float, return the full name
1332 of the user with that uid, or nil if there is no such user.
1333 If UID is a string, return the full name of the user with that login
1334 name, or nil if there is no such user. */)
1335 (Lisp_Object uid)
1337 struct passwd *pw;
1338 register char *p, *q;
1339 Lisp_Object full;
1341 if (NILP (uid))
1342 return Vuser_full_name;
1343 else if (NUMBERP (uid))
1345 uid_t u = XFLOATINT (uid);
1346 BLOCK_INPUT;
1347 pw = getpwuid (u);
1348 UNBLOCK_INPUT;
1350 else if (STRINGP (uid))
1352 BLOCK_INPUT;
1353 pw = getpwnam (SSDATA (uid));
1354 UNBLOCK_INPUT;
1356 else
1357 error ("Invalid UID specification");
1359 if (!pw)
1360 return Qnil;
1362 p = USER_FULL_NAME;
1363 /* Chop off everything after the first comma. */
1364 q = strchr (p, ',');
1365 full = make_string (p, q ? q - p : strlen (p));
1367 #ifdef AMPERSAND_FULL_NAME
1368 p = SSDATA (full);
1369 q = strchr (p, '&');
1370 /* Substitute the login name for the &, upcasing the first character. */
1371 if (q)
1373 register char *r;
1374 Lisp_Object login;
1376 login = Fuser_login_name (make_number (pw->pw_uid));
1377 r = (char *) alloca (strlen (p) + SCHARS (login) + 1);
1378 memcpy (r, p, q - p);
1379 r[q - p] = 0;
1380 strcat (r, SSDATA (login));
1381 r[q - p] = upcase ((unsigned char) r[q - p]);
1382 strcat (r, q + 1);
1383 full = build_string (r);
1385 #endif /* AMPERSAND_FULL_NAME */
1387 return full;
1390 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1391 doc: /* Return the host name of the machine you are running on, as a string. */)
1392 (void)
1394 return Vsystem_name;
1397 const char *
1398 get_system_name (void)
1400 if (STRINGP (Vsystem_name))
1401 return SSDATA (Vsystem_name);
1402 else
1403 return "";
1406 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1407 doc: /* Return the process ID of Emacs, as an integer. */)
1408 (void)
1410 return make_number (getpid ());
1415 #ifndef TIME_T_MIN
1416 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1417 #endif
1418 #ifndef TIME_T_MAX
1419 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1420 #endif
1422 /* Report that a time value is out of range for Emacs. */
1423 static void
1424 time_overflow (void)
1426 error ("Specified time is not representable");
1429 /* Return the upper part of the time T (everything but the bottom 16 bits),
1430 making sure that it is representable. */
1431 static EMACS_INT
1432 hi_time (time_t t)
1434 time_t hi = t >> 16;
1436 /* Check for overflow, helping the compiler for common cases where
1437 no runtime check is needed, and taking care not to convert
1438 negative numbers to unsigned before comparing them. */
1439 if (! ((! TYPE_SIGNED (time_t)
1440 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1441 || MOST_NEGATIVE_FIXNUM <= hi)
1442 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1443 || hi <= MOST_POSITIVE_FIXNUM)))
1444 time_overflow ();
1446 return hi;
1449 /* Return the bottom 16 bits of the time T. */
1450 static EMACS_INT
1451 lo_time (time_t t)
1453 return t & ((1 << 16) - 1);
1456 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1457 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1458 The time is returned as a list of three integers. The first has the
1459 most significant 16 bits of the seconds, while the second has the
1460 least significant 16 bits. The third integer gives the microsecond
1461 count.
1463 The microsecond count is zero on systems that do not provide
1464 resolution finer than a second. */)
1465 (void)
1467 EMACS_TIME t;
1469 EMACS_GET_TIME (t);
1470 return list3 (make_number (hi_time (EMACS_SECS (t))),
1471 make_number (lo_time (EMACS_SECS (t))),
1472 make_number (EMACS_USECS (t)));
1475 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1476 0, 0, 0,
1477 doc: /* Return the current run time used by Emacs.
1478 The time is returned as a list of three integers. The first has the
1479 most significant 16 bits of the seconds, while the second has the
1480 least significant 16 bits. The third integer gives the microsecond
1481 count.
1483 On systems that can't determine the run time, `get-internal-run-time'
1484 does the same thing as `current-time'. The microsecond count is zero
1485 on systems that do not provide resolution finer than a second. */)
1486 (void)
1488 #ifdef HAVE_GETRUSAGE
1489 struct rusage usage;
1490 time_t secs;
1491 int usecs;
1493 if (getrusage (RUSAGE_SELF, &usage) < 0)
1494 /* This shouldn't happen. What action is appropriate? */
1495 xsignal0 (Qerror);
1497 /* Sum up user time and system time. */
1498 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1499 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1500 if (usecs >= 1000000)
1502 usecs -= 1000000;
1503 secs++;
1506 return list3 (make_number (hi_time (secs)),
1507 make_number (lo_time (secs)),
1508 make_number (usecs));
1509 #else /* ! HAVE_GETRUSAGE */
1510 #ifdef WINDOWSNT
1511 return w32_get_internal_run_time ();
1512 #else /* ! WINDOWSNT */
1513 return Fcurrent_time ();
1514 #endif /* WINDOWSNT */
1515 #endif /* HAVE_GETRUSAGE */
1519 /* Make a Lisp list that represents the time T. */
1520 Lisp_Object
1521 make_time (time_t t)
1523 return list2 (make_number (hi_time (t)),
1524 make_number (lo_time (t)));
1527 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1528 If SPECIFIED_TIME is nil, use the current time.
1529 Set *RESULT to seconds since the Epoch.
1530 If USEC is not null, set *USEC to the microseconds component.
1531 Return nonzero if successful. */
1533 lisp_time_argument (Lisp_Object specified_time, time_t *result, int *usec)
1535 if (NILP (specified_time))
1537 if (usec)
1539 EMACS_TIME t;
1541 EMACS_GET_TIME (t);
1542 *usec = EMACS_USECS (t);
1543 *result = EMACS_SECS (t);
1544 return 1;
1546 else
1547 return time (result) != -1;
1549 else
1551 Lisp_Object high, low;
1552 EMACS_INT hi;
1553 high = Fcar (specified_time);
1554 CHECK_NUMBER (high);
1555 low = Fcdr (specified_time);
1556 if (CONSP (low))
1558 if (usec)
1560 Lisp_Object usec_l = Fcdr (low);
1561 if (CONSP (usec_l))
1562 usec_l = Fcar (usec_l);
1563 if (NILP (usec_l))
1564 *usec = 0;
1565 else
1567 CHECK_NUMBER (usec_l);
1568 *usec = XINT (usec_l);
1571 low = Fcar (low);
1573 else if (usec)
1574 *usec = 0;
1575 CHECK_NUMBER (low);
1576 hi = XINT (high);
1578 /* Check for overflow, helping the compiler for common cases
1579 where no runtime check is needed, and taking care not to
1580 convert negative numbers to unsigned before comparing them. */
1581 if (! ((TYPE_SIGNED (time_t)
1582 ? (TIME_T_MIN >> 16 <= MOST_NEGATIVE_FIXNUM
1583 || TIME_T_MIN >> 16 <= hi)
1584 : 0 <= hi)
1585 && (MOST_POSITIVE_FIXNUM <= TIME_T_MAX >> 16
1586 || hi <= TIME_T_MAX >> 16)))
1587 return 0;
1589 *result = (hi << 16) + (XINT (low) & 0xffff);
1590 return 1;
1594 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1595 doc: /* Return the current time, as a float number of seconds since the epoch.
1596 If SPECIFIED-TIME is given, it is the time to convert to float
1597 instead of the current time. The argument should have the form
1598 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1599 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1600 have the form (HIGH . LOW), but this is considered obsolete.
1602 WARNING: Since the result is floating point, it may not be exact.
1603 If precise time stamps are required, use either `current-time',
1604 or (if you need time as a string) `format-time-string'. */)
1605 (Lisp_Object specified_time)
1607 time_t sec;
1608 int usec;
1610 if (! lisp_time_argument (specified_time, &sec, &usec))
1611 error ("Invalid time specification");
1613 return make_float ((sec * 1e6 + usec) / 1e6);
1616 /* Write information into buffer S of size MAXSIZE, according to the
1617 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1618 Default to Universal Time if UT is nonzero, local time otherwise.
1619 Use NS as the number of nanoseconds in the %N directive.
1620 Return the number of bytes written, not including the terminating
1621 '\0'. If S is NULL, nothing will be written anywhere; so to
1622 determine how many bytes would be written, use NULL for S and
1623 ((size_t) -1) for MAXSIZE.
1625 This function behaves like nstrftime, except it allows null
1626 bytes in FORMAT and it does not support nanoseconds. */
1627 static size_t
1628 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1629 size_t format_len, const struct tm *tp, int ut, int ns)
1631 size_t total = 0;
1633 /* Loop through all the null-terminated strings in the format
1634 argument. Normally there's just one null-terminated string, but
1635 there can be arbitrarily many, concatenated together, if the
1636 format contains '\0' bytes. nstrftime stops at the first
1637 '\0' byte so we must invoke it separately for each such string. */
1638 for (;;)
1640 size_t len;
1641 size_t result;
1643 if (s)
1644 s[0] = '\1';
1646 result = nstrftime (s, maxsize, format, tp, ut, ns);
1648 if (s)
1650 if (result == 0 && s[0] != '\0')
1651 return 0;
1652 s += result + 1;
1655 maxsize -= result + 1;
1656 total += result;
1657 len = strlen (format);
1658 if (len == format_len)
1659 return total;
1660 total++;
1661 format += len + 1;
1662 format_len -= len + 1;
1666 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1667 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1668 TIME is specified as (HIGH LOW . IGNORED), as returned by
1669 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1670 is also still accepted.
1671 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1672 as Universal Time; nil means describe TIME in the local time zone.
1673 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1674 by text that describes the specified date and time in TIME:
1676 %Y is the year, %y within the century, %C the century.
1677 %G is the year corresponding to the ISO week, %g within the century.
1678 %m is the numeric month.
1679 %b and %h are the locale's abbreviated month name, %B the full name.
1680 %d is the day of the month, zero-padded, %e is blank-padded.
1681 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1682 %a is the locale's abbreviated name of the day of week, %A the full name.
1683 %U is the week number starting on Sunday, %W starting on Monday,
1684 %V according to ISO 8601.
1685 %j is the day of the year.
1687 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1688 only blank-padded, %l is like %I blank-padded.
1689 %p is the locale's equivalent of either AM or PM.
1690 %M is the minute.
1691 %S is the second.
1692 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1693 %Z is the time zone name, %z is the numeric form.
1694 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1696 %c is the locale's date and time format.
1697 %x is the locale's "preferred" date format.
1698 %D is like "%m/%d/%y".
1700 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1701 %X is the locale's "preferred" time format.
1703 Finally, %n is a newline, %t is a tab, %% is a literal %.
1705 Certain flags and modifiers are available with some format controls.
1706 The flags are `_', `-', `^' and `#'. For certain characters X,
1707 %_X is like %X, but padded with blanks; %-X is like %X,
1708 but without padding. %^X is like %X, but with all textual
1709 characters up-cased; %#X is like %X, but with letter-case of
1710 all textual characters reversed.
1711 %NX (where N stands for an integer) is like %X,
1712 but takes up at least N (a number) positions.
1713 The modifiers are `E' and `O'. For certain characters X,
1714 %EX is a locale's alternative version of %X;
1715 %OX is like %X, but uses the locale's number symbols.
1717 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1718 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1720 time_t value;
1721 int size;
1722 int usec;
1723 int ns;
1724 struct tm *tm;
1725 int ut = ! NILP (universal);
1727 CHECK_STRING (format_string);
1729 if (! (lisp_time_argument (timeval, &value, &usec)
1730 && 0 <= usec && usec < 1000000))
1731 error ("Invalid time specification");
1732 ns = usec * 1000;
1734 format_string = code_convert_string_norecord (format_string,
1735 Vlocale_coding_system, 1);
1737 /* This is probably enough. */
1738 size = SBYTES (format_string) * 6 + 50;
1740 BLOCK_INPUT;
1741 tm = ut ? gmtime (&value) : localtime (&value);
1742 UNBLOCK_INPUT;
1743 if (! tm)
1744 time_overflow ();
1746 synchronize_system_time_locale ();
1748 while (1)
1750 char *buf = (char *) alloca (size + 1);
1751 int result;
1753 buf[0] = '\1';
1754 BLOCK_INPUT;
1755 result = emacs_nmemftime (buf, size, SSDATA (format_string),
1756 SBYTES (format_string),
1757 tm, ut, ns);
1758 UNBLOCK_INPUT;
1759 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1760 return code_convert_string_norecord (make_unibyte_string (buf, result),
1761 Vlocale_coding_system, 0);
1763 /* If buffer was too small, make it bigger and try again. */
1764 BLOCK_INPUT;
1765 result = emacs_nmemftime (NULL, (size_t) -1,
1766 SSDATA (format_string),
1767 SBYTES (format_string),
1768 tm, ut, ns);
1769 UNBLOCK_INPUT;
1770 size = result + 1;
1774 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1775 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1776 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1777 as from `current-time' and `file-attributes', or nil to use the
1778 current time. The obsolete form (HIGH . LOW) is also still accepted.
1779 The list has the following nine members: SEC is an integer between 0
1780 and 60; SEC is 60 for a leap second, which only some operating systems
1781 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1782 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1783 integer between 1 and 12. YEAR is an integer indicating the
1784 four-digit year. DOW is the day of week, an integer between 0 and 6,
1785 where 0 is Sunday. DST is t if daylight saving time is in effect,
1786 otherwise nil. ZONE is an integer indicating the number of seconds
1787 east of Greenwich. (Note that Common Lisp has different meanings for
1788 DOW and ZONE.) */)
1789 (Lisp_Object specified_time)
1791 time_t time_spec;
1792 struct tm save_tm;
1793 struct tm *decoded_time;
1794 Lisp_Object list_args[9];
1796 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1797 error ("Invalid time specification");
1799 BLOCK_INPUT;
1800 decoded_time = localtime (&time_spec);
1801 UNBLOCK_INPUT;
1802 if (! (decoded_time
1803 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= decoded_time->tm_year
1804 && decoded_time->tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1805 time_overflow ();
1806 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1807 XSETFASTINT (list_args[1], decoded_time->tm_min);
1808 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1809 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1810 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1811 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1812 cast below avoids overflow in int arithmetics. */
1813 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1814 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1815 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1817 /* Make a copy, in case gmtime modifies the struct. */
1818 save_tm = *decoded_time;
1819 BLOCK_INPUT;
1820 decoded_time = gmtime (&time_spec);
1821 UNBLOCK_INPUT;
1822 if (decoded_time == 0)
1823 list_args[8] = Qnil;
1824 else
1825 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1826 return Flist (9, list_args);
1829 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1830 the result is representable as an int. Assume OFFSET is small and
1831 nonnegative. */
1832 static int
1833 check_tm_member (Lisp_Object obj, int offset)
1835 EMACS_INT n;
1836 CHECK_NUMBER (obj);
1837 n = XINT (obj);
1838 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1839 time_overflow ();
1840 return n - offset;
1843 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1844 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1845 This is the reverse operation of `decode-time', which see.
1846 ZONE defaults to the current time zone rule. This can
1847 be a string or t (as from `set-time-zone-rule'), or it can be a list
1848 \(as from `current-time-zone') or an integer (as from `decode-time')
1849 applied without consideration for daylight saving time.
1851 You can pass more than 7 arguments; then the first six arguments
1852 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1853 The intervening arguments are ignored.
1854 This feature lets (apply 'encode-time (decode-time ...)) work.
1856 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1857 for example, a DAY of 0 means the day preceding the given month.
1858 Year numbers less than 100 are treated just like other year numbers.
1859 If you want them to stand for years in this century, you must do that yourself.
1861 Years before 1970 are not guaranteed to work. On some systems,
1862 year values as low as 1901 do work.
1864 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1865 (size_t nargs, register Lisp_Object *args)
1867 time_t value;
1868 struct tm tm;
1869 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1871 tm.tm_sec = check_tm_member (args[0], 0);
1872 tm.tm_min = check_tm_member (args[1], 0);
1873 tm.tm_hour = check_tm_member (args[2], 0);
1874 tm.tm_mday = check_tm_member (args[3], 0);
1875 tm.tm_mon = check_tm_member (args[4], 1);
1876 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1877 tm.tm_isdst = -1;
1879 if (CONSP (zone))
1880 zone = Fcar (zone);
1881 if (NILP (zone))
1883 BLOCK_INPUT;
1884 value = mktime (&tm);
1885 UNBLOCK_INPUT;
1887 else
1889 char tzbuf[100];
1890 const char *tzstring;
1891 char **oldenv = environ, **newenv;
1893 if (EQ (zone, Qt))
1894 tzstring = "UTC0";
1895 else if (STRINGP (zone))
1896 tzstring = SSDATA (zone);
1897 else if (INTEGERP (zone))
1899 int abszone = eabs (XINT (zone));
1900 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1901 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1902 tzstring = tzbuf;
1904 else
1905 error ("Invalid time zone specification");
1907 /* Set TZ before calling mktime; merely adjusting mktime's returned
1908 value doesn't suffice, since that would mishandle leap seconds. */
1909 set_time_zone_rule (tzstring);
1911 BLOCK_INPUT;
1912 value = mktime (&tm);
1913 UNBLOCK_INPUT;
1915 /* Restore TZ to previous value. */
1916 newenv = environ;
1917 environ = oldenv;
1918 xfree (newenv);
1919 #ifdef LOCALTIME_CACHE
1920 tzset ();
1921 #endif
1924 if (value == (time_t) -1)
1925 time_overflow ();
1927 return make_time (value);
1930 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1931 doc: /* Return the current local time, as a human-readable string.
1932 Programs can use this function to decode a time,
1933 since the number of columns in each field is fixed
1934 if the year is in the range 1000-9999.
1935 The format is `Sun Sep 16 01:03:52 1973'.
1936 However, see also the functions `decode-time' and `format-time-string'
1937 which provide a much more powerful and general facility.
1939 If SPECIFIED-TIME is given, it is a time to format instead of the
1940 current time. The argument should have the form (HIGH LOW . IGNORED).
1941 Thus, you can use times obtained from `current-time' and from
1942 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1943 but this is considered obsolete. */)
1944 (Lisp_Object specified_time)
1946 time_t value;
1947 struct tm *tm;
1948 register char *tem;
1950 if (! lisp_time_argument (specified_time, &value, NULL))
1951 error ("Invalid time specification");
1953 /* Convert to a string, checking for out-of-range time stamps.
1954 Don't use 'ctime', as that might dump core if VALUE is out of
1955 range. */
1956 BLOCK_INPUT;
1957 tm = localtime (&value);
1958 UNBLOCK_INPUT;
1959 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1960 time_overflow ();
1962 /* Remove the trailing newline. */
1963 tem[strlen (tem) - 1] = '\0';
1965 return build_string (tem);
1968 /* Yield A - B, measured in seconds.
1969 This function is copied from the GNU C Library. */
1970 static int
1971 tm_diff (struct tm *a, struct tm *b)
1973 /* Compute intervening leap days correctly even if year is negative.
1974 Take care to avoid int overflow in leap day calculations,
1975 but it's OK to assume that A and B are close to each other. */
1976 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1977 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1978 int a100 = a4 / 25 - (a4 % 25 < 0);
1979 int b100 = b4 / 25 - (b4 % 25 < 0);
1980 int a400 = a100 >> 2;
1981 int b400 = b100 >> 2;
1982 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1983 int years = a->tm_year - b->tm_year;
1984 int days = (365 * years + intervening_leap_days
1985 + (a->tm_yday - b->tm_yday));
1986 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1987 + (a->tm_min - b->tm_min))
1988 + (a->tm_sec - b->tm_sec));
1991 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1992 doc: /* Return the offset and name for the local time zone.
1993 This returns a list of the form (OFFSET NAME).
1994 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1995 A negative value means west of Greenwich.
1996 NAME is a string giving the name of the time zone.
1997 If SPECIFIED-TIME is given, the time zone offset is determined from it
1998 instead of using the current time. The argument should have the form
1999 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2000 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2001 have the form (HIGH . LOW), but this is considered obsolete.
2003 Some operating systems cannot provide all this information to Emacs;
2004 in this case, `current-time-zone' returns a list containing nil for
2005 the data it can't find. */)
2006 (Lisp_Object specified_time)
2008 time_t value;
2009 struct tm *t;
2010 struct tm gmt;
2012 if (!lisp_time_argument (specified_time, &value, NULL))
2013 t = NULL;
2014 else
2016 BLOCK_INPUT;
2017 t = gmtime (&value);
2018 if (t)
2020 gmt = *t;
2021 t = localtime (&value);
2023 UNBLOCK_INPUT;
2026 if (t)
2028 int offset = tm_diff (t, &gmt);
2029 char *s = 0;
2030 char buf[6];
2032 #ifdef HAVE_TM_ZONE
2033 if (t->tm_zone)
2034 s = (char *)t->tm_zone;
2035 #else /* not HAVE_TM_ZONE */
2036 #ifdef HAVE_TZNAME
2037 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2038 s = tzname[t->tm_isdst];
2039 #endif
2040 #endif /* not HAVE_TM_ZONE */
2042 if (!s)
2044 /* No local time zone name is available; use "+-NNNN" instead. */
2045 int am = (offset < 0 ? -offset : offset) / 60;
2046 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2047 s = buf;
2050 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2052 else
2053 return Fmake_list (make_number (2), Qnil);
2056 /* This holds the value of `environ' produced by the previous
2057 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2058 has never been called. */
2059 static char **environbuf;
2061 /* This holds the startup value of the TZ environment variable so it
2062 can be restored if the user calls set-time-zone-rule with a nil
2063 argument. */
2064 static char *initial_tz;
2066 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2067 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2068 If TZ is nil, use implementation-defined default time zone information.
2069 If TZ is t, use Universal Time. */)
2070 (Lisp_Object tz)
2072 const char *tzstring;
2074 /* When called for the first time, save the original TZ. */
2075 if (!environbuf)
2076 initial_tz = (char *) getenv ("TZ");
2078 if (NILP (tz))
2079 tzstring = initial_tz;
2080 else if (EQ (tz, Qt))
2081 tzstring = "UTC0";
2082 else
2084 CHECK_STRING (tz);
2085 tzstring = SSDATA (tz);
2088 set_time_zone_rule (tzstring);
2089 free (environbuf);
2090 environbuf = environ;
2092 return Qnil;
2095 #ifdef LOCALTIME_CACHE
2097 /* These two values are known to load tz files in buggy implementations,
2098 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2099 Their values shouldn't matter in non-buggy implementations.
2100 We don't use string literals for these strings,
2101 since if a string in the environment is in readonly
2102 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2103 See Sun bugs 1113095 and 1114114, ``Timezone routines
2104 improperly modify environment''. */
2106 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2107 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2109 #endif
2111 /* Set the local time zone rule to TZSTRING.
2112 This allocates memory into `environ', which it is the caller's
2113 responsibility to free. */
2115 void
2116 set_time_zone_rule (const char *tzstring)
2118 int envptrs;
2119 char **from, **to, **newenv;
2121 /* Make the ENVIRON vector longer with room for TZSTRING. */
2122 for (from = environ; *from; from++)
2123 continue;
2124 envptrs = from - environ + 2;
2125 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2126 + (tzstring ? strlen (tzstring) + 4 : 0));
2128 /* Add TZSTRING to the end of environ, as a value for TZ. */
2129 if (tzstring)
2131 char *t = (char *) (to + envptrs);
2132 strcpy (t, "TZ=");
2133 strcat (t, tzstring);
2134 *to++ = t;
2137 /* Copy the old environ vector elements into NEWENV,
2138 but don't copy the TZ variable.
2139 So we have only one definition of TZ, which came from TZSTRING. */
2140 for (from = environ; *from; from++)
2141 if (strncmp (*from, "TZ=", 3) != 0)
2142 *to++ = *from;
2143 *to = 0;
2145 environ = newenv;
2147 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2148 the TZ variable is stored. If we do not have a TZSTRING,
2149 TO points to the vector slot which has the terminating null. */
2151 #ifdef LOCALTIME_CACHE
2153 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2154 "US/Pacific" that loads a tz file, then changes to a value like
2155 "XXX0" that does not load a tz file, and then changes back to
2156 its original value, the last change is (incorrectly) ignored.
2157 Also, if TZ changes twice in succession to values that do
2158 not load a tz file, tzset can dump core (see Sun bug#1225179).
2159 The following code works around these bugs. */
2161 if (tzstring)
2163 /* Temporarily set TZ to a value that loads a tz file
2164 and that differs from tzstring. */
2165 char *tz = *newenv;
2166 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2167 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2168 tzset ();
2169 *newenv = tz;
2171 else
2173 /* The implied tzstring is unknown, so temporarily set TZ to
2174 two different values that each load a tz file. */
2175 *to = set_time_zone_rule_tz1;
2176 to[1] = 0;
2177 tzset ();
2178 *to = set_time_zone_rule_tz2;
2179 tzset ();
2180 *to = 0;
2183 /* Now TZ has the desired value, and tzset can be invoked safely. */
2186 tzset ();
2187 #endif
2190 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2191 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2192 type of object is Lisp_String). INHERIT is passed to
2193 INSERT_FROM_STRING_FUNC as the last argument. */
2195 static void
2196 general_insert_function (void (*insert_func)
2197 (const char *, EMACS_INT),
2198 void (*insert_from_string_func)
2199 (Lisp_Object, EMACS_INT, EMACS_INT,
2200 EMACS_INT, EMACS_INT, int),
2201 int inherit, size_t nargs, Lisp_Object *args)
2203 register size_t argnum;
2204 register Lisp_Object val;
2206 for (argnum = 0; argnum < nargs; argnum++)
2208 val = args[argnum];
2209 if (CHARACTERP (val))
2211 unsigned char str[MAX_MULTIBYTE_LENGTH];
2212 int len;
2214 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2215 len = CHAR_STRING (XFASTINT (val), str);
2216 else
2218 str[0] = (ASCII_CHAR_P (XINT (val))
2219 ? XINT (val)
2220 : multibyte_char_to_unibyte (XINT (val)));
2221 len = 1;
2223 (*insert_func) ((char *) str, len);
2225 else if (STRINGP (val))
2227 (*insert_from_string_func) (val, 0, 0,
2228 SCHARS (val),
2229 SBYTES (val),
2230 inherit);
2232 else
2233 wrong_type_argument (Qchar_or_string_p, val);
2237 void
2238 insert1 (Lisp_Object arg)
2240 Finsert (1, &arg);
2244 /* Callers passing one argument to Finsert need not gcpro the
2245 argument "array", since the only element of the array will
2246 not be used after calling insert or insert_from_string, so
2247 we don't care if it gets trashed. */
2249 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2250 doc: /* Insert the arguments, either strings or characters, at point.
2251 Point and before-insertion markers move forward to end up
2252 after the inserted text.
2253 Any other markers at the point of insertion remain before the text.
2255 If the current buffer is multibyte, unibyte strings are converted
2256 to multibyte for insertion (see `string-make-multibyte').
2257 If the current buffer is unibyte, multibyte strings are converted
2258 to unibyte for insertion (see `string-make-unibyte').
2260 When operating on binary data, it may be necessary to preserve the
2261 original bytes of a unibyte string when inserting it into a multibyte
2262 buffer; to accomplish this, apply `string-as-multibyte' to the string
2263 and insert the result.
2265 usage: (insert &rest ARGS) */)
2266 (size_t nargs, register Lisp_Object *args)
2268 general_insert_function (insert, insert_from_string, 0, nargs, args);
2269 return Qnil;
2272 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2273 0, MANY, 0,
2274 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2275 Point and before-insertion markers move forward to end up
2276 after the inserted text.
2277 Any other markers at the point of insertion remain before the text.
2279 If the current buffer is multibyte, unibyte strings are converted
2280 to multibyte for insertion (see `unibyte-char-to-multibyte').
2281 If the current buffer is unibyte, multibyte strings are converted
2282 to unibyte for insertion.
2284 usage: (insert-and-inherit &rest ARGS) */)
2285 (size_t nargs, register Lisp_Object *args)
2287 general_insert_function (insert_and_inherit, insert_from_string, 1,
2288 nargs, args);
2289 return Qnil;
2292 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2293 doc: /* Insert strings or characters at point, relocating markers after the text.
2294 Point and markers move forward to end up after the inserted text.
2296 If the current buffer is multibyte, unibyte strings are converted
2297 to multibyte for insertion (see `unibyte-char-to-multibyte').
2298 If the current buffer is unibyte, multibyte strings are converted
2299 to unibyte for insertion.
2301 usage: (insert-before-markers &rest ARGS) */)
2302 (size_t nargs, register Lisp_Object *args)
2304 general_insert_function (insert_before_markers,
2305 insert_from_string_before_markers, 0,
2306 nargs, args);
2307 return Qnil;
2310 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2311 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2312 doc: /* Insert text at point, relocating markers and inheriting properties.
2313 Point and markers move forward to end up after the inserted text.
2315 If the current buffer is multibyte, unibyte strings are converted
2316 to multibyte for insertion (see `unibyte-char-to-multibyte').
2317 If the current buffer is unibyte, multibyte strings are converted
2318 to unibyte for insertion.
2320 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2321 (size_t nargs, register Lisp_Object *args)
2323 general_insert_function (insert_before_markers_and_inherit,
2324 insert_from_string_before_markers, 1,
2325 nargs, args);
2326 return Qnil;
2329 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2330 doc: /* Insert COUNT copies of CHARACTER.
2331 Point, and before-insertion markers, are relocated as in the function `insert'.
2332 The optional third arg INHERIT, if non-nil, says to inherit text properties
2333 from adjoining text, if those properties are sticky. */)
2334 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2336 register char *string;
2337 register EMACS_INT stringlen;
2338 register int i;
2339 register EMACS_INT n;
2340 int len;
2341 unsigned char str[MAX_MULTIBYTE_LENGTH];
2343 CHECK_NUMBER (character);
2344 CHECK_NUMBER (count);
2346 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2347 len = CHAR_STRING (XFASTINT (character), str);
2348 else
2349 str[0] = XFASTINT (character), len = 1;
2350 if (MOST_POSITIVE_FIXNUM / len < XINT (count))
2351 error ("Maximum buffer size would be exceeded");
2352 n = XINT (count) * len;
2353 if (n <= 0)
2354 return Qnil;
2355 stringlen = min (n, 256 * len);
2356 string = (char *) alloca (stringlen);
2357 for (i = 0; i < stringlen; i++)
2358 string[i] = str[i % len];
2359 while (n >= stringlen)
2361 QUIT;
2362 if (!NILP (inherit))
2363 insert_and_inherit (string, stringlen);
2364 else
2365 insert (string, stringlen);
2366 n -= stringlen;
2368 if (n > 0)
2370 if (!NILP (inherit))
2371 insert_and_inherit (string, n);
2372 else
2373 insert (string, n);
2375 return Qnil;
2378 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2379 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2380 Both arguments are required.
2381 BYTE is a number of the range 0..255.
2383 If BYTE is 128..255 and the current buffer is multibyte, the
2384 corresponding eight-bit character is inserted.
2386 Point, and before-insertion markers, are relocated as in the function `insert'.
2387 The optional third arg INHERIT, if non-nil, says to inherit text properties
2388 from adjoining text, if those properties are sticky. */)
2389 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2391 CHECK_NUMBER (byte);
2392 if (XINT (byte) < 0 || XINT (byte) > 255)
2393 args_out_of_range_3 (byte, make_number (0), make_number (255));
2394 if (XINT (byte) >= 128
2395 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2396 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2397 return Finsert_char (byte, count, inherit);
2401 /* Making strings from buffer contents. */
2403 /* Return a Lisp_String containing the text of the current buffer from
2404 START to END. If text properties are in use and the current buffer
2405 has properties in the range specified, the resulting string will also
2406 have them, if PROPS is nonzero.
2408 We don't want to use plain old make_string here, because it calls
2409 make_uninit_string, which can cause the buffer arena to be
2410 compacted. make_string has no way of knowing that the data has
2411 been moved, and thus copies the wrong data into the string. This
2412 doesn't effect most of the other users of make_string, so it should
2413 be left as is. But we should use this function when conjuring
2414 buffer substrings. */
2416 Lisp_Object
2417 make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
2419 EMACS_INT start_byte = CHAR_TO_BYTE (start);
2420 EMACS_INT end_byte = CHAR_TO_BYTE (end);
2422 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2425 /* Return a Lisp_String containing the text of the current buffer from
2426 START / START_BYTE to END / END_BYTE.
2428 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 nonzero.
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_both (EMACS_INT start, EMACS_INT start_byte,
2442 EMACS_INT end, EMACS_INT end_byte, int props)
2444 Lisp_Object result, tem, tem1;
2446 if (start < GPT && GPT < end)
2447 move_gap (start);
2449 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2450 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2451 else
2452 result = make_uninit_string (end - start);
2453 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2455 /* If desired, update and copy the text properties. */
2456 if (props)
2458 update_buffer_properties (start, end);
2460 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2461 tem1 = Ftext_properties_at (make_number (start), Qnil);
2463 if (XINT (tem) != end || !NILP (tem1))
2464 copy_intervals_to_string (result, current_buffer, start,
2465 end - start);
2468 return result;
2471 /* Call Vbuffer_access_fontify_functions for the range START ... END
2472 in the current buffer, if necessary. */
2474 static void
2475 update_buffer_properties (EMACS_INT start, EMACS_INT end)
2477 /* If this buffer has some access functions,
2478 call them, specifying the range of the buffer being accessed. */
2479 if (!NILP (Vbuffer_access_fontify_functions))
2481 Lisp_Object args[3];
2482 Lisp_Object tem;
2484 args[0] = Qbuffer_access_fontify_functions;
2485 XSETINT (args[1], start);
2486 XSETINT (args[2], end);
2488 /* But don't call them if we can tell that the work
2489 has already been done. */
2490 if (!NILP (Vbuffer_access_fontified_property))
2492 tem = Ftext_property_any (args[1], args[2],
2493 Vbuffer_access_fontified_property,
2494 Qnil, Qnil);
2495 if (! NILP (tem))
2496 Frun_hook_with_args (3, args);
2498 else
2499 Frun_hook_with_args (3, args);
2503 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2504 doc: /* Return the contents of part of the current buffer as a string.
2505 The two arguments START and END are character positions;
2506 they can be in either order.
2507 The string returned is multibyte if the buffer is multibyte.
2509 This function copies the text properties of that part of the buffer
2510 into the result string; if you don't want the text properties,
2511 use `buffer-substring-no-properties' instead. */)
2512 (Lisp_Object start, Lisp_Object end)
2514 register EMACS_INT b, e;
2516 validate_region (&start, &end);
2517 b = XINT (start);
2518 e = XINT (end);
2520 return make_buffer_string (b, e, 1);
2523 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2524 Sbuffer_substring_no_properties, 2, 2, 0,
2525 doc: /* Return the characters of part of the buffer, without the text properties.
2526 The two arguments START and END are character positions;
2527 they can be in either order. */)
2528 (Lisp_Object start, Lisp_Object end)
2530 register EMACS_INT b, e;
2532 validate_region (&start, &end);
2533 b = XINT (start);
2534 e = XINT (end);
2536 return make_buffer_string (b, e, 0);
2539 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2540 doc: /* Return the contents of the current buffer as a string.
2541 If narrowing is in effect, this function returns only the visible part
2542 of the buffer. */)
2543 (void)
2545 return make_buffer_string (BEGV, ZV, 1);
2548 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2549 1, 3, 0,
2550 doc: /* Insert before point a substring of the contents of BUFFER.
2551 BUFFER may be a buffer or a buffer name.
2552 Arguments START and END are character positions specifying the substring.
2553 They default to the values of (point-min) and (point-max) in BUFFER. */)
2554 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2556 register EMACS_INT b, e, temp;
2557 register struct buffer *bp, *obuf;
2558 Lisp_Object buf;
2560 buf = Fget_buffer (buffer);
2561 if (NILP (buf))
2562 nsberror (buffer);
2563 bp = XBUFFER (buf);
2564 if (NILP (BVAR (bp, name)))
2565 error ("Selecting deleted buffer");
2567 if (NILP (start))
2568 b = BUF_BEGV (bp);
2569 else
2571 CHECK_NUMBER_COERCE_MARKER (start);
2572 b = XINT (start);
2574 if (NILP (end))
2575 e = BUF_ZV (bp);
2576 else
2578 CHECK_NUMBER_COERCE_MARKER (end);
2579 e = XINT (end);
2582 if (b > e)
2583 temp = b, b = e, e = temp;
2585 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2586 args_out_of_range (start, end);
2588 obuf = current_buffer;
2589 set_buffer_internal_1 (bp);
2590 update_buffer_properties (b, e);
2591 set_buffer_internal_1 (obuf);
2593 insert_from_buffer (bp, b, e - b, 0);
2594 return Qnil;
2597 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2598 6, 6, 0,
2599 doc: /* Compare two substrings of two buffers; return result as number.
2600 the value is -N if first string is less after N-1 chars,
2601 +N if first string is greater after N-1 chars, or 0 if strings match.
2602 Each substring is represented as three arguments: BUFFER, START and END.
2603 That makes six args in all, three for each substring.
2605 The value of `case-fold-search' in the current buffer
2606 determines whether case is significant or ignored. */)
2607 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2609 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2610 register struct buffer *bp1, *bp2;
2611 register Lisp_Object trt
2612 = (!NILP (BVAR (current_buffer, case_fold_search))
2613 ? BVAR (current_buffer, case_canon_table) : Qnil);
2614 EMACS_INT chars = 0;
2615 EMACS_INT i1, i2, i1_byte, i2_byte;
2617 /* Find the first buffer and its substring. */
2619 if (NILP (buffer1))
2620 bp1 = current_buffer;
2621 else
2623 Lisp_Object buf1;
2624 buf1 = Fget_buffer (buffer1);
2625 if (NILP (buf1))
2626 nsberror (buffer1);
2627 bp1 = XBUFFER (buf1);
2628 if (NILP (BVAR (bp1, name)))
2629 error ("Selecting deleted buffer");
2632 if (NILP (start1))
2633 begp1 = BUF_BEGV (bp1);
2634 else
2636 CHECK_NUMBER_COERCE_MARKER (start1);
2637 begp1 = XINT (start1);
2639 if (NILP (end1))
2640 endp1 = BUF_ZV (bp1);
2641 else
2643 CHECK_NUMBER_COERCE_MARKER (end1);
2644 endp1 = XINT (end1);
2647 if (begp1 > endp1)
2648 temp = begp1, begp1 = endp1, endp1 = temp;
2650 if (!(BUF_BEGV (bp1) <= begp1
2651 && begp1 <= endp1
2652 && endp1 <= BUF_ZV (bp1)))
2653 args_out_of_range (start1, end1);
2655 /* Likewise for second substring. */
2657 if (NILP (buffer2))
2658 bp2 = current_buffer;
2659 else
2661 Lisp_Object buf2;
2662 buf2 = Fget_buffer (buffer2);
2663 if (NILP (buf2))
2664 nsberror (buffer2);
2665 bp2 = XBUFFER (buf2);
2666 if (NILP (BVAR (bp2, name)))
2667 error ("Selecting deleted buffer");
2670 if (NILP (start2))
2671 begp2 = BUF_BEGV (bp2);
2672 else
2674 CHECK_NUMBER_COERCE_MARKER (start2);
2675 begp2 = XINT (start2);
2677 if (NILP (end2))
2678 endp2 = BUF_ZV (bp2);
2679 else
2681 CHECK_NUMBER_COERCE_MARKER (end2);
2682 endp2 = XINT (end2);
2685 if (begp2 > endp2)
2686 temp = begp2, begp2 = endp2, endp2 = temp;
2688 if (!(BUF_BEGV (bp2) <= begp2
2689 && begp2 <= endp2
2690 && endp2 <= BUF_ZV (bp2)))
2691 args_out_of_range (start2, end2);
2693 i1 = begp1;
2694 i2 = begp2;
2695 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2696 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2698 while (i1 < endp1 && i2 < endp2)
2700 /* When we find a mismatch, we must compare the
2701 characters, not just the bytes. */
2702 int c1, c2;
2704 QUIT;
2706 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2708 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2709 BUF_INC_POS (bp1, i1_byte);
2710 i1++;
2712 else
2714 c1 = BUF_FETCH_BYTE (bp1, i1);
2715 MAKE_CHAR_MULTIBYTE (c1);
2716 i1++;
2719 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2721 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2722 BUF_INC_POS (bp2, i2_byte);
2723 i2++;
2725 else
2727 c2 = BUF_FETCH_BYTE (bp2, i2);
2728 MAKE_CHAR_MULTIBYTE (c2);
2729 i2++;
2732 if (!NILP (trt))
2734 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2735 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2737 if (c1 < c2)
2738 return make_number (- 1 - chars);
2739 if (c1 > c2)
2740 return make_number (chars + 1);
2742 chars++;
2745 /* The strings match as far as they go.
2746 If one is shorter, that one is less. */
2747 if (chars < endp1 - begp1)
2748 return make_number (chars + 1);
2749 else if (chars < endp2 - begp2)
2750 return make_number (- chars - 1);
2752 /* Same length too => they are equal. */
2753 return make_number (0);
2756 static Lisp_Object
2757 subst_char_in_region_unwind (Lisp_Object arg)
2759 return BVAR (current_buffer, undo_list) = arg;
2762 static Lisp_Object
2763 subst_char_in_region_unwind_1 (Lisp_Object arg)
2765 return BVAR (current_buffer, filename) = arg;
2768 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2769 Ssubst_char_in_region, 4, 5, 0,
2770 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2771 If optional arg NOUNDO is non-nil, don't record this change for undo
2772 and don't mark the buffer as really changed.
2773 Both characters must have the same length of multi-byte form. */)
2774 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2776 register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
2777 /* Keep track of the first change in the buffer:
2778 if 0 we haven't found it yet.
2779 if < 0 we've found it and we've run the before-change-function.
2780 if > 0 we've actually performed it and the value is its position. */
2781 EMACS_INT changed = 0;
2782 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2783 unsigned char *p;
2784 int count = SPECPDL_INDEX ();
2785 #define COMBINING_NO 0
2786 #define COMBINING_BEFORE 1
2787 #define COMBINING_AFTER 2
2788 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2789 int maybe_byte_combining = COMBINING_NO;
2790 EMACS_INT last_changed = 0;
2791 int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2793 restart:
2795 validate_region (&start, &end);
2796 CHECK_NUMBER (fromchar);
2797 CHECK_NUMBER (tochar);
2799 if (multibyte_p)
2801 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2802 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2803 error ("Characters in `subst-char-in-region' have different byte-lengths");
2804 if (!ASCII_BYTE_P (*tostr))
2806 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2807 complete multibyte character, it may be combined with the
2808 after bytes. If it is in the range 0xA0..0xFF, it may be
2809 combined with the before and after bytes. */
2810 if (!CHAR_HEAD_P (*tostr))
2811 maybe_byte_combining = COMBINING_BOTH;
2812 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2813 maybe_byte_combining = COMBINING_AFTER;
2816 else
2818 len = 1;
2819 fromstr[0] = XFASTINT (fromchar);
2820 tostr[0] = XFASTINT (tochar);
2823 pos = XINT (start);
2824 pos_byte = CHAR_TO_BYTE (pos);
2825 stop = CHAR_TO_BYTE (XINT (end));
2826 end_byte = stop;
2828 /* If we don't want undo, turn off putting stuff on the list.
2829 That's faster than getting rid of things,
2830 and it prevents even the entry for a first change.
2831 Also inhibit locking the file. */
2832 if (!changed && !NILP (noundo))
2834 record_unwind_protect (subst_char_in_region_unwind,
2835 BVAR (current_buffer, undo_list));
2836 BVAR (current_buffer, undo_list) = Qt;
2837 /* Don't do file-locking. */
2838 record_unwind_protect (subst_char_in_region_unwind_1,
2839 BVAR (current_buffer, filename));
2840 BVAR (current_buffer, filename) = Qnil;
2843 if (pos_byte < GPT_BYTE)
2844 stop = min (stop, GPT_BYTE);
2845 while (1)
2847 EMACS_INT pos_byte_next = pos_byte;
2849 if (pos_byte >= stop)
2851 if (pos_byte >= end_byte) break;
2852 stop = end_byte;
2854 p = BYTE_POS_ADDR (pos_byte);
2855 if (multibyte_p)
2856 INC_POS (pos_byte_next);
2857 else
2858 ++pos_byte_next;
2859 if (pos_byte_next - pos_byte == len
2860 && p[0] == fromstr[0]
2861 && (len == 1
2862 || (p[1] == fromstr[1]
2863 && (len == 2 || (p[2] == fromstr[2]
2864 && (len == 3 || p[3] == fromstr[3]))))))
2866 if (changed < 0)
2867 /* We've already seen this and run the before-change-function;
2868 this time we only need to record the actual position. */
2869 changed = pos;
2870 else if (!changed)
2872 changed = -1;
2873 modify_region (current_buffer, pos, XINT (end), 0);
2875 if (! NILP (noundo))
2877 if (MODIFF - 1 == SAVE_MODIFF)
2878 SAVE_MODIFF++;
2879 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2880 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2883 /* The before-change-function may have moved the gap
2884 or even modified the buffer so we should start over. */
2885 goto restart;
2888 /* Take care of the case where the new character
2889 combines with neighboring bytes. */
2890 if (maybe_byte_combining
2891 && (maybe_byte_combining == COMBINING_AFTER
2892 ? (pos_byte_next < Z_BYTE
2893 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2894 : ((pos_byte_next < Z_BYTE
2895 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2896 || (pos_byte > BEG_BYTE
2897 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2899 Lisp_Object tem, string;
2901 struct gcpro gcpro1;
2903 tem = BVAR (current_buffer, undo_list);
2904 GCPRO1 (tem);
2906 /* Make a multibyte string containing this single character. */
2907 string = make_multibyte_string ((char *) tostr, 1, len);
2908 /* replace_range is less efficient, because it moves the gap,
2909 but it handles combining correctly. */
2910 replace_range (pos, pos + 1, string,
2911 0, 0, 1);
2912 pos_byte_next = CHAR_TO_BYTE (pos);
2913 if (pos_byte_next > pos_byte)
2914 /* Before combining happened. We should not increment
2915 POS. So, to cancel the later increment of POS,
2916 decrease it now. */
2917 pos--;
2918 else
2919 INC_POS (pos_byte_next);
2921 if (! NILP (noundo))
2922 BVAR (current_buffer, undo_list) = tem;
2924 UNGCPRO;
2926 else
2928 if (NILP (noundo))
2929 record_change (pos, 1);
2930 for (i = 0; i < len; i++) *p++ = tostr[i];
2932 last_changed = pos + 1;
2934 pos_byte = pos_byte_next;
2935 pos++;
2938 if (changed > 0)
2940 signal_after_change (changed,
2941 last_changed - changed, last_changed - changed);
2942 update_compositions (changed, last_changed, CHECK_ALL);
2945 unbind_to (count, Qnil);
2946 return Qnil;
2950 static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
2951 Lisp_Object);
2953 /* Helper function for Ftranslate_region_internal.
2955 Check if a character sequence at POS (POS_BYTE) matches an element
2956 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2957 element is found, return it. Otherwise return Qnil. */
2959 static Lisp_Object
2960 check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
2961 Lisp_Object val)
2963 int buf_size = 16, buf_used = 0;
2964 int *buf = alloca (sizeof (int) * buf_size);
2966 for (; CONSP (val); val = XCDR (val))
2968 Lisp_Object elt;
2969 EMACS_INT len, i;
2971 elt = XCAR (val);
2972 if (! CONSP (elt))
2973 continue;
2974 elt = XCAR (elt);
2975 if (! VECTORP (elt))
2976 continue;
2977 len = ASIZE (elt);
2978 if (len <= end - pos)
2980 for (i = 0; i < len; i++)
2982 if (buf_used <= i)
2984 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2985 int len1;
2987 if (buf_used == buf_size)
2989 int *newbuf;
2991 buf_size += 16;
2992 newbuf = alloca (sizeof (int) * buf_size);
2993 memcpy (newbuf, buf, sizeof (int) * buf_used);
2994 buf = newbuf;
2996 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
2997 pos_byte += len1;
2999 if (XINT (AREF (elt, i)) != buf[i])
3000 break;
3002 if (i == len)
3003 return XCAR (val);
3006 return Qnil;
3010 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3011 Stranslate_region_internal, 3, 3, 0,
3012 doc: /* Internal use only.
3013 From START to END, translate characters according to TABLE.
3014 TABLE is a string or a char-table; the Nth character in it is the
3015 mapping for the character with code N.
3016 It returns the number of characters changed. */)
3017 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3019 register unsigned char *tt; /* Trans table. */
3020 register int nc; /* New character. */
3021 int cnt; /* Number of changes made. */
3022 EMACS_INT size; /* Size of translate table. */
3023 EMACS_INT pos, pos_byte, end_pos;
3024 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3025 int string_multibyte IF_LINT (= 0);
3027 validate_region (&start, &end);
3028 if (CHAR_TABLE_P (table))
3030 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3031 error ("Not a translation table");
3032 size = MAX_CHAR;
3033 tt = NULL;
3035 else
3037 CHECK_STRING (table);
3039 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3040 table = string_make_unibyte (table);
3041 string_multibyte = SCHARS (table) < SBYTES (table);
3042 size = SBYTES (table);
3043 tt = SDATA (table);
3046 pos = XINT (start);
3047 pos_byte = CHAR_TO_BYTE (pos);
3048 end_pos = XINT (end);
3049 modify_region (current_buffer, pos, end_pos, 0);
3051 cnt = 0;
3052 for (; pos < end_pos; )
3054 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3055 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3056 int len, str_len;
3057 int oc;
3058 Lisp_Object val;
3060 if (multibyte)
3061 oc = STRING_CHAR_AND_LENGTH (p, len);
3062 else
3063 oc = *p, len = 1;
3064 if (oc < size)
3066 if (tt)
3068 /* Reload as signal_after_change in last iteration may GC. */
3069 tt = SDATA (table);
3070 if (string_multibyte)
3072 str = tt + string_char_to_byte (table, oc);
3073 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3075 else
3077 nc = tt[oc];
3078 if (! ASCII_BYTE_P (nc) && multibyte)
3080 str_len = BYTE8_STRING (nc, buf);
3081 str = buf;
3083 else
3085 str_len = 1;
3086 str = tt + oc;
3090 else
3092 EMACS_INT c;
3094 nc = oc;
3095 val = CHAR_TABLE_REF (table, oc);
3096 if (CHARACTERP (val)
3097 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3099 nc = c;
3100 str_len = CHAR_STRING (nc, buf);
3101 str = buf;
3103 else if (VECTORP (val) || (CONSP (val)))
3105 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3106 where TO is TO-CHAR or [TO-CHAR ...]. */
3107 nc = -1;
3111 if (nc != oc && nc >= 0)
3113 /* Simple one char to one char translation. */
3114 if (len != str_len)
3116 Lisp_Object string;
3118 /* This is less efficient, because it moves the gap,
3119 but it should handle multibyte characters correctly. */
3120 string = make_multibyte_string ((char *) str, 1, str_len);
3121 replace_range (pos, pos + 1, string, 1, 0, 1);
3122 len = str_len;
3124 else
3126 record_change (pos, 1);
3127 while (str_len-- > 0)
3128 *p++ = *str++;
3129 signal_after_change (pos, 1, 1);
3130 update_compositions (pos, pos + 1, CHECK_BORDER);
3132 ++cnt;
3134 else if (nc < 0)
3136 Lisp_Object string;
3138 if (CONSP (val))
3140 val = check_translation (pos, pos_byte, end_pos, val);
3141 if (NILP (val))
3143 pos_byte += len;
3144 pos++;
3145 continue;
3147 /* VAL is ([FROM-CHAR ...] . TO). */
3148 len = ASIZE (XCAR (val));
3149 val = XCDR (val);
3151 else
3152 len = 1;
3154 if (VECTORP (val))
3156 string = Fconcat (1, &val);
3158 else
3160 string = Fmake_string (make_number (1), val);
3162 replace_range (pos, pos + len, string, 1, 0, 1);
3163 pos_byte += SBYTES (string);
3164 pos += SCHARS (string);
3165 cnt += SCHARS (string);
3166 end_pos += SCHARS (string) - len;
3167 continue;
3170 pos_byte += len;
3171 pos++;
3174 return make_number (cnt);
3177 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3178 doc: /* Delete the text between point and mark.
3180 When called from a program, expects two arguments,
3181 positions (integers or markers) specifying the stretch to be deleted. */)
3182 (Lisp_Object start, Lisp_Object end)
3184 validate_region (&start, &end);
3185 del_range (XINT (start), XINT (end));
3186 return Qnil;
3189 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3190 Sdelete_and_extract_region, 2, 2, 0,
3191 doc: /* Delete the text between START and END and return it. */)
3192 (Lisp_Object start, Lisp_Object end)
3194 validate_region (&start, &end);
3195 if (XINT (start) == XINT (end))
3196 return empty_unibyte_string;
3197 return del_range_1 (XINT (start), XINT (end), 1, 1);
3200 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3201 doc: /* Remove restrictions (narrowing) from current buffer.
3202 This allows the buffer's full text to be seen and edited. */)
3203 (void)
3205 if (BEG != BEGV || Z != ZV)
3206 current_buffer->clip_changed = 1;
3207 BEGV = BEG;
3208 BEGV_BYTE = BEG_BYTE;
3209 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3210 /* Changing the buffer bounds invalidates any recorded current column. */
3211 invalidate_current_column ();
3212 return Qnil;
3215 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3216 doc: /* Restrict editing in this buffer to the current region.
3217 The rest of the text becomes temporarily invisible and untouchable
3218 but is not deleted; if you save the buffer in a file, the invisible
3219 text is included in the file. \\[widen] makes all visible again.
3220 See also `save-restriction'.
3222 When calling from a program, pass two arguments; positions (integers
3223 or markers) bounding the text that should remain visible. */)
3224 (register Lisp_Object start, Lisp_Object end)
3226 CHECK_NUMBER_COERCE_MARKER (start);
3227 CHECK_NUMBER_COERCE_MARKER (end);
3229 if (XINT (start) > XINT (end))
3231 Lisp_Object tem;
3232 tem = start; start = end; end = tem;
3235 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3236 args_out_of_range (start, end);
3238 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3239 current_buffer->clip_changed = 1;
3241 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3242 SET_BUF_ZV (current_buffer, XFASTINT (end));
3243 if (PT < XFASTINT (start))
3244 SET_PT (XFASTINT (start));
3245 if (PT > XFASTINT (end))
3246 SET_PT (XFASTINT (end));
3247 /* Changing the buffer bounds invalidates any recorded current column. */
3248 invalidate_current_column ();
3249 return Qnil;
3252 Lisp_Object
3253 save_restriction_save (void)
3255 if (BEGV == BEG && ZV == Z)
3256 /* The common case that the buffer isn't narrowed.
3257 We return just the buffer object, which save_restriction_restore
3258 recognizes as meaning `no restriction'. */
3259 return Fcurrent_buffer ();
3260 else
3261 /* We have to save a restriction, so return a pair of markers, one
3262 for the beginning and one for the end. */
3264 Lisp_Object beg, end;
3266 beg = buildmark (BEGV, BEGV_BYTE);
3267 end = buildmark (ZV, ZV_BYTE);
3269 /* END must move forward if text is inserted at its exact location. */
3270 XMARKER(end)->insertion_type = 1;
3272 return Fcons (beg, end);
3276 Lisp_Object
3277 save_restriction_restore (Lisp_Object data)
3279 struct buffer *cur = NULL;
3280 struct buffer *buf = (CONSP (data)
3281 ? XMARKER (XCAR (data))->buffer
3282 : XBUFFER (data));
3284 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3285 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3286 is the case if it is or has an indirect buffer), then make
3287 sure it is current before we update BEGV, so
3288 set_buffer_internal takes care of managing those markers. */
3289 cur = current_buffer;
3290 set_buffer_internal (buf);
3293 if (CONSP (data))
3294 /* A pair of marks bounding a saved restriction. */
3296 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3297 struct Lisp_Marker *end = XMARKER (XCDR (data));
3298 eassert (buf == end->buffer);
3300 if (buf /* Verify marker still points to a buffer. */
3301 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3302 /* The restriction has changed from the saved one, so restore
3303 the saved restriction. */
3305 EMACS_INT pt = BUF_PT (buf);
3307 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3308 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3310 if (pt < beg->charpos || pt > end->charpos)
3311 /* The point is outside the new visible range, move it inside. */
3312 SET_BUF_PT_BOTH (buf,
3313 clip_to_bounds (beg->charpos, pt, end->charpos),
3314 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3315 end->bytepos));
3317 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3320 else
3321 /* A buffer, which means that there was no old restriction. */
3323 if (buf /* Verify marker still points to a buffer. */
3324 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3325 /* The buffer has been narrowed, get rid of the narrowing. */
3327 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3328 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3330 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3334 /* Changing the buffer bounds invalidates any recorded current column. */
3335 invalidate_current_column ();
3337 if (cur)
3338 set_buffer_internal (cur);
3340 return Qnil;
3343 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3344 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3345 The buffer's restrictions make parts of the beginning and end invisible.
3346 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3347 This special form, `save-restriction', saves the current buffer's restrictions
3348 when it is entered, and restores them when it is exited.
3349 So any `narrow-to-region' within BODY lasts only until the end of the form.
3350 The old restrictions settings are restored
3351 even in case of abnormal exit (throw or error).
3353 The value returned is the value of the last form in BODY.
3355 Note: if you are using both `save-excursion' and `save-restriction',
3356 use `save-excursion' outermost:
3357 (save-excursion (save-restriction ...))
3359 usage: (save-restriction &rest BODY) */)
3360 (Lisp_Object body)
3362 register Lisp_Object val;
3363 int count = SPECPDL_INDEX ();
3365 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3366 val = Fprogn (body);
3367 return unbind_to (count, val);
3370 /* Buffer for the most recent text displayed by Fmessage_box. */
3371 static char *message_text;
3373 /* Allocated length of that buffer. */
3374 static int message_length;
3376 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3377 doc: /* Display a message at the bottom of the screen.
3378 The message also goes into the `*Messages*' buffer.
3379 \(In keyboard macros, that's all it does.)
3380 Return the message.
3382 The first argument is a format control string, and the rest are data
3383 to be formatted under control of the string. See `format' for details.
3385 Note: Use (message "%s" VALUE) to print the value of expressions and
3386 variables to avoid accidentally interpreting `%' as format specifiers.
3388 If the first argument is nil or the empty string, the function clears
3389 any existing message; this lets the minibuffer contents show. See
3390 also `current-message'.
3392 usage: (message FORMAT-STRING &rest ARGS) */)
3393 (size_t nargs, Lisp_Object *args)
3395 if (NILP (args[0])
3396 || (STRINGP (args[0])
3397 && SBYTES (args[0]) == 0))
3399 message (0);
3400 return args[0];
3402 else
3404 register Lisp_Object val;
3405 val = Fformat (nargs, args);
3406 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3407 return val;
3411 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3412 doc: /* Display a message, in a dialog box if possible.
3413 If a dialog box is not available, use the echo area.
3414 The first argument is a format control string, and the rest are data
3415 to be formatted under control of the string. See `format' for details.
3417 If the first argument is nil or the empty string, clear any existing
3418 message; let the minibuffer contents show.
3420 usage: (message-box FORMAT-STRING &rest ARGS) */)
3421 (size_t nargs, Lisp_Object *args)
3423 if (NILP (args[0]))
3425 message (0);
3426 return Qnil;
3428 else
3430 register Lisp_Object val;
3431 val = Fformat (nargs, args);
3432 #ifdef HAVE_MENUS
3433 /* The MS-DOS frames support popup menus even though they are
3434 not FRAME_WINDOW_P. */
3435 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3436 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3438 Lisp_Object pane, menu;
3439 struct gcpro gcpro1;
3440 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3441 GCPRO1 (pane);
3442 menu = Fcons (val, pane);
3443 Fx_popup_dialog (Qt, menu, Qt);
3444 UNGCPRO;
3445 return val;
3447 #endif /* HAVE_MENUS */
3448 /* Copy the data so that it won't move when we GC. */
3449 if (! message_text)
3451 message_text = (char *)xmalloc (80);
3452 message_length = 80;
3454 if (SBYTES (val) > message_length)
3456 message_length = SBYTES (val);
3457 message_text = (char *)xrealloc (message_text, message_length);
3459 memcpy (message_text, SDATA (val), SBYTES (val));
3460 message2 (message_text, SBYTES (val),
3461 STRING_MULTIBYTE (val));
3462 return val;
3466 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3467 doc: /* Display a message in a dialog box or in the echo area.
3468 If this command was invoked with the mouse, use a dialog box if
3469 `use-dialog-box' is non-nil.
3470 Otherwise, use the echo area.
3471 The first argument is a format control string, and the rest are data
3472 to be formatted under control of the string. See `format' for details.
3474 If the first argument is nil or the empty string, clear any existing
3475 message; let the minibuffer contents show.
3477 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3478 (size_t nargs, Lisp_Object *args)
3480 #ifdef HAVE_MENUS
3481 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3482 && use_dialog_box)
3483 return Fmessage_box (nargs, args);
3484 #endif
3485 return Fmessage (nargs, args);
3488 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3489 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3490 (void)
3492 return current_message ();
3496 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3497 doc: /* Return a copy of STRING with text properties added.
3498 First argument is the string to copy.
3499 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3500 properties to add to the result.
3501 usage: (propertize STRING &rest PROPERTIES) */)
3502 (size_t nargs, Lisp_Object *args)
3504 Lisp_Object properties, string;
3505 struct gcpro gcpro1, gcpro2;
3506 size_t i;
3508 /* Number of args must be odd. */
3509 if ((nargs & 1) == 0)
3510 error ("Wrong number of arguments");
3512 properties = string = Qnil;
3513 GCPRO2 (properties, string);
3515 /* First argument must be a string. */
3516 CHECK_STRING (args[0]);
3517 string = Fcopy_sequence (args[0]);
3519 for (i = 1; i < nargs; i += 2)
3520 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3522 Fadd_text_properties (make_number (0),
3523 make_number (SCHARS (string)),
3524 properties, string);
3525 RETURN_UNGCPRO (string);
3529 /* Number of bytes that STRING will occupy when put into the result.
3530 MULTIBYTE is nonzero if the result should be multibyte. */
3532 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3533 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3534 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3535 : SBYTES (STRING))
3537 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3538 doc: /* Format a string out of a format-string and arguments.
3539 The first argument is a format control string.
3540 The other arguments are substituted into it to make the result, a string.
3542 The format control string may contain %-sequences meaning to substitute
3543 the next available argument:
3545 %s means print a string argument. Actually, prints any object, with `princ'.
3546 %d means print as number in decimal (%o octal, %x hex).
3547 %X is like %x, but uses upper case.
3548 %e means print a number in exponential notation.
3549 %f means print a number in decimal-point notation.
3550 %g means print a number in exponential notation
3551 or decimal-point notation, whichever uses fewer characters.
3552 %c means print a number as a single character.
3553 %S means print any object as an s-expression (using `prin1').
3555 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3556 Use %% to put a single % into the output.
3558 A %-sequence may contain optional flag, width, and precision
3559 specifiers, as follows:
3561 %<flags><width><precision>character
3563 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3565 The + flag character inserts a + before any positive number, while a
3566 space inserts a space before any positive number; these flags only
3567 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3568 The # flag means to use an alternate display form for %o, %x, %X, %e,
3569 %f, and %g sequences. The - and 0 flags affect the width specifier,
3570 as described below.
3572 The width specifier supplies a lower limit for the length of the
3573 printed representation. The padding, if any, normally goes on the
3574 left, but it goes on the right if the - flag is present. The padding
3575 character is normally a space, but it is 0 if the 0 flag is present.
3576 The - flag takes precedence over the 0 flag.
3578 For %e, %f, and %g sequences, the number after the "." in the
3579 precision specifier says how many decimal places to show; if zero, the
3580 decimal point itself is omitted. For %s and %S, the precision
3581 specifier truncates the string to the given width.
3583 usage: (format STRING &rest OBJECTS) */)
3584 (size_t nargs, register Lisp_Object *args)
3586 register size_t n; /* The number of the next arg to substitute */
3587 register size_t total; /* An estimate of the final length */
3588 char *buf, *p;
3589 register char *format, *end, *format_start;
3590 int nchars;
3591 /* Nonzero if the output should be a multibyte string,
3592 which is true if any of the inputs is one. */
3593 int multibyte = 0;
3594 /* When we make a multibyte string, we must pay attention to the
3595 byte combining problem, i.e., a byte may be combined with a
3596 multibyte character of the previous string. This flag tells if we
3597 must consider such a situation or not. */
3598 int maybe_combine_byte;
3599 char *this_format;
3600 /* Precision for each spec, or -1, a flag value meaning no precision
3601 was given in that spec. Element 0, corresponding to the format
3602 string itself, will not be used. Element NARGS, corresponding to
3603 no argument, *will* be assigned to in the case that a `%' and `.'
3604 occur after the final format specifier. */
3605 int *precision = (int *) (alloca ((nargs + 1) * sizeof (int)));
3606 int longest_format;
3607 Lisp_Object val;
3608 int 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 = 0;
3616 /* Each element records, for one argument,
3617 the start and end bytepos in the output string,
3618 and whether the argument is a string with intervals.
3619 info[0] is unused. Unused elements have -1 for start. */
3620 struct info
3622 int start, end, intervals;
3623 } *info = 0;
3625 /* It should not be necessary to GCPRO ARGS, because
3626 the caller in the interpreter should take care of that. */
3628 /* Try to determine whether the result should be multibyte.
3629 This is not always right; sometimes the result needs to be multibyte
3630 because of an object that we will pass through prin1,
3631 and in that case, we won't know it here. */
3632 for (n = 0; n < nargs; n++)
3634 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3635 multibyte = 1;
3636 /* Piggyback on this loop to initialize precision[N]. */
3637 precision[n] = -1;
3639 precision[nargs] = -1;
3641 CHECK_STRING (args[0]);
3642 /* We may have to change "%S" to "%s". */
3643 args[0] = Fcopy_sequence (args[0]);
3645 /* GC should never happen here, so abort if it does. */
3646 abort_on_gc++;
3648 /* If we start out planning a unibyte result,
3649 then discover it has to be multibyte, we jump back to retry.
3650 That can only happen from the first large while loop below. */
3651 retry:
3653 format = SSDATA (args[0]);
3654 format_start = format;
3655 end = format + SBYTES (args[0]);
3656 longest_format = 0;
3658 /* Make room in result for all the non-%-codes in the control string. */
3659 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3661 /* Allocate the info and discarded tables. */
3663 size_t nbytes = (nargs+1) * sizeof *info;
3664 size_t i;
3665 if (!info)
3666 info = (struct info *) alloca (nbytes);
3667 memset (info, 0, nbytes);
3668 for (i = 0; i < nargs + 1; i++)
3669 info[i].start = -1;
3670 if (!discarded)
3671 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3672 memset (discarded, 0, SBYTES (args[0]));
3675 /* Add to TOTAL enough space to hold the converted arguments. */
3677 n = 0;
3678 while (format != end)
3679 if (*format++ == '%')
3681 EMACS_INT thissize = 0;
3682 EMACS_INT actual_width = 0;
3683 char *this_format_start = format - 1;
3684 int field_width = 0;
3686 /* General format specifications look like
3688 '%' [flags] [field-width] [precision] format
3690 where
3692 flags ::= [-+ #0]+
3693 field-width ::= [0-9]+
3694 precision ::= '.' [0-9]*
3696 If a field-width is specified, it specifies to which width
3697 the output should be padded with blanks, if the output
3698 string is shorter than field-width.
3700 If precision is specified, it specifies the number of
3701 digits to print after the '.' for floats, or the max.
3702 number of chars to print from a string. */
3704 while (format != end
3705 && (*format == '-' || *format == '0' || *format == '#'
3706 || * format == ' ' || *format == '+'))
3707 ++format;
3709 if (*format >= '0' && *format <= '9')
3711 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3712 field_width = 10 * field_width + *format - '0';
3715 /* N is not incremented for another few lines below, so refer to
3716 element N+1 (which might be precision[NARGS]). */
3717 if (*format == '.')
3719 ++format;
3720 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3721 precision[n+1] = 10 * precision[n+1] + *format - '0';
3724 /* Extra +1 for 'l' that we may need to insert into the
3725 format. */
3726 if (format - this_format_start + 2 > longest_format)
3727 longest_format = format - this_format_start + 2;
3729 if (format == end)
3730 error ("Format string ends in middle of format specifier");
3731 if (*format == '%')
3732 format++;
3733 else if (++n >= nargs)
3734 error ("Not enough arguments for format string");
3735 else if (*format == 'S')
3737 /* For `S', prin1 the argument and then treat like a string. */
3738 register Lisp_Object tem;
3739 tem = Fprin1_to_string (args[n], Qnil);
3740 if (STRING_MULTIBYTE (tem) && ! multibyte)
3742 multibyte = 1;
3743 goto retry;
3745 args[n] = tem;
3746 /* If we restart the loop, we should not come here again
3747 because args[n] is now a string and calling
3748 Fprin1_to_string on it produces superflous double
3749 quotes. So, change "%S" to "%s" now. */
3750 *format = 's';
3751 goto string;
3753 else if (SYMBOLP (args[n]))
3755 args[n] = SYMBOL_NAME (args[n]);
3756 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3758 multibyte = 1;
3759 goto retry;
3761 goto string;
3763 else if (STRINGP (args[n]))
3765 string:
3766 if (*format != 's' && *format != 'S')
3767 error ("Format specifier doesn't match argument type");
3768 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3769 to be as large as is calculated here. Easy check for
3770 the case PRECISION = 0. */
3771 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3772 /* The precision also constrains how much of the argument
3773 string will finally appear (Bug#5710). */
3774 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3775 if (precision[n] != -1)
3776 actual_width = min (actual_width, precision[n]);
3778 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3779 else if (INTEGERP (args[n]) && *format != 's')
3781 /* The following loop assumes the Lisp type indicates
3782 the proper way to pass the argument.
3783 So make sure we have a flonum if the argument should
3784 be a double. */
3785 if (*format == 'e' || *format == 'f' || *format == 'g')
3786 args[n] = Ffloat (args[n]);
3787 else
3788 if (*format != 'd' && *format != 'o' && *format != 'x'
3789 && *format != 'i' && *format != 'X' && *format != 'c')
3790 error ("Invalid format operation %%%c", *format);
3792 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3793 if (*format == 'c')
3795 if (! ASCII_CHAR_P (XINT (args[n]))
3796 /* Note: No one can remember why we have to treat
3797 the character 0 as a multibyte character here.
3798 But, until it causes a real problem, let's
3799 don't change it. */
3800 || XINT (args[n]) == 0)
3802 if (! multibyte)
3804 multibyte = 1;
3805 goto retry;
3807 args[n] = Fchar_to_string (args[n]);
3808 thissize = SBYTES (args[n]);
3812 else if (FLOATP (args[n]) && *format != 's')
3814 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3816 if (*format != 'd' && *format != 'o' && *format != 'x'
3817 && *format != 'i' && *format != 'X' && *format != 'c')
3818 error ("Invalid format operation %%%c", *format);
3819 /* This fails unnecessarily if args[n] is bigger than
3820 most-positive-fixnum but smaller than MAXINT.
3821 These cases are important because we sometimes use floats
3822 to represent such integer values (typically such values
3823 come from UIDs or PIDs). */
3824 /* args[n] = Ftruncate (args[n], Qnil); */
3827 /* Note that we're using sprintf to print floats,
3828 so we have to take into account what that function
3829 prints. */
3830 /* Filter out flag value of -1. */
3831 thissize = (MAX_10_EXP + 100
3832 + (precision[n] > 0 ? precision[n] : 0));
3834 else
3836 /* Anything but a string, convert to a string using princ. */
3837 register Lisp_Object tem;
3838 tem = Fprin1_to_string (args[n], Qt);
3839 if (STRING_MULTIBYTE (tem) && ! multibyte)
3841 multibyte = 1;
3842 goto retry;
3844 args[n] = tem;
3845 goto string;
3848 thissize += max (0, field_width - actual_width);
3849 total += thissize + 4;
3852 abort_on_gc--;
3854 /* Now we can no longer jump to retry.
3855 TOTAL and LONGEST_FORMAT are known for certain. */
3857 this_format = (char *) alloca (longest_format + 1);
3859 /* Allocate the space for the result.
3860 Note that TOTAL is an overestimate. */
3861 SAFE_ALLOCA (buf, char *, total);
3863 p = buf;
3864 nchars = 0;
3865 n = 0;
3867 /* Scan the format and store result in BUF. */
3868 format = SSDATA (args[0]);
3869 format_start = format;
3870 end = format + SBYTES (args[0]);
3871 maybe_combine_byte = 0;
3872 while (format != end)
3874 if (*format == '%')
3876 int minlen;
3877 int negative = 0;
3878 char *this_format_start = format;
3880 discarded[format - format_start] = 1;
3881 format++;
3883 while (strchr ("-+0# ", *format))
3885 if (*format == '-')
3887 negative = 1;
3889 discarded[format - format_start] = 1;
3890 ++format;
3893 minlen = atoi (format);
3895 while ((*format >= '0' && *format <= '9') || *format == '.')
3897 discarded[format - format_start] = 1;
3898 format++;
3901 if (*format++ == '%')
3903 *p++ = '%';
3904 nchars++;
3905 continue;
3908 ++n;
3910 discarded[format - format_start - 1] = 1;
3911 info[n].start = nchars;
3913 if (STRINGP (args[n]))
3915 /* handle case (precision[n] >= 0) */
3917 int width, padding;
3918 EMACS_INT nbytes, start;
3919 EMACS_INT nchars_string;
3921 /* lisp_string_width ignores a precision of 0, but GNU
3922 libc functions print 0 characters when the precision
3923 is 0. Imitate libc behavior here. Changing
3924 lisp_string_width is the right thing, and will be
3925 done, but meanwhile we work with it. */
3927 if (precision[n] == 0)
3928 width = nchars_string = nbytes = 0;
3929 else if (precision[n] > 0)
3930 width = lisp_string_width (args[n], precision[n],
3931 &nchars_string, &nbytes);
3932 else
3933 { /* no precision spec given for this argument */
3934 width = lisp_string_width (args[n], -1, NULL, NULL);
3935 nbytes = SBYTES (args[n]);
3936 nchars_string = SCHARS (args[n]);
3939 /* If spec requires it, pad on right with spaces. */
3940 padding = minlen - width;
3941 if (! negative)
3942 while (padding-- > 0)
3944 *p++ = ' ';
3945 ++nchars;
3948 info[n].start = start = nchars;
3949 nchars += nchars_string;
3951 if (p > buf
3952 && multibyte
3953 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3954 && STRING_MULTIBYTE (args[n])
3955 && !CHAR_HEAD_P (SREF (args[n], 0)))
3956 maybe_combine_byte = 1;
3958 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3959 nbytes,
3960 STRING_MULTIBYTE (args[n]), multibyte);
3962 info[n].end = nchars;
3964 if (negative)
3965 while (padding-- > 0)
3967 *p++ = ' ';
3968 nchars++;
3971 /* If this argument has text properties, record where
3972 in the result string it appears. */
3973 if (STRING_INTERVALS (args[n]))
3974 info[n].intervals = arg_intervals = 1;
3976 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3978 int this_nchars;
3980 memcpy (this_format, this_format_start,
3981 format - this_format_start);
3982 this_format[format - this_format_start] = 0;
3984 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3985 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3986 else
3988 if (sizeof (EMACS_INT) > sizeof (int)
3989 && format[-1] != 'c')
3991 /* Insert 'l' before format spec. */
3992 this_format[format - this_format_start]
3993 = this_format[format - this_format_start - 1];
3994 this_format[format - this_format_start - 1] = 'l';
3995 this_format[format - this_format_start + 1] = 0;
3998 if (INTEGERP (args[n]))
4000 if (format[-1] == 'c')
4001 sprintf (p, this_format, (int) XINT (args[n]));
4002 else if (format[-1] == 'd')
4003 sprintf (p, this_format, XINT (args[n]));
4004 /* Don't sign-extend for octal or hex printing. */
4005 else
4006 sprintf (p, this_format, XUINT (args[n]));
4008 else if (format[-1] == 'c')
4009 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4010 else if (format[-1] == 'd')
4011 /* Maybe we should use "%1.0f" instead so it also works
4012 for values larger than MAXINT. */
4013 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4014 else
4015 /* Don't sign-extend for octal or hex printing. */
4016 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4019 if (p > buf
4020 && multibyte
4021 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4022 && !CHAR_HEAD_P (*((unsigned char *) p)))
4023 maybe_combine_byte = 1;
4024 this_nchars = strlen (p);
4025 if (multibyte)
4026 p += str_to_multibyte ((unsigned char *) p,
4027 buf + total - 1 - p, this_nchars);
4028 else
4029 p += this_nchars;
4030 nchars += this_nchars;
4031 info[n].end = nchars;
4035 else if (STRING_MULTIBYTE (args[0]))
4037 /* Copy a whole multibyte character. */
4038 if (p > buf
4039 && multibyte
4040 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4041 && !CHAR_HEAD_P (*format))
4042 maybe_combine_byte = 1;
4043 *p++ = *format++;
4044 while (! CHAR_HEAD_P (*format))
4046 discarded[format - format_start] = 2;
4047 *p++ = *format++;
4049 nchars++;
4051 else if (multibyte)
4053 /* Convert a single-byte character to multibyte. */
4054 int len = copy_text ((unsigned char *) format, (unsigned char *) p,
4055 1, 0, 1);
4057 p += len;
4058 format++;
4059 nchars++;
4061 else
4062 *p++ = *format++, nchars++;
4065 if (p > buf + total)
4066 abort ();
4068 if (maybe_combine_byte)
4069 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4070 val = make_specified_string (buf, nchars, p - buf, multibyte);
4072 /* If we allocated BUF with malloc, free it too. */
4073 SAFE_FREE ();
4075 /* If the format string has text properties, or any of the string
4076 arguments has text properties, set up text properties of the
4077 result string. */
4079 if (STRING_INTERVALS (args[0]) || arg_intervals)
4081 Lisp_Object len, new_len, props;
4082 struct gcpro gcpro1;
4084 /* Add text properties from the format string. */
4085 len = make_number (SCHARS (args[0]));
4086 props = text_property_list (args[0], make_number (0), len, Qnil);
4087 GCPRO1 (props);
4089 if (CONSP (props))
4091 EMACS_INT bytepos = 0, position = 0, translated = 0;
4092 int argn = 1;
4093 Lisp_Object list;
4095 /* Adjust the bounds of each text property
4096 to the proper start and end in the output string. */
4098 /* Put the positions in PROPS in increasing order, so that
4099 we can do (effectively) one scan through the position
4100 space of the format string. */
4101 props = Fnreverse (props);
4103 /* BYTEPOS is the byte position in the format string,
4104 POSITION is the untranslated char position in it,
4105 TRANSLATED is the translated char position in BUF,
4106 and ARGN is the number of the next arg we will come to. */
4107 for (list = props; CONSP (list); list = XCDR (list))
4109 Lisp_Object item;
4110 EMACS_INT pos;
4112 item = XCAR (list);
4114 /* First adjust the property start position. */
4115 pos = XINT (XCAR (item));
4117 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4118 up to this position. */
4119 for (; position < pos; bytepos++)
4121 if (! discarded[bytepos])
4122 position++, translated++;
4123 else if (discarded[bytepos] == 1)
4125 position++;
4126 if (translated == info[argn].start)
4128 translated += info[argn].end - info[argn].start;
4129 argn++;
4134 XSETCAR (item, make_number (translated));
4136 /* Likewise adjust the property end position. */
4137 pos = XINT (XCAR (XCDR (item)));
4139 for (; position < pos; bytepos++)
4141 if (! discarded[bytepos])
4142 position++, translated++;
4143 else if (discarded[bytepos] == 1)
4145 position++;
4146 if (translated == info[argn].start)
4148 translated += info[argn].end - info[argn].start;
4149 argn++;
4154 XSETCAR (XCDR (item), make_number (translated));
4157 add_text_properties_from_list (val, props, make_number (0));
4160 /* Add text properties from arguments. */
4161 if (arg_intervals)
4162 for (n = 1; n < nargs; ++n)
4163 if (info[n].intervals)
4165 len = make_number (SCHARS (args[n]));
4166 new_len = make_number (info[n].end - info[n].start);
4167 props = text_property_list (args[n], make_number (0), len, Qnil);
4168 props = extend_property_ranges (props, new_len);
4169 /* If successive arguments have properties, be sure that
4170 the value of `composition' property be the copy. */
4171 if (n > 1 && info[n - 1].end)
4172 make_composition_value_copy (props);
4173 add_text_properties_from_list (val, props,
4174 make_number (info[n].start));
4177 UNGCPRO;
4180 return val;
4183 Lisp_Object
4184 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4186 Lisp_Object args[3];
4187 args[0] = build_string (string1);
4188 args[1] = arg0;
4189 args[2] = arg1;
4190 return Fformat (3, args);
4193 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4194 doc: /* Return t if two characters match, optionally ignoring case.
4195 Both arguments must be characters (i.e. integers).
4196 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4197 (register Lisp_Object c1, Lisp_Object c2)
4199 int i1, i2;
4200 /* Check they're chars, not just integers, otherwise we could get array
4201 bounds violations in downcase. */
4202 CHECK_CHARACTER (c1);
4203 CHECK_CHARACTER (c2);
4205 if (XINT (c1) == XINT (c2))
4206 return Qt;
4207 if (NILP (BVAR (current_buffer, case_fold_search)))
4208 return Qnil;
4210 i1 = XFASTINT (c1);
4211 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4212 && ! ASCII_CHAR_P (i1))
4214 MAKE_CHAR_MULTIBYTE (i1);
4216 i2 = XFASTINT (c2);
4217 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4218 && ! ASCII_CHAR_P (i2))
4220 MAKE_CHAR_MULTIBYTE (i2);
4222 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4225 /* Transpose the markers in two regions of the current buffer, and
4226 adjust the ones between them if necessary (i.e.: if the regions
4227 differ in size).
4229 START1, END1 are the character positions of the first region.
4230 START1_BYTE, END1_BYTE are the byte positions.
4231 START2, END2 are the character positions of the second region.
4232 START2_BYTE, END2_BYTE are the byte positions.
4234 Traverses the entire marker list of the buffer to do so, adding an
4235 appropriate amount to some, subtracting from some, and leaving the
4236 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4238 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4240 static void
4241 transpose_markers (EMACS_INT start1, EMACS_INT end1,
4242 EMACS_INT start2, EMACS_INT end2,
4243 EMACS_INT start1_byte, EMACS_INT end1_byte,
4244 EMACS_INT start2_byte, EMACS_INT end2_byte)
4246 register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4247 register struct Lisp_Marker *marker;
4249 /* Update point as if it were a marker. */
4250 if (PT < start1)
4252 else if (PT < end1)
4253 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4254 PT_BYTE + (end2_byte - end1_byte));
4255 else if (PT < start2)
4256 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4257 (PT_BYTE + (end2_byte - start2_byte)
4258 - (end1_byte - start1_byte)));
4259 else if (PT < end2)
4260 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4261 PT_BYTE - (start2_byte - start1_byte));
4263 /* We used to adjust the endpoints here to account for the gap, but that
4264 isn't good enough. Even if we assume the caller has tried to move the
4265 gap out of our way, it might still be at start1 exactly, for example;
4266 and that places it `inside' the interval, for our purposes. The amount
4267 of adjustment is nontrivial if there's a `denormalized' marker whose
4268 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4269 the dirty work to Fmarker_position, below. */
4271 /* The difference between the region's lengths */
4272 diff = (end2 - start2) - (end1 - start1);
4273 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4275 /* For shifting each marker in a region by the length of the other
4276 region plus the distance between the regions. */
4277 amt1 = (end2 - start2) + (start2 - end1);
4278 amt2 = (end1 - start1) + (start2 - end1);
4279 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4280 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4282 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4284 mpos = marker->bytepos;
4285 if (mpos >= start1_byte && mpos < end2_byte)
4287 if (mpos < end1_byte)
4288 mpos += amt1_byte;
4289 else if (mpos < start2_byte)
4290 mpos += diff_byte;
4291 else
4292 mpos -= amt2_byte;
4293 marker->bytepos = mpos;
4295 mpos = marker->charpos;
4296 if (mpos >= start1 && mpos < end2)
4298 if (mpos < end1)
4299 mpos += amt1;
4300 else if (mpos < start2)
4301 mpos += diff;
4302 else
4303 mpos -= amt2;
4305 marker->charpos = mpos;
4309 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4310 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4311 The regions should not be overlapping, because the size of the buffer is
4312 never changed in a transposition.
4314 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4315 any markers that happen to be located in the regions.
4317 Transposing beyond buffer boundaries is an error. */)
4318 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4320 register EMACS_INT start1, end1, start2, end2;
4321 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4322 EMACS_INT gap, len1, len_mid, len2;
4323 unsigned char *start1_addr, *start2_addr, *temp;
4325 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4326 Lisp_Object buf;
4328 XSETBUFFER (buf, current_buffer);
4329 cur_intv = BUF_INTERVALS (current_buffer);
4331 validate_region (&startr1, &endr1);
4332 validate_region (&startr2, &endr2);
4334 start1 = XFASTINT (startr1);
4335 end1 = XFASTINT (endr1);
4336 start2 = XFASTINT (startr2);
4337 end2 = XFASTINT (endr2);
4338 gap = GPT;
4340 /* Swap the regions if they're reversed. */
4341 if (start2 < end1)
4343 register EMACS_INT glumph = start1;
4344 start1 = start2;
4345 start2 = glumph;
4346 glumph = end1;
4347 end1 = end2;
4348 end2 = glumph;
4351 len1 = end1 - start1;
4352 len2 = end2 - start2;
4354 if (start2 < end1)
4355 error ("Transposed regions overlap");
4356 else if (start1 == end1 || start2 == end2)
4357 error ("Transposed region has length 0");
4359 /* The possibilities are:
4360 1. Adjacent (contiguous) regions, or separate but equal regions
4361 (no, really equal, in this case!), or
4362 2. Separate regions of unequal size.
4364 The worst case is usually No. 2. It means that (aside from
4365 potential need for getting the gap out of the way), there also
4366 needs to be a shifting of the text between the two regions. So
4367 if they are spread far apart, we are that much slower... sigh. */
4369 /* It must be pointed out that the really studly thing to do would
4370 be not to move the gap at all, but to leave it in place and work
4371 around it if necessary. This would be extremely efficient,
4372 especially considering that people are likely to do
4373 transpositions near where they are working interactively, which
4374 is exactly where the gap would be found. However, such code
4375 would be much harder to write and to read. So, if you are
4376 reading this comment and are feeling squirrely, by all means have
4377 a go! I just didn't feel like doing it, so I will simply move
4378 the gap the minimum distance to get it out of the way, and then
4379 deal with an unbroken array. */
4381 /* Make sure the gap won't interfere, by moving it out of the text
4382 we will operate on. */
4383 if (start1 < gap && gap < end2)
4385 if (gap - start1 < end2 - gap)
4386 move_gap (start1);
4387 else
4388 move_gap (end2);
4391 start1_byte = CHAR_TO_BYTE (start1);
4392 start2_byte = CHAR_TO_BYTE (start2);
4393 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4394 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4396 #ifdef BYTE_COMBINING_DEBUG
4397 if (end1 == start2)
4399 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4400 len2_byte, start1, start1_byte)
4401 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4402 len1_byte, end2, start2_byte + len2_byte)
4403 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4404 len1_byte, end2, start2_byte + len2_byte))
4405 abort ();
4407 else
4409 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4410 len2_byte, start1, start1_byte)
4411 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4412 len1_byte, start2, start2_byte)
4413 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4414 len2_byte, end1, start1_byte + len1_byte)
4415 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4416 len1_byte, end2, start2_byte + len2_byte))
4417 abort ();
4419 #endif
4421 /* Hmmm... how about checking to see if the gap is large
4422 enough to use as the temporary storage? That would avoid an
4423 allocation... interesting. Later, don't fool with it now. */
4425 /* Working without memmove, for portability (sigh), so must be
4426 careful of overlapping subsections of the array... */
4428 if (end1 == start2) /* adjacent regions */
4430 modify_region (current_buffer, start1, end2, 0);
4431 record_change (start1, len1 + len2);
4433 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4434 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4435 /* Don't use Fset_text_properties: that can cause GC, which can
4436 clobber objects stored in the tmp_intervals. */
4437 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4438 if (!NULL_INTERVAL_P (tmp_interval3))
4439 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4441 /* First region smaller than second. */
4442 if (len1_byte < len2_byte)
4444 USE_SAFE_ALLOCA;
4446 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4448 /* Don't precompute these addresses. We have to compute them
4449 at the last minute, because the relocating allocator might
4450 have moved the buffer around during the xmalloc. */
4451 start1_addr = BYTE_POS_ADDR (start1_byte);
4452 start2_addr = BYTE_POS_ADDR (start2_byte);
4454 memcpy (temp, start2_addr, len2_byte);
4455 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4456 memcpy (start1_addr, temp, len2_byte);
4457 SAFE_FREE ();
4459 else
4460 /* First region not smaller than second. */
4462 USE_SAFE_ALLOCA;
4464 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4465 start1_addr = BYTE_POS_ADDR (start1_byte);
4466 start2_addr = BYTE_POS_ADDR (start2_byte);
4467 memcpy (temp, start1_addr, len1_byte);
4468 memcpy (start1_addr, start2_addr, len2_byte);
4469 memcpy (start1_addr + len2_byte, temp, len1_byte);
4470 SAFE_FREE ();
4472 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4473 len1, current_buffer, 0);
4474 graft_intervals_into_buffer (tmp_interval2, start1,
4475 len2, current_buffer, 0);
4476 update_compositions (start1, start1 + len2, CHECK_BORDER);
4477 update_compositions (start1 + len2, end2, CHECK_TAIL);
4479 /* Non-adjacent regions, because end1 != start2, bleagh... */
4480 else
4482 len_mid = start2_byte - (start1_byte + len1_byte);
4484 if (len1_byte == len2_byte)
4485 /* Regions are same size, though, how nice. */
4487 USE_SAFE_ALLOCA;
4489 modify_region (current_buffer, start1, end1, 0);
4490 modify_region (current_buffer, start2, end2, 0);
4491 record_change (start1, len1);
4492 record_change (start2, len2);
4493 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4494 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4496 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4497 if (!NULL_INTERVAL_P (tmp_interval3))
4498 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4500 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4501 if (!NULL_INTERVAL_P (tmp_interval3))
4502 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4504 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4505 start1_addr = BYTE_POS_ADDR (start1_byte);
4506 start2_addr = BYTE_POS_ADDR (start2_byte);
4507 memcpy (temp, start1_addr, len1_byte);
4508 memcpy (start1_addr, start2_addr, len2_byte);
4509 memcpy (start2_addr, temp, len1_byte);
4510 SAFE_FREE ();
4512 graft_intervals_into_buffer (tmp_interval1, start2,
4513 len1, current_buffer, 0);
4514 graft_intervals_into_buffer (tmp_interval2, start1,
4515 len2, current_buffer, 0);
4518 else if (len1_byte < len2_byte) /* Second region larger than first */
4519 /* Non-adjacent & unequal size, area between must also be shifted. */
4521 USE_SAFE_ALLOCA;
4523 modify_region (current_buffer, start1, end2, 0);
4524 record_change (start1, (end2 - start1));
4525 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4526 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4527 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4529 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4530 if (!NULL_INTERVAL_P (tmp_interval3))
4531 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4533 /* holds region 2 */
4534 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4535 start1_addr = BYTE_POS_ADDR (start1_byte);
4536 start2_addr = BYTE_POS_ADDR (start2_byte);
4537 memcpy (temp, start2_addr, len2_byte);
4538 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4539 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4540 memcpy (start1_addr, temp, len2_byte);
4541 SAFE_FREE ();
4543 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4544 len1, current_buffer, 0);
4545 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4546 len_mid, current_buffer, 0);
4547 graft_intervals_into_buffer (tmp_interval2, start1,
4548 len2, current_buffer, 0);
4550 else
4551 /* Second region smaller than first. */
4553 USE_SAFE_ALLOCA;
4555 record_change (start1, (end2 - start1));
4556 modify_region (current_buffer, start1, end2, 0);
4558 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4559 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4560 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4562 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4563 if (!NULL_INTERVAL_P (tmp_interval3))
4564 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4566 /* holds region 1 */
4567 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4568 start1_addr = BYTE_POS_ADDR (start1_byte);
4569 start2_addr = BYTE_POS_ADDR (start2_byte);
4570 memcpy (temp, start1_addr, len1_byte);
4571 memcpy (start1_addr, start2_addr, len2_byte);
4572 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4573 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4574 SAFE_FREE ();
4576 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4577 len1, current_buffer, 0);
4578 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4579 len_mid, current_buffer, 0);
4580 graft_intervals_into_buffer (tmp_interval2, start1,
4581 len2, current_buffer, 0);
4584 update_compositions (start1, start1 + len2, CHECK_BORDER);
4585 update_compositions (end2 - len1, end2, CHECK_BORDER);
4588 /* When doing multiple transpositions, it might be nice
4589 to optimize this. Perhaps the markers in any one buffer
4590 should be organized in some sorted data tree. */
4591 if (NILP (leave_markers))
4593 transpose_markers (start1, end1, start2, end2,
4594 start1_byte, start1_byte + len1_byte,
4595 start2_byte, start2_byte + len2_byte);
4596 fix_start_end_in_overlays (start1, end2);
4599 signal_after_change (start1, end2 - start1, end2 - start1);
4600 return Qnil;
4604 void
4605 syms_of_editfns (void)
4607 environbuf = 0;
4608 initial_tz = 0;
4610 Qbuffer_access_fontify_functions
4611 = intern_c_string ("buffer-access-fontify-functions");
4612 staticpro (&Qbuffer_access_fontify_functions);
4614 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4615 doc: /* Non-nil means text motion commands don't notice fields. */);
4616 Vinhibit_field_text_motion = Qnil;
4618 DEFVAR_LISP ("buffer-access-fontify-functions",
4619 Vbuffer_access_fontify_functions,
4620 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4621 Each function is called with two arguments which specify the range
4622 of the buffer being accessed. */);
4623 Vbuffer_access_fontify_functions = Qnil;
4626 Lisp_Object obuf;
4627 obuf = Fcurrent_buffer ();
4628 /* Do this here, because init_buffer_once is too early--it won't work. */
4629 Fset_buffer (Vprin1_to_string_buffer);
4630 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4631 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4632 Qnil);
4633 Fset_buffer (obuf);
4636 DEFVAR_LISP ("buffer-access-fontified-property",
4637 Vbuffer_access_fontified_property,
4638 doc: /* Property which (if non-nil) indicates text has been fontified.
4639 `buffer-substring' need not call the `buffer-access-fontify-functions'
4640 functions if all the text being accessed has this property. */);
4641 Vbuffer_access_fontified_property = Qnil;
4643 DEFVAR_LISP ("system-name", Vsystem_name,
4644 doc: /* The host name of the machine Emacs is running on. */);
4646 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4647 doc: /* The full name of the user logged in. */);
4649 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4650 doc: /* The user's name, taken from environment variables if possible. */);
4652 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4653 doc: /* The user's name, based upon the real uid only. */);
4655 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4656 doc: /* The release of the operating system Emacs is running on. */);
4658 defsubr (&Spropertize);
4659 defsubr (&Schar_equal);
4660 defsubr (&Sgoto_char);
4661 defsubr (&Sstring_to_char);
4662 defsubr (&Schar_to_string);
4663 defsubr (&Sbyte_to_string);
4664 defsubr (&Sbuffer_substring);
4665 defsubr (&Sbuffer_substring_no_properties);
4666 defsubr (&Sbuffer_string);
4668 defsubr (&Spoint_marker);
4669 defsubr (&Smark_marker);
4670 defsubr (&Spoint);
4671 defsubr (&Sregion_beginning);
4672 defsubr (&Sregion_end);
4674 staticpro (&Qfield);
4675 Qfield = intern_c_string ("field");
4676 staticpro (&Qboundary);
4677 Qboundary = intern_c_string ("boundary");
4678 defsubr (&Sfield_beginning);
4679 defsubr (&Sfield_end);
4680 defsubr (&Sfield_string);
4681 defsubr (&Sfield_string_no_properties);
4682 defsubr (&Sdelete_field);
4683 defsubr (&Sconstrain_to_field);
4685 defsubr (&Sline_beginning_position);
4686 defsubr (&Sline_end_position);
4688 /* defsubr (&Smark); */
4689 /* defsubr (&Sset_mark); */
4690 defsubr (&Ssave_excursion);
4691 defsubr (&Ssave_current_buffer);
4693 defsubr (&Sbufsize);
4694 defsubr (&Spoint_max);
4695 defsubr (&Spoint_min);
4696 defsubr (&Spoint_min_marker);
4697 defsubr (&Spoint_max_marker);
4698 defsubr (&Sgap_position);
4699 defsubr (&Sgap_size);
4700 defsubr (&Sposition_bytes);
4701 defsubr (&Sbyte_to_position);
4703 defsubr (&Sbobp);
4704 defsubr (&Seobp);
4705 defsubr (&Sbolp);
4706 defsubr (&Seolp);
4707 defsubr (&Sfollowing_char);
4708 defsubr (&Sprevious_char);
4709 defsubr (&Schar_after);
4710 defsubr (&Schar_before);
4711 defsubr (&Sinsert);
4712 defsubr (&Sinsert_before_markers);
4713 defsubr (&Sinsert_and_inherit);
4714 defsubr (&Sinsert_and_inherit_before_markers);
4715 defsubr (&Sinsert_char);
4716 defsubr (&Sinsert_byte);
4718 defsubr (&Suser_login_name);
4719 defsubr (&Suser_real_login_name);
4720 defsubr (&Suser_uid);
4721 defsubr (&Suser_real_uid);
4722 defsubr (&Suser_full_name);
4723 defsubr (&Semacs_pid);
4724 defsubr (&Scurrent_time);
4725 defsubr (&Sget_internal_run_time);
4726 defsubr (&Sformat_time_string);
4727 defsubr (&Sfloat_time);
4728 defsubr (&Sdecode_time);
4729 defsubr (&Sencode_time);
4730 defsubr (&Scurrent_time_string);
4731 defsubr (&Scurrent_time_zone);
4732 defsubr (&Sset_time_zone_rule);
4733 defsubr (&Ssystem_name);
4734 defsubr (&Smessage);
4735 defsubr (&Smessage_box);
4736 defsubr (&Smessage_or_box);
4737 defsubr (&Scurrent_message);
4738 defsubr (&Sformat);
4740 defsubr (&Sinsert_buffer_substring);
4741 defsubr (&Scompare_buffer_substrings);
4742 defsubr (&Ssubst_char_in_region);
4743 defsubr (&Stranslate_region_internal);
4744 defsubr (&Sdelete_region);
4745 defsubr (&Sdelete_and_extract_region);
4746 defsubr (&Swiden);
4747 defsubr (&Snarrow_to_region);
4748 defsubr (&Ssave_restriction);
4749 defsubr (&Stranspose_regions);