Fix crash with invisible text and overlays (Bug#7016).
[emacs.git] / src / editfns.c
blob910fd13aed40aec7e0d62e231a73f513438932e3
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985, 1986, 1987, 1989, 1993, 1994, 1995, 1996, 1997,
4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
5 2009, 2010 Free Software Foundation, Inc.
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
23 #include <config.h>
24 #include <sys/types.h>
25 #include <stdio.h>
26 #include <setjmp.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 #ifdef HAVE_SYS_UTSNAME_H
37 #include <sys/utsname.h>
38 #endif
40 #include "lisp.h"
42 /* systime.h includes <sys/time.h> which, on some systems, is required
43 for <sys/resource.h>; thus systime.h must be included before
44 <sys/resource.h> */
45 #include "systime.h"
47 #if defined HAVE_SYS_RESOURCE_H
48 #include <sys/resource.h>
49 #endif
51 #include <ctype.h>
53 #include "intervals.h"
54 #include "buffer.h"
55 #include "character.h"
56 #include "coding.h"
57 #include "frame.h"
58 #include "window.h"
59 #include "blockinput.h"
61 #ifdef STDC_HEADERS
62 #include <float.h>
63 #define MAX_10_EXP DBL_MAX_10_EXP
64 #else
65 #define MAX_10_EXP 310
66 #endif
68 #ifndef NULL
69 #define NULL 0
70 #endif
72 #ifndef USER_FULL_NAME
73 #define USER_FULL_NAME pw->pw_gecos
74 #endif
76 #ifndef USE_CRT_DLL
77 extern char **environ;
78 #endif
80 #define TM_YEAR_BASE 1900
82 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
83 asctime to have well-defined behavior. */
84 #ifndef TM_YEAR_IN_ASCTIME_RANGE
85 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
86 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
87 #endif
89 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
90 const struct tm *, int));
92 #ifdef WINDOWSNT
93 extern Lisp_Object w32_get_internal_run_time ();
94 #endif
96 static int tm_diff P_ ((struct tm *, struct tm *));
97 static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
98 static void update_buffer_properties P_ ((int, int));
99 static Lisp_Object region_limit P_ ((int));
100 int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
101 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
102 size_t, const struct tm *, int));
103 static void general_insert_function (void (*) (const unsigned char *, EMACS_INT),
104 void (*) (Lisp_Object, EMACS_INT,
105 EMACS_INT, EMACS_INT,
106 EMACS_INT, int),
107 int, int, Lisp_Object *);
108 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
109 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
110 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
112 #ifdef HAVE_INDEX
113 extern char *index P_ ((const char *, int));
114 #endif
116 Lisp_Object Vbuffer_access_fontify_functions;
117 Lisp_Object Qbuffer_access_fontify_functions;
118 Lisp_Object Vbuffer_access_fontified_property;
120 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
122 /* Non-nil means don't stop at field boundary in text motion commands. */
124 Lisp_Object Vinhibit_field_text_motion;
126 /* Some static data, and a function to initialize it for each run */
128 Lisp_Object Vsystem_name;
129 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
130 Lisp_Object Vuser_full_name; /* full name of current user */
131 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
132 Lisp_Object Voperating_system_release; /* Operating System Release */
134 /* Symbol for the text property used to mark fields. */
136 Lisp_Object Qfield;
138 /* A special value for Qfield properties. */
140 Lisp_Object Qboundary;
143 void
144 init_editfns ()
146 char *user_name;
147 register unsigned char *p;
148 struct passwd *pw; /* password entry for the current user */
149 Lisp_Object tem;
151 /* Set up system_name even when dumping. */
152 init_system_name ();
154 #ifndef CANNOT_DUMP
155 /* Don't bother with this on initial start when just dumping out */
156 if (!initialized)
157 return;
158 #endif /* not CANNOT_DUMP */
160 pw = (struct passwd *) getpwuid (getuid ());
161 #ifdef MSDOS
162 /* We let the real user name default to "root" because that's quite
163 accurate on MSDOG and because it lets Emacs find the init file.
164 (The DVX libraries override the Djgpp libraries here.) */
165 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
166 #else
167 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
168 #endif
170 /* Get the effective user name, by consulting environment variables,
171 or the effective uid if those are unset. */
172 user_name = (char *) getenv ("LOGNAME");
173 if (!user_name)
174 #ifdef WINDOWSNT
175 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
176 #else /* WINDOWSNT */
177 user_name = (char *) getenv ("USER");
178 #endif /* WINDOWSNT */
179 if (!user_name)
181 pw = (struct passwd *) getpwuid (geteuid ());
182 user_name = (char *) (pw ? pw->pw_name : "unknown");
184 Vuser_login_name = build_string (user_name);
186 /* If the user name claimed in the environment vars differs from
187 the real uid, use the claimed name to find the full name. */
188 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
189 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
190 : Vuser_login_name);
192 p = (unsigned char *) getenv ("NAME");
193 if (p)
194 Vuser_full_name = build_string (p);
195 else if (NILP (Vuser_full_name))
196 Vuser_full_name = build_string ("unknown");
198 #ifdef HAVE_SYS_UTSNAME_H
200 struct utsname uts;
201 uname (&uts);
202 Voperating_system_release = build_string (uts.release);
204 #else
205 Voperating_system_release = Qnil;
206 #endif
209 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
210 doc: /* Convert arg CHAR to a string containing that character.
211 usage: (char-to-string CHAR) */)
212 (character)
213 Lisp_Object character;
215 int len;
216 unsigned char str[MAX_MULTIBYTE_LENGTH];
218 CHECK_CHARACTER (character);
220 len = CHAR_STRING (XFASTINT (character), str);
221 return make_string_from_bytes (str, 1, len);
224 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
225 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
226 (byte)
227 Lisp_Object byte;
229 unsigned char b;
230 CHECK_NUMBER (byte);
231 if (XINT (byte) < 0 || XINT (byte) > 255)
232 error ("Invalid byte");
233 b = XINT (byte);
234 return make_string_from_bytes (&b, 1, 1);
237 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
238 doc: /* Convert arg STRING to a character, the first character of that string.
239 A multibyte character is handled correctly. */)
240 (string)
241 register Lisp_Object string;
243 register Lisp_Object val;
244 CHECK_STRING (string);
245 if (SCHARS (string))
247 if (STRING_MULTIBYTE (string))
248 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
249 else
250 XSETFASTINT (val, SREF (string, 0));
252 else
253 XSETFASTINT (val, 0);
254 return val;
257 static Lisp_Object
258 buildmark (charpos, bytepos)
259 int charpos, bytepos;
261 register Lisp_Object mark;
262 mark = Fmake_marker ();
263 set_marker_both (mark, Qnil, charpos, bytepos);
264 return mark;
267 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
268 doc: /* Return value of point, as an integer.
269 Beginning of buffer is position (point-min). */)
272 Lisp_Object temp;
273 XSETFASTINT (temp, PT);
274 return temp;
277 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
278 doc: /* Return value of point, as a marker object. */)
281 return buildmark (PT, PT_BYTE);
285 clip_to_bounds (lower, num, upper)
286 int lower, num, upper;
288 if (num < lower)
289 return lower;
290 else if (num > upper)
291 return upper;
292 else
293 return num;
296 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
297 doc: /* Set point to POSITION, a number or marker.
298 Beginning of buffer is position (point-min), end is (point-max).
300 The return value is POSITION. */)
301 (position)
302 register Lisp_Object position;
304 int pos;
306 if (MARKERP (position)
307 && current_buffer == XMARKER (position)->buffer)
309 pos = marker_position (position);
310 if (pos < BEGV)
311 SET_PT_BOTH (BEGV, BEGV_BYTE);
312 else if (pos > ZV)
313 SET_PT_BOTH (ZV, ZV_BYTE);
314 else
315 SET_PT_BOTH (pos, marker_byte_position (position));
317 return position;
320 CHECK_NUMBER_COERCE_MARKER (position);
322 pos = clip_to_bounds (BEGV, XINT (position), ZV);
323 SET_PT (pos);
324 return position;
328 /* Return the start or end position of the region.
329 BEGINNINGP non-zero means return the start.
330 If there is no region active, signal an error. */
332 static Lisp_Object
333 region_limit (beginningp)
334 int beginningp;
336 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
337 Lisp_Object m;
339 if (!NILP (Vtransient_mark_mode)
340 && NILP (Vmark_even_if_inactive)
341 && NILP (current_buffer->mark_active))
342 xsignal0 (Qmark_inactive);
344 m = Fmarker_position (current_buffer->mark);
345 if (NILP (m))
346 error ("The mark is not set now, so there is no region");
348 if ((PT < XFASTINT (m)) == (beginningp != 0))
349 m = make_number (PT);
350 return m;
353 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
354 doc: /* Return position of beginning of region, as an integer. */)
357 return region_limit (1);
360 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
361 doc: /* Return position of end of region, as an integer. */)
364 return region_limit (0);
367 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
368 doc: /* Return this buffer's mark, as a marker object.
369 Watch out! Moving this marker changes the mark position.
370 If you set the marker not to point anywhere, the buffer will have no mark. */)
373 return current_buffer->mark;
377 /* Find all the overlays in the current buffer that touch position POS.
378 Return the number found, and store them in a vector in VEC
379 of length LEN. */
381 static int
382 overlays_around (pos, vec, len)
383 int pos;
384 Lisp_Object *vec;
385 int len;
387 Lisp_Object overlay, start, end;
388 struct Lisp_Overlay *tail;
389 int startpos, endpos;
390 int idx = 0;
392 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
394 XSETMISC (overlay, tail);
396 end = OVERLAY_END (overlay);
397 endpos = OVERLAY_POSITION (end);
398 if (endpos < pos)
399 break;
400 start = OVERLAY_START (overlay);
401 startpos = OVERLAY_POSITION (start);
402 if (startpos <= pos)
404 if (idx < len)
405 vec[idx] = overlay;
406 /* Keep counting overlays even if we can't return them all. */
407 idx++;
411 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
413 XSETMISC (overlay, tail);
415 start = OVERLAY_START (overlay);
416 startpos = OVERLAY_POSITION (start);
417 if (pos < startpos)
418 break;
419 end = OVERLAY_END (overlay);
420 endpos = OVERLAY_POSITION (end);
421 if (pos <= endpos)
423 if (idx < len)
424 vec[idx] = overlay;
425 idx++;
429 return idx;
432 /* Return the value of property PROP, in OBJECT at POSITION.
433 It's the value of PROP that a char inserted at POSITION would get.
434 OBJECT is optional and defaults to the current buffer.
435 If OBJECT is a buffer, then overlay properties are considered as well as
436 text properties.
437 If OBJECT is a window, then that window's buffer is used, but
438 window-specific overlays are considered only if they are associated
439 with OBJECT. */
440 Lisp_Object
441 get_pos_property (position, prop, object)
442 Lisp_Object position, object;
443 register Lisp_Object prop;
445 CHECK_NUMBER_COERCE_MARKER (position);
447 if (NILP (object))
448 XSETBUFFER (object, current_buffer);
449 else if (WINDOWP (object))
450 object = XWINDOW (object)->buffer;
452 if (!BUFFERP (object))
453 /* pos-property only makes sense in buffers right now, since strings
454 have no overlays and no notion of insertion for which stickiness
455 could be obeyed. */
456 return Fget_text_property (position, prop, object);
457 else
459 int posn = XINT (position);
460 int noverlays;
461 Lisp_Object *overlay_vec, tem;
462 struct buffer *obuf = current_buffer;
464 set_buffer_temp (XBUFFER (object));
466 /* First try with room for 40 overlays. */
467 noverlays = 40;
468 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
469 noverlays = overlays_around (posn, overlay_vec, noverlays);
471 /* If there are more than 40,
472 make enough space for all, and try again. */
473 if (noverlays > 40)
475 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
476 noverlays = overlays_around (posn, overlay_vec, noverlays);
478 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
480 set_buffer_temp (obuf);
482 /* Now check the overlays in order of decreasing priority. */
483 while (--noverlays >= 0)
485 Lisp_Object ol = overlay_vec[noverlays];
486 tem = Foverlay_get (ol, prop);
487 if (!NILP (tem))
489 /* Check the overlay is indeed active at point. */
490 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
491 if ((OVERLAY_POSITION (start) == posn
492 && XMARKER (start)->insertion_type == 1)
493 || (OVERLAY_POSITION (finish) == posn
494 && XMARKER (finish)->insertion_type == 0))
495 ; /* The overlay will not cover a char inserted at point. */
496 else
498 return tem;
503 { /* Now check the text properties. */
504 int stickiness = text_property_stickiness (prop, position, object);
505 if (stickiness > 0)
506 return Fget_text_property (position, prop, object);
507 else if (stickiness < 0
508 && XINT (position) > BUF_BEGV (XBUFFER (object)))
509 return Fget_text_property (make_number (XINT (position) - 1),
510 prop, object);
511 else
512 return Qnil;
517 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
518 the value of point is used instead. If BEG or END is null,
519 means don't store the beginning or end of the field.
521 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
522 results; they do not effect boundary behavior.
524 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
525 position of a field, then the beginning of the previous field is
526 returned instead of the beginning of POS's field (since the end of a
527 field is actually also the beginning of the next input field, this
528 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
529 true case, if two fields are separated by a field with the special
530 value `boundary', and POS lies within it, then the two separated
531 fields are considered to be adjacent, and POS between them, when
532 finding the beginning and ending of the "merged" field.
534 Either BEG or END may be 0, in which case the corresponding value
535 is not stored. */
537 static void
538 find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
539 Lisp_Object pos;
540 Lisp_Object merge_at_boundary;
541 Lisp_Object beg_limit, end_limit;
542 int *beg, *end;
544 /* Fields right before and after the point. */
545 Lisp_Object before_field, after_field;
546 /* 1 if POS counts as the start of a field. */
547 int at_field_start = 0;
548 /* 1 if POS counts as the end of a field. */
549 int at_field_end = 0;
551 if (NILP (pos))
552 XSETFASTINT (pos, PT);
553 else
554 CHECK_NUMBER_COERCE_MARKER (pos);
556 after_field
557 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
558 before_field
559 = (XFASTINT (pos) > BEGV
560 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
561 Qfield, Qnil, NULL)
562 /* Using nil here would be a more obvious choice, but it would
563 fail when the buffer starts with a non-sticky field. */
564 : after_field);
566 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
567 and POS is at beginning of a field, which can also be interpreted
568 as the end of the previous field. Note that the case where if
569 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
570 more natural one; then we avoid treating the beginning of a field
571 specially. */
572 if (NILP (merge_at_boundary))
574 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
575 if (!EQ (field, after_field))
576 at_field_end = 1;
577 if (!EQ (field, before_field))
578 at_field_start = 1;
579 if (NILP (field) && at_field_start && at_field_end)
580 /* If an inserted char would have a nil field while the surrounding
581 text is non-nil, we're probably not looking at a
582 zero-length field, but instead at a non-nil field that's
583 not intended for editing (such as comint's prompts). */
584 at_field_end = at_field_start = 0;
587 /* Note about special `boundary' fields:
589 Consider the case where the point (`.') is between the fields `x' and `y':
591 xxxx.yyyy
593 In this situation, if merge_at_boundary is true, we consider the
594 `x' and `y' fields as forming one big merged field, and so the end
595 of the field is the end of `y'.
597 However, if `x' and `y' are separated by a special `boundary' field
598 (a field with a `field' char-property of 'boundary), then we ignore
599 this special field when merging adjacent fields. Here's the same
600 situation, but with a `boundary' field between the `x' and `y' fields:
602 xxx.BBBByyyy
604 Here, if point is at the end of `x', the beginning of `y', or
605 anywhere in-between (within the `boundary' field), we merge all
606 three fields and consider the beginning as being the beginning of
607 the `x' field, and the end as being the end of the `y' field. */
609 if (beg)
611 if (at_field_start)
612 /* POS is at the edge of a field, and we should consider it as
613 the beginning of the following field. */
614 *beg = XFASTINT (pos);
615 else
616 /* Find the previous field boundary. */
618 Lisp_Object p = pos;
619 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
620 /* Skip a `boundary' field. */
621 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
622 beg_limit);
624 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
625 beg_limit);
626 *beg = NILP (p) ? BEGV : XFASTINT (p);
630 if (end)
632 if (at_field_end)
633 /* POS is at the edge of a field, and we should consider it as
634 the end of the previous field. */
635 *end = XFASTINT (pos);
636 else
637 /* Find the next field boundary. */
639 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
640 /* Skip a `boundary' field. */
641 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
642 end_limit);
644 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
645 end_limit);
646 *end = NILP (pos) ? ZV : XFASTINT (pos);
652 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
653 doc: /* Delete the field surrounding POS.
654 A field is a region of text with the same `field' property.
655 If POS is nil, the value of point is used for POS. */)
656 (pos)
657 Lisp_Object pos;
659 int beg, end;
660 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
661 if (beg != end)
662 del_range (beg, end);
663 return Qnil;
666 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
667 doc: /* Return the contents of the field surrounding POS as a string.
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 (pos)
671 Lisp_Object pos;
673 int beg, end;
674 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
675 return make_buffer_string (beg, end, 1);
678 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
679 doc: /* Return the contents of the field around POS, without text properties.
680 A field is a region of text with the same `field' property.
681 If POS is nil, the value of point is used for POS. */)
682 (pos)
683 Lisp_Object pos;
685 int beg, end;
686 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
687 return make_buffer_string (beg, end, 0);
690 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
691 doc: /* Return the beginning of the field surrounding POS.
692 A field is a region of text with the same `field' property.
693 If POS is nil, the value of point is used for POS.
694 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
695 field, then the beginning of the *previous* field is returned.
696 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
697 is before LIMIT, then LIMIT will be returned instead. */)
698 (pos, escape_from_edge, limit)
699 Lisp_Object pos, escape_from_edge, limit;
701 int beg;
702 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
703 return make_number (beg);
706 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
707 doc: /* Return the end of the field surrounding POS.
708 A field is a region of text with the same `field' property.
709 If POS is nil, the value of point is used for POS.
710 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
711 then the end of the *following* field is returned.
712 If LIMIT is non-nil, it is a buffer position; if the end of the field
713 is after LIMIT, then LIMIT will be returned instead. */)
714 (pos, escape_from_edge, limit)
715 Lisp_Object pos, escape_from_edge, limit;
717 int end;
718 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
719 return make_number (end);
722 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
723 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
725 A field is a region of text with the same `field' property.
726 If NEW-POS is nil, then the current point is used instead, and set to the
727 constrained position if that is different.
729 If OLD-POS is at the boundary of two fields, then the allowable
730 positions for NEW-POS depends on the value of the optional argument
731 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
732 constrained to the field that has the same `field' char-property
733 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
734 is non-nil, NEW-POS is constrained to the union of the two adjacent
735 fields. Additionally, if two fields are separated by another field with
736 the special value `boundary', then any point within this special field is
737 also considered to be `on the boundary'.
739 If the optional argument ONLY-IN-LINE is non-nil and constraining
740 NEW-POS would move it to a different line, NEW-POS is returned
741 unconstrained. This useful for commands that move by line, like
742 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
743 only in the case where they can still move to the right line.
745 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
746 a non-nil property of that name, then any field boundaries are ignored.
748 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
749 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
750 Lisp_Object new_pos, old_pos;
751 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
753 /* If non-zero, then the original point, before re-positioning. */
754 int orig_point = 0;
755 int fwd;
756 Lisp_Object prev_old, prev_new;
758 if (NILP (new_pos))
759 /* Use the current point, and afterwards, set it. */
761 orig_point = PT;
762 XSETFASTINT (new_pos, PT);
765 CHECK_NUMBER_COERCE_MARKER (new_pos);
766 CHECK_NUMBER_COERCE_MARKER (old_pos);
768 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
770 prev_old = make_number (XFASTINT (old_pos) - 1);
771 prev_new = make_number (XFASTINT (new_pos) - 1);
773 if (NILP (Vinhibit_field_text_motion)
774 && !EQ (new_pos, old_pos)
775 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
776 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
777 /* To recognize field boundaries, we must also look at the
778 previous positions; we could use `get_pos_property'
779 instead, but in itself that would fail inside non-sticky
780 fields (like comint prompts). */
781 || (XFASTINT (new_pos) > BEGV
782 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
783 || (XFASTINT (old_pos) > BEGV
784 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
785 && (NILP (inhibit_capture_property)
786 /* Field boundaries are again a problem; but now we must
787 decide the case exactly, so we need to call
788 `get_pos_property' as well. */
789 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
790 && (XFASTINT (old_pos) <= BEGV
791 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
792 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
793 /* It is possible that NEW_POS is not within the same field as
794 OLD_POS; try to move NEW_POS so that it is. */
796 int shortage;
797 Lisp_Object field_bound;
799 if (fwd)
800 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
801 else
802 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
804 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
805 other side of NEW_POS, which would mean that NEW_POS is
806 already acceptable, and it's not necessary to constrain it
807 to FIELD_BOUND. */
808 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
809 /* NEW_POS should be constrained, but only if either
810 ONLY_IN_LINE is nil (in which case any constraint is OK),
811 or NEW_POS and FIELD_BOUND are on the same line (in which
812 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
813 && (NILP (only_in_line)
814 /* This is the ONLY_IN_LINE case, check that NEW_POS and
815 FIELD_BOUND are on the same line by seeing whether
816 there's an intervening newline or not. */
817 || (scan_buffer ('\n',
818 XFASTINT (new_pos), XFASTINT (field_bound),
819 fwd ? -1 : 1, &shortage, 1),
820 shortage != 0)))
821 /* Constrain NEW_POS to FIELD_BOUND. */
822 new_pos = field_bound;
824 if (orig_point && XFASTINT (new_pos) != orig_point)
825 /* The NEW_POS argument was originally nil, so automatically set PT. */
826 SET_PT (XFASTINT (new_pos));
829 return new_pos;
833 DEFUN ("line-beginning-position",
834 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
835 doc: /* Return the character position of the first character on the current line.
836 With argument N not nil or 1, move forward N - 1 lines first.
837 If scan reaches end of buffer, return that position.
839 This function constrains the returned position to the current field
840 unless that would be on a different line than the original,
841 unconstrained result. If N is nil or 1, and a front-sticky field
842 starts at point, the scan stops as soon as it starts. To ignore field
843 boundaries bind `inhibit-field-text-motion' to t.
845 This function does not move point. */)
847 Lisp_Object n;
849 int orig, orig_byte, end;
850 int count = SPECPDL_INDEX ();
851 specbind (Qinhibit_point_motion_hooks, Qt);
853 if (NILP (n))
854 XSETFASTINT (n, 1);
855 else
856 CHECK_NUMBER (n);
858 orig = PT;
859 orig_byte = PT_BYTE;
860 Fforward_line (make_number (XINT (n) - 1));
861 end = PT;
863 SET_PT_BOTH (orig, orig_byte);
865 unbind_to (count, Qnil);
867 /* Return END constrained to the current input field. */
868 return Fconstrain_to_field (make_number (end), make_number (orig),
869 XINT (n) != 1 ? Qt : Qnil,
870 Qt, Qnil);
873 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
874 doc: /* Return the character position of the last character on the current line.
875 With argument N not nil or 1, move forward N - 1 lines first.
876 If scan reaches end of buffer, return that position.
878 This function constrains the returned position to the current field
879 unless that would be on a different line than the original,
880 unconstrained result. If N is nil or 1, and a rear-sticky field ends
881 at point, the scan stops as soon as it starts. To ignore field
882 boundaries bind `inhibit-field-text-motion' to t.
884 This function does not move point. */)
886 Lisp_Object n;
888 int end_pos;
889 int orig = PT;
891 if (NILP (n))
892 XSETFASTINT (n, 1);
893 else
894 CHECK_NUMBER (n);
896 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
898 /* Return END_POS constrained to the current input field. */
899 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
900 Qnil, Qt, Qnil);
904 Lisp_Object
905 save_excursion_save ()
907 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
908 == current_buffer);
910 return Fcons (Fpoint_marker (),
911 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
912 Fcons (visible ? Qt : Qnil,
913 Fcons (current_buffer->mark_active,
914 selected_window))));
917 Lisp_Object
918 save_excursion_restore (info)
919 Lisp_Object info;
921 Lisp_Object tem, tem1, omark, nmark;
922 struct gcpro gcpro1, gcpro2, gcpro3;
923 int visible_p;
925 tem = Fmarker_buffer (XCAR (info));
926 /* If buffer being returned to is now deleted, avoid error */
927 /* Otherwise could get error here while unwinding to top level
928 and crash */
929 /* In that case, Fmarker_buffer returns nil now. */
930 if (NILP (tem))
931 return Qnil;
933 omark = nmark = Qnil;
934 GCPRO3 (info, omark, nmark);
936 Fset_buffer (tem);
938 /* Point marker. */
939 tem = XCAR (info);
940 Fgoto_char (tem);
941 unchain_marker (XMARKER (tem));
943 /* Mark marker. */
944 info = XCDR (info);
945 tem = XCAR (info);
946 omark = Fmarker_position (current_buffer->mark);
947 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
948 nmark = Fmarker_position (tem);
949 unchain_marker (XMARKER (tem));
951 /* visible */
952 info = XCDR (info);
953 visible_p = !NILP (XCAR (info));
955 #if 0 /* We used to make the current buffer visible in the selected window
956 if that was true previously. That avoids some anomalies.
957 But it creates others, and it wasn't documented, and it is simpler
958 and cleaner never to alter the window/buffer connections. */
959 tem1 = Fcar (tem);
960 if (!NILP (tem1)
961 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
962 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
963 #endif /* 0 */
965 /* Mark active */
966 info = XCDR (info);
967 tem = XCAR (info);
968 tem1 = current_buffer->mark_active;
969 current_buffer->mark_active = tem;
971 if (!NILP (Vrun_hooks))
973 /* If mark is active now, and either was not active
974 or was at a different place, run the activate hook. */
975 if (! NILP (current_buffer->mark_active))
977 if (! EQ (omark, nmark))
978 call1 (Vrun_hooks, intern ("activate-mark-hook"));
980 /* If mark has ceased to be active, run deactivate hook. */
981 else if (! NILP (tem1))
982 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
985 /* If buffer was visible in a window, and a different window was
986 selected, and the old selected window is still showing this
987 buffer, restore point in that window. */
988 tem = XCDR (info);
989 if (visible_p
990 && !EQ (tem, selected_window)
991 && (tem1 = XWINDOW (tem)->buffer,
992 (/* Window is live... */
993 BUFFERP (tem1)
994 /* ...and it shows the current buffer. */
995 && XBUFFER (tem1) == current_buffer)))
996 Fset_window_point (tem, make_number (PT));
998 UNGCPRO;
999 return Qnil;
1002 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
1003 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
1004 Executes BODY just like `progn'.
1005 The values of point, mark and the current buffer are restored
1006 even in case of abnormal exit (throw or error).
1007 The state of activation of the mark is also restored.
1009 This construct does not save `deactivate-mark', and therefore
1010 functions that change the buffer will still cause deactivation
1011 of the mark at the end of the command. To prevent that, bind
1012 `deactivate-mark' with `let'.
1014 If you only want to save the current buffer but not point nor mark,
1015 then just use `save-current-buffer', or even `with-current-buffer'.
1017 usage: (save-excursion &rest BODY) */)
1018 (args)
1019 Lisp_Object args;
1021 register Lisp_Object val;
1022 int count = SPECPDL_INDEX ();
1024 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1026 val = Fprogn (args);
1027 return unbind_to (count, val);
1030 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1031 doc: /* Save the current buffer; execute BODY; restore the current buffer.
1032 Executes BODY just like `progn'.
1033 usage: (save-current-buffer &rest BODY) */)
1034 (args)
1035 Lisp_Object args;
1037 Lisp_Object val;
1038 int count = SPECPDL_INDEX ();
1040 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
1042 val = Fprogn (args);
1043 return unbind_to (count, val);
1046 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1047 doc: /* Return the number of characters in the current buffer.
1048 If BUFFER, return the number of characters in that buffer instead. */)
1049 (buffer)
1050 Lisp_Object buffer;
1052 if (NILP (buffer))
1053 return make_number (Z - BEG);
1054 else
1056 CHECK_BUFFER (buffer);
1057 return make_number (BUF_Z (XBUFFER (buffer))
1058 - BUF_BEG (XBUFFER (buffer)));
1062 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1063 doc: /* Return the minimum permissible value of point in the current buffer.
1064 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1067 Lisp_Object temp;
1068 XSETFASTINT (temp, BEGV);
1069 return temp;
1072 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1073 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1074 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1077 return buildmark (BEGV, BEGV_BYTE);
1080 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1081 doc: /* Return the maximum permissible value of point in the current buffer.
1082 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1083 is in effect, in which case it is less. */)
1086 Lisp_Object temp;
1087 XSETFASTINT (temp, ZV);
1088 return temp;
1091 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1092 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1093 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1094 is in effect, in which case it is less. */)
1097 return buildmark (ZV, ZV_BYTE);
1100 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1101 doc: /* Return the position of the gap, in the current buffer.
1102 See also `gap-size'. */)
1105 Lisp_Object temp;
1106 XSETFASTINT (temp, GPT);
1107 return temp;
1110 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1111 doc: /* Return the size of the current buffer's gap.
1112 See also `gap-position'. */)
1115 Lisp_Object temp;
1116 XSETFASTINT (temp, GAP_SIZE);
1117 return temp;
1120 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1121 doc: /* Return the byte position for character position POSITION.
1122 If POSITION is out of range, the value is nil. */)
1123 (position)
1124 Lisp_Object position;
1126 CHECK_NUMBER_COERCE_MARKER (position);
1127 if (XINT (position) < BEG || XINT (position) > Z)
1128 return Qnil;
1129 return make_number (CHAR_TO_BYTE (XINT (position)));
1132 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1133 doc: /* Return the character position for byte position BYTEPOS.
1134 If BYTEPOS is out of range, the value is nil. */)
1135 (bytepos)
1136 Lisp_Object bytepos;
1138 CHECK_NUMBER (bytepos);
1139 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1140 return Qnil;
1141 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1144 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1145 doc: /* Return the character following point, as a number.
1146 At the end of the buffer or accessible region, return 0. */)
1149 Lisp_Object temp;
1150 if (PT >= ZV)
1151 XSETFASTINT (temp, 0);
1152 else
1153 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1154 return temp;
1157 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1158 doc: /* Return the character preceding point, as a number.
1159 At the beginning of the buffer or accessible region, return 0. */)
1162 Lisp_Object temp;
1163 if (PT <= BEGV)
1164 XSETFASTINT (temp, 0);
1165 else if (!NILP (current_buffer->enable_multibyte_characters))
1167 int pos = PT_BYTE;
1168 DEC_POS (pos);
1169 XSETFASTINT (temp, FETCH_CHAR (pos));
1171 else
1172 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1173 return temp;
1176 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1177 doc: /* Return t if point is at the beginning of the buffer.
1178 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1181 if (PT == BEGV)
1182 return Qt;
1183 return Qnil;
1186 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1187 doc: /* Return t if point is at the end of the buffer.
1188 If the buffer is narrowed, this means the end of the narrowed part. */)
1191 if (PT == ZV)
1192 return Qt;
1193 return Qnil;
1196 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1197 doc: /* Return t if point is at the beginning of a line. */)
1200 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1201 return Qt;
1202 return Qnil;
1205 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1206 doc: /* Return t if point is at the end of a line.
1207 `End of a line' includes point being at the end of the buffer. */)
1210 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1211 return Qt;
1212 return Qnil;
1215 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1216 doc: /* Return character in current buffer at position POS.
1217 POS is an integer or a marker and defaults to point.
1218 If POS is out of range, the value is nil. */)
1219 (pos)
1220 Lisp_Object pos;
1222 register int pos_byte;
1224 if (NILP (pos))
1226 pos_byte = PT_BYTE;
1227 XSETFASTINT (pos, PT);
1230 if (MARKERP (pos))
1232 pos_byte = marker_byte_position (pos);
1233 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1234 return Qnil;
1236 else
1238 CHECK_NUMBER_COERCE_MARKER (pos);
1239 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1240 return Qnil;
1242 pos_byte = CHAR_TO_BYTE (XINT (pos));
1245 return make_number (FETCH_CHAR (pos_byte));
1248 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1249 doc: /* Return character in current buffer preceding position POS.
1250 POS is an integer or a marker and defaults to point.
1251 If POS is out of range, the value is nil. */)
1252 (pos)
1253 Lisp_Object pos;
1255 register Lisp_Object val;
1256 register int pos_byte;
1258 if (NILP (pos))
1260 pos_byte = PT_BYTE;
1261 XSETFASTINT (pos, PT);
1264 if (MARKERP (pos))
1266 pos_byte = marker_byte_position (pos);
1268 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1269 return Qnil;
1271 else
1273 CHECK_NUMBER_COERCE_MARKER (pos);
1275 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1276 return Qnil;
1278 pos_byte = CHAR_TO_BYTE (XINT (pos));
1281 if (!NILP (current_buffer->enable_multibyte_characters))
1283 DEC_POS (pos_byte);
1284 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1286 else
1288 pos_byte--;
1289 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1291 return val;
1294 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1295 doc: /* Return the name under which the user logged in, as a string.
1296 This is based on the effective uid, not the real uid.
1297 Also, if the environment variables LOGNAME or USER are set,
1298 that determines the value of this function.
1300 If optional argument UID is an integer or a float, return the login name
1301 of the user with that uid, or nil if there is no such user. */)
1302 (uid)
1303 Lisp_Object uid;
1305 struct passwd *pw;
1306 uid_t id;
1308 /* Set up the user name info if we didn't do it before.
1309 (That can happen if Emacs is dumpable
1310 but you decide to run `temacs -l loadup' and not dump. */
1311 if (INTEGERP (Vuser_login_name))
1312 init_editfns ();
1314 if (NILP (uid))
1315 return Vuser_login_name;
1317 id = (uid_t)XFLOATINT (uid);
1318 BLOCK_INPUT;
1319 pw = (struct passwd *) getpwuid (id);
1320 UNBLOCK_INPUT;
1321 return (pw ? build_string (pw->pw_name) : Qnil);
1324 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1325 0, 0, 0,
1326 doc: /* Return the name of the user's real uid, as a string.
1327 This ignores the environment variables LOGNAME and USER, so it differs from
1328 `user-login-name' when running under `su'. */)
1331 /* Set up the user name info if we didn't do it before.
1332 (That can happen if Emacs is dumpable
1333 but you decide to run `temacs -l loadup' and not dump. */
1334 if (INTEGERP (Vuser_login_name))
1335 init_editfns ();
1336 return Vuser_real_login_name;
1339 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1340 doc: /* Return the effective uid of Emacs.
1341 Value is an integer or a float, depending on the value. */)
1344 /* Assignment to EMACS_INT stops GCC whining about limited range of
1345 data type. */
1346 EMACS_INT euid = geteuid ();
1348 /* Make sure we don't produce a negative UID due to signed integer
1349 overflow. */
1350 if (euid < 0)
1351 return make_float ((double)geteuid ());
1352 return make_fixnum_or_float (euid);
1355 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1356 doc: /* Return the real uid of Emacs.
1357 Value is an integer or a float, depending on the value. */)
1360 /* Assignment to EMACS_INT stops GCC whining about limited range of
1361 data type. */
1362 EMACS_INT uid = getuid ();
1364 /* Make sure we don't produce a negative UID due to signed integer
1365 overflow. */
1366 if (uid < 0)
1367 return make_float ((double)getuid ());
1368 return make_fixnum_or_float (uid);
1371 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1372 doc: /* Return the full name of the user logged in, as a string.
1373 If the full name corresponding to Emacs's userid is not known,
1374 return "unknown".
1376 If optional argument UID is an integer or float, return the full name
1377 of the user with that uid, or nil if there is no such user.
1378 If UID is a string, return the full name of the user with that login
1379 name, or nil if there is no such user. */)
1380 (uid)
1381 Lisp_Object uid;
1383 struct passwd *pw;
1384 register unsigned char *p, *q;
1385 Lisp_Object full;
1387 if (NILP (uid))
1388 return Vuser_full_name;
1389 else if (NUMBERP (uid))
1391 BLOCK_INPUT;
1392 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1393 UNBLOCK_INPUT;
1395 else if (STRINGP (uid))
1397 BLOCK_INPUT;
1398 pw = (struct passwd *) getpwnam (SDATA (uid));
1399 UNBLOCK_INPUT;
1401 else
1402 error ("Invalid UID specification");
1404 if (!pw)
1405 return Qnil;
1407 p = (unsigned char *) USER_FULL_NAME;
1408 /* Chop off everything after the first comma. */
1409 q = (unsigned char *) index (p, ',');
1410 full = make_string (p, q ? q - p : strlen (p));
1412 #ifdef AMPERSAND_FULL_NAME
1413 p = SDATA (full);
1414 q = (unsigned char *) index (p, '&');
1415 /* Substitute the login name for the &, upcasing the first character. */
1416 if (q)
1418 register unsigned char *r;
1419 Lisp_Object login;
1421 login = Fuser_login_name (make_number (pw->pw_uid));
1422 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1423 bcopy (p, r, q - p);
1424 r[q - p] = 0;
1425 strcat (r, SDATA (login));
1426 r[q - p] = UPCASE (r[q - p]);
1427 strcat (r, q + 1);
1428 full = build_string (r);
1430 #endif /* AMPERSAND_FULL_NAME */
1432 return full;
1435 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1436 doc: /* Return the host name of the machine you are running on, as a string. */)
1439 return Vsystem_name;
1442 /* For the benefit of callers who don't want to include lisp.h */
1444 char *
1445 get_system_name ()
1447 if (STRINGP (Vsystem_name))
1448 return (char *) SDATA (Vsystem_name);
1449 else
1450 return "";
1453 char *
1454 get_operating_system_release()
1456 if (STRINGP (Voperating_system_release))
1457 return (char *) SDATA (Voperating_system_release);
1458 else
1459 return "";
1462 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1463 doc: /* Return the process ID of Emacs, as an integer. */)
1466 return make_number (getpid ());
1469 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1470 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1471 The time is returned as a list of three integers. The first has the
1472 most significant 16 bits of the seconds, while the second has the
1473 least significant 16 bits. The third integer gives the microsecond
1474 count.
1476 The microsecond count is zero on systems that do not provide
1477 resolution finer than a second. */)
1480 EMACS_TIME t;
1482 EMACS_GET_TIME (t);
1483 return list3 (make_number ((EMACS_SECS (t) >> 16) & 0xffff),
1484 make_number ((EMACS_SECS (t) >> 0) & 0xffff),
1485 make_number (EMACS_USECS (t)));
1488 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1489 0, 0, 0,
1490 doc: /* Return the current run time used by Emacs.
1491 The time is returned as a list of three integers. The first has the
1492 most significant 16 bits of the seconds, while the second has the
1493 least significant 16 bits. The third integer gives the microsecond
1494 count.
1496 On systems that can't determine the run time, `get-internal-run-time'
1497 does the same thing as `current-time'. The microsecond count is zero
1498 on systems that do not provide resolution finer than a second. */)
1501 #ifdef HAVE_GETRUSAGE
1502 struct rusage usage;
1503 int secs, usecs;
1505 if (getrusage (RUSAGE_SELF, &usage) < 0)
1506 /* This shouldn't happen. What action is appropriate? */
1507 xsignal0 (Qerror);
1509 /* Sum up user time and system time. */
1510 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1511 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1512 if (usecs >= 1000000)
1514 usecs -= 1000000;
1515 secs++;
1518 return list3 (make_number ((secs >> 16) & 0xffff),
1519 make_number ((secs >> 0) & 0xffff),
1520 make_number (usecs));
1521 #else /* ! HAVE_GETRUSAGE */
1522 #ifdef WINDOWSNT
1523 return w32_get_internal_run_time ();
1524 #else /* ! WINDOWSNT */
1525 return Fcurrent_time ();
1526 #endif /* WINDOWSNT */
1527 #endif /* HAVE_GETRUSAGE */
1532 lisp_time_argument (specified_time, result, usec)
1533 Lisp_Object specified_time;
1534 time_t *result;
1535 int *usec;
1537 if (NILP (specified_time))
1539 if (usec)
1541 EMACS_TIME t;
1543 EMACS_GET_TIME (t);
1544 *usec = EMACS_USECS (t);
1545 *result = EMACS_SECS (t);
1546 return 1;
1548 else
1549 return time (result) != -1;
1551 else
1553 Lisp_Object high, low;
1554 high = Fcar (specified_time);
1555 CHECK_NUMBER (high);
1556 low = Fcdr (specified_time);
1557 if (CONSP (low))
1559 if (usec)
1561 Lisp_Object usec_l = Fcdr (low);
1562 if (CONSP (usec_l))
1563 usec_l = Fcar (usec_l);
1564 if (NILP (usec_l))
1565 *usec = 0;
1566 else
1568 CHECK_NUMBER (usec_l);
1569 *usec = XINT (usec_l);
1572 low = Fcar (low);
1574 else if (usec)
1575 *usec = 0;
1576 CHECK_NUMBER (low);
1577 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1578 return *result >> 16 == XINT (high);
1582 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1583 doc: /* Return the current time, as a float number of seconds since the epoch.
1584 If SPECIFIED-TIME is given, it is the time to convert to float
1585 instead of the current time. The argument should have the form
1586 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1587 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1588 have the form (HIGH . LOW), but this is considered obsolete.
1590 WARNING: Since the result is floating point, it may not be exact.
1591 If precise time stamps are required, use either `current-time',
1592 or (if you need time as a string) `format-time-string'. */)
1593 (specified_time)
1594 Lisp_Object specified_time;
1596 time_t sec;
1597 int usec;
1599 if (! lisp_time_argument (specified_time, &sec, &usec))
1600 error ("Invalid time specification");
1602 return make_float ((sec * 1e6 + usec) / 1e6);
1605 /* Write information into buffer S of size MAXSIZE, according to the
1606 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1607 Default to Universal Time if UT is nonzero, local time otherwise.
1608 Return the number of bytes written, not including the terminating
1609 '\0'. If S is NULL, nothing will be written anywhere; so to
1610 determine how many bytes would be written, use NULL for S and
1611 ((size_t) -1) for MAXSIZE.
1613 This function behaves like emacs_strftimeu, except it allows null
1614 bytes in FORMAT. */
1615 static size_t
1616 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1617 char *s;
1618 size_t maxsize;
1619 const char *format;
1620 size_t format_len;
1621 const struct tm *tp;
1622 int ut;
1624 size_t total = 0;
1626 /* Loop through all the null-terminated strings in the format
1627 argument. Normally there's just one null-terminated string, but
1628 there can be arbitrarily many, concatenated together, if the
1629 format contains '\0' bytes. emacs_strftimeu stops at the first
1630 '\0' byte so we must invoke it separately for each such string. */
1631 for (;;)
1633 size_t len;
1634 size_t result;
1636 if (s)
1637 s[0] = '\1';
1639 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1641 if (s)
1643 if (result == 0 && s[0] != '\0')
1644 return 0;
1645 s += result + 1;
1648 maxsize -= result + 1;
1649 total += result;
1650 len = strlen (format);
1651 if (len == format_len)
1652 return total;
1653 total++;
1654 format += len + 1;
1655 format_len -= len + 1;
1659 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1660 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1661 TIME is specified as (HIGH LOW . IGNORED), as returned by
1662 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1663 is also still accepted.
1664 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1665 as Universal Time; nil means describe TIME in the local time zone.
1666 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1667 by text that describes the specified date and time in TIME:
1669 %Y is the year, %y within the century, %C the century.
1670 %G is the year corresponding to the ISO week, %g within the century.
1671 %m is the numeric month.
1672 %b and %h are the locale's abbreviated month name, %B the full name.
1673 %d is the day of the month, zero-padded, %e is blank-padded.
1674 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1675 %a is the locale's abbreviated name of the day of week, %A the full name.
1676 %U is the week number starting on Sunday, %W starting on Monday,
1677 %V according to ISO 8601.
1678 %j is the day of the year.
1680 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1681 only blank-padded, %l is like %I blank-padded.
1682 %p is the locale's equivalent of either AM or PM.
1683 %M is the minute.
1684 %S is the second.
1685 %Z is the time zone name, %z is the numeric form.
1686 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1688 %c is the locale's date and time format.
1689 %x is the locale's "preferred" date format.
1690 %D is like "%m/%d/%y".
1692 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1693 %X is the locale's "preferred" time format.
1695 Finally, %n is a newline, %t is a tab, %% is a literal %.
1697 Certain flags and modifiers are available with some format controls.
1698 The flags are `_', `-', `^' and `#'. For certain characters X,
1699 %_X is like %X, but padded with blanks; %-X is like %X,
1700 but without padding. %^X is like %X, but with all textual
1701 characters up-cased; %#X is like %X, but with letter-case of
1702 all textual characters reversed.
1703 %NX (where N stands for an integer) is like %X,
1704 but takes up at least N (a number) positions.
1705 The modifiers are `E' and `O'. For certain characters X,
1706 %EX is a locale's alternative version of %X;
1707 %OX is like %X, but uses the locale's number symbols.
1709 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1710 (format_string, time, universal)
1711 Lisp_Object format_string, time, universal;
1713 time_t value;
1714 int size;
1715 struct tm *tm;
1716 int ut = ! NILP (universal);
1718 CHECK_STRING (format_string);
1720 if (! lisp_time_argument (time, &value, NULL))
1721 error ("Invalid time specification");
1723 format_string = code_convert_string_norecord (format_string,
1724 Vlocale_coding_system, 1);
1726 /* This is probably enough. */
1727 size = SBYTES (format_string) * 6 + 50;
1729 BLOCK_INPUT;
1730 tm = ut ? gmtime (&value) : localtime (&value);
1731 UNBLOCK_INPUT;
1732 if (! tm)
1733 error ("Specified time is not representable");
1735 synchronize_system_time_locale ();
1737 while (1)
1739 char *buf = (char *) alloca (size + 1);
1740 int result;
1742 buf[0] = '\1';
1743 BLOCK_INPUT;
1744 result = emacs_memftimeu (buf, size, SDATA (format_string),
1745 SBYTES (format_string),
1746 tm, ut);
1747 UNBLOCK_INPUT;
1748 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1749 return code_convert_string_norecord (make_unibyte_string (buf, result),
1750 Vlocale_coding_system, 0);
1752 /* If buffer was too small, make it bigger and try again. */
1753 BLOCK_INPUT;
1754 result = emacs_memftimeu (NULL, (size_t) -1,
1755 SDATA (format_string),
1756 SBYTES (format_string),
1757 tm, ut);
1758 UNBLOCK_INPUT;
1759 size = result + 1;
1763 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1764 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1765 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1766 as from `current-time' and `file-attributes', or nil to use the
1767 current time. The obsolete form (HIGH . LOW) is also still accepted.
1768 The list has the following nine members: SEC is an integer between 0
1769 and 60; SEC is 60 for a leap second, which only some operating systems
1770 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1771 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1772 integer between 1 and 12. YEAR is an integer indicating the
1773 four-digit year. DOW is the day of week, an integer between 0 and 6,
1774 where 0 is Sunday. DST is t if daylight saving time is in effect,
1775 otherwise nil. ZONE is an integer indicating the number of seconds
1776 east of Greenwich. (Note that Common Lisp has different meanings for
1777 DOW and ZONE.) */)
1778 (specified_time)
1779 Lisp_Object specified_time;
1781 time_t time_spec;
1782 struct tm save_tm;
1783 struct tm *decoded_time;
1784 Lisp_Object list_args[9];
1786 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1787 error ("Invalid time specification");
1789 BLOCK_INPUT;
1790 decoded_time = localtime (&time_spec);
1791 UNBLOCK_INPUT;
1792 if (! decoded_time)
1793 error ("Specified time is not representable");
1794 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1795 XSETFASTINT (list_args[1], decoded_time->tm_min);
1796 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1797 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1798 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1799 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1800 cast below avoids overflow in int arithmetics. */
1801 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1802 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1803 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1805 /* Make a copy, in case gmtime modifies the struct. */
1806 save_tm = *decoded_time;
1807 BLOCK_INPUT;
1808 decoded_time = gmtime (&time_spec);
1809 UNBLOCK_INPUT;
1810 if (decoded_time == 0)
1811 list_args[8] = Qnil;
1812 else
1813 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1814 return Flist (9, list_args);
1817 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1818 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1819 This is the reverse operation of `decode-time', which see.
1820 ZONE defaults to the current time zone rule. This can
1821 be a string or t (as from `set-time-zone-rule'), or it can be a list
1822 \(as from `current-time-zone') or an integer (as from `decode-time')
1823 applied without consideration for daylight saving time.
1825 You can pass more than 7 arguments; then the first six arguments
1826 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1827 The intervening arguments are ignored.
1828 This feature lets (apply 'encode-time (decode-time ...)) work.
1830 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1831 for example, a DAY of 0 means the day preceding the given month.
1832 Year numbers less than 100 are treated just like other year numbers.
1833 If you want them to stand for years in this century, you must do that yourself.
1835 Years before 1970 are not guaranteed to work. On some systems,
1836 year values as low as 1901 do work.
1838 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1839 (nargs, args)
1840 int nargs;
1841 register Lisp_Object *args;
1843 time_t time;
1844 struct tm tm;
1845 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1847 CHECK_NUMBER (args[0]); /* second */
1848 CHECK_NUMBER (args[1]); /* minute */
1849 CHECK_NUMBER (args[2]); /* hour */
1850 CHECK_NUMBER (args[3]); /* day */
1851 CHECK_NUMBER (args[4]); /* month */
1852 CHECK_NUMBER (args[5]); /* year */
1854 tm.tm_sec = XINT (args[0]);
1855 tm.tm_min = XINT (args[1]);
1856 tm.tm_hour = XINT (args[2]);
1857 tm.tm_mday = XINT (args[3]);
1858 tm.tm_mon = XINT (args[4]) - 1;
1859 tm.tm_year = XINT (args[5]) - TM_YEAR_BASE;
1860 tm.tm_isdst = -1;
1862 if (CONSP (zone))
1863 zone = Fcar (zone);
1864 if (NILP (zone))
1866 BLOCK_INPUT;
1867 time = mktime (&tm);
1868 UNBLOCK_INPUT;
1870 else
1872 char tzbuf[100];
1873 char *tzstring;
1874 char **oldenv = environ, **newenv;
1876 if (EQ (zone, Qt))
1877 tzstring = "UTC0";
1878 else if (STRINGP (zone))
1879 tzstring = (char *) SDATA (zone);
1880 else if (INTEGERP (zone))
1882 int abszone = eabs (XINT (zone));
1883 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1884 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1885 tzstring = tzbuf;
1887 else
1888 error ("Invalid time zone specification");
1890 /* Set TZ before calling mktime; merely adjusting mktime's returned
1891 value doesn't suffice, since that would mishandle leap seconds. */
1892 set_time_zone_rule (tzstring);
1894 BLOCK_INPUT;
1895 time = mktime (&tm);
1896 UNBLOCK_INPUT;
1898 /* Restore TZ to previous value. */
1899 newenv = environ;
1900 environ = oldenv;
1901 xfree (newenv);
1902 #ifdef LOCALTIME_CACHE
1903 tzset ();
1904 #endif
1907 if (time == (time_t) -1)
1908 error ("Specified time is not representable");
1910 return make_time (time);
1913 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1914 doc: /* Return the current local time, as a human-readable string.
1915 Programs can use this function to decode a time,
1916 since the number of columns in each field is fixed
1917 if the year is in the range 1000-9999.
1918 The format is `Sun Sep 16 01:03:52 1973'.
1919 However, see also the functions `decode-time' and `format-time-string'
1920 which provide a much more powerful and general facility.
1922 If SPECIFIED-TIME is given, it is a time to format instead of the
1923 current time. The argument should have the form (HIGH LOW . IGNORED).
1924 Thus, you can use times obtained from `current-time' and from
1925 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1926 but this is considered obsolete. */)
1927 (specified_time)
1928 Lisp_Object specified_time;
1930 time_t value;
1931 struct tm *tm;
1932 register char *tem;
1934 if (! lisp_time_argument (specified_time, &value, NULL))
1935 error ("Invalid time specification");
1937 /* Convert to a string, checking for out-of-range time stamps.
1938 Don't use 'ctime', as that might dump core if VALUE is out of
1939 range. */
1940 BLOCK_INPUT;
1941 tm = localtime (&value);
1942 UNBLOCK_INPUT;
1943 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1944 error ("Specified time is not representable");
1946 /* Remove the trailing newline. */
1947 tem[strlen (tem) - 1] = '\0';
1949 return build_string (tem);
1952 /* Yield A - B, measured in seconds.
1953 This function is copied from the GNU C Library. */
1954 static int
1955 tm_diff (a, b)
1956 struct tm *a, *b;
1958 /* Compute intervening leap days correctly even if year is negative.
1959 Take care to avoid int overflow in leap day calculations,
1960 but it's OK to assume that A and B are close to each other. */
1961 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1962 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1963 int a100 = a4 / 25 - (a4 % 25 < 0);
1964 int b100 = b4 / 25 - (b4 % 25 < 0);
1965 int a400 = a100 >> 2;
1966 int b400 = b100 >> 2;
1967 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1968 int years = a->tm_year - b->tm_year;
1969 int days = (365 * years + intervening_leap_days
1970 + (a->tm_yday - b->tm_yday));
1971 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1972 + (a->tm_min - b->tm_min))
1973 + (a->tm_sec - b->tm_sec));
1976 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1977 doc: /* Return the offset and name for the local time zone.
1978 This returns a list of the form (OFFSET NAME).
1979 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1980 A negative value means west of Greenwich.
1981 NAME is a string giving the name of the time zone.
1982 If SPECIFIED-TIME is given, the time zone offset is determined from it
1983 instead of using the current time. The argument should have the form
1984 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1985 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1986 have the form (HIGH . LOW), but this is considered obsolete.
1988 Some operating systems cannot provide all this information to Emacs;
1989 in this case, `current-time-zone' returns a list containing nil for
1990 the data it can't find. */)
1991 (specified_time)
1992 Lisp_Object specified_time;
1994 time_t value;
1995 struct tm *t;
1996 struct tm gmt;
1998 if (!lisp_time_argument (specified_time, &value, NULL))
1999 t = NULL;
2000 else
2002 BLOCK_INPUT;
2003 t = gmtime (&value);
2004 if (t)
2006 gmt = *t;
2007 t = localtime (&value);
2009 UNBLOCK_INPUT;
2012 if (t)
2014 int offset = tm_diff (t, &gmt);
2015 char *s = 0;
2016 char buf[6];
2018 #ifdef HAVE_TM_ZONE
2019 if (t->tm_zone)
2020 s = (char *)t->tm_zone;
2021 #else /* not HAVE_TM_ZONE */
2022 #ifdef HAVE_TZNAME
2023 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2024 s = tzname[t->tm_isdst];
2025 #endif
2026 #endif /* not HAVE_TM_ZONE */
2028 if (!s)
2030 /* No local time zone name is available; use "+-NNNN" instead. */
2031 int am = (offset < 0 ? -offset : offset) / 60;
2032 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2033 s = buf;
2036 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2038 else
2039 return Fmake_list (make_number (2), Qnil);
2042 /* This holds the value of `environ' produced by the previous
2043 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2044 has never been called. */
2045 static char **environbuf;
2047 /* This holds the startup value of the TZ environment variable so it
2048 can be restored if the user calls set-time-zone-rule with a nil
2049 argument. */
2050 static char *initial_tz;
2052 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2053 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2054 If TZ is nil, use implementation-defined default time zone information.
2055 If TZ is t, use Universal Time. */)
2056 (tz)
2057 Lisp_Object tz;
2059 char *tzstring;
2061 /* When called for the first time, save the original TZ. */
2062 if (!environbuf)
2063 initial_tz = (char *) getenv ("TZ");
2065 if (NILP (tz))
2066 tzstring = initial_tz;
2067 else if (EQ (tz, Qt))
2068 tzstring = "UTC0";
2069 else
2071 CHECK_STRING (tz);
2072 tzstring = (char *) SDATA (tz);
2075 set_time_zone_rule (tzstring);
2076 free (environbuf);
2077 environbuf = environ;
2079 return Qnil;
2082 #ifdef LOCALTIME_CACHE
2084 /* These two values are known to load tz files in buggy implementations,
2085 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2086 Their values shouldn't matter in non-buggy implementations.
2087 We don't use string literals for these strings,
2088 since if a string in the environment is in readonly
2089 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2090 See Sun bugs 1113095 and 1114114, ``Timezone routines
2091 improperly modify environment''. */
2093 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2094 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2096 #endif
2098 /* Set the local time zone rule to TZSTRING.
2099 This allocates memory into `environ', which it is the caller's
2100 responsibility to free. */
2102 void
2103 set_time_zone_rule (tzstring)
2104 char *tzstring;
2106 int envptrs;
2107 char **from, **to, **newenv;
2109 /* Make the ENVIRON vector longer with room for TZSTRING. */
2110 for (from = environ; *from; from++)
2111 continue;
2112 envptrs = from - environ + 2;
2113 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2114 + (tzstring ? strlen (tzstring) + 4 : 0));
2116 /* Add TZSTRING to the end of environ, as a value for TZ. */
2117 if (tzstring)
2119 char *t = (char *) (to + envptrs);
2120 strcpy (t, "TZ=");
2121 strcat (t, tzstring);
2122 *to++ = t;
2125 /* Copy the old environ vector elements into NEWENV,
2126 but don't copy the TZ variable.
2127 So we have only one definition of TZ, which came from TZSTRING. */
2128 for (from = environ; *from; from++)
2129 if (strncmp (*from, "TZ=", 3) != 0)
2130 *to++ = *from;
2131 *to = 0;
2133 environ = newenv;
2135 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2136 the TZ variable is stored. If we do not have a TZSTRING,
2137 TO points to the vector slot which has the terminating null. */
2139 #ifdef LOCALTIME_CACHE
2141 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2142 "US/Pacific" that loads a tz file, then changes to a value like
2143 "XXX0" that does not load a tz file, and then changes back to
2144 its original value, the last change is (incorrectly) ignored.
2145 Also, if TZ changes twice in succession to values that do
2146 not load a tz file, tzset can dump core (see Sun bug#1225179).
2147 The following code works around these bugs. */
2149 if (tzstring)
2151 /* Temporarily set TZ to a value that loads a tz file
2152 and that differs from tzstring. */
2153 char *tz = *newenv;
2154 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2155 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2156 tzset ();
2157 *newenv = tz;
2159 else
2161 /* The implied tzstring is unknown, so temporarily set TZ to
2162 two different values that each load a tz file. */
2163 *to = set_time_zone_rule_tz1;
2164 to[1] = 0;
2165 tzset ();
2166 *to = set_time_zone_rule_tz2;
2167 tzset ();
2168 *to = 0;
2171 /* Now TZ has the desired value, and tzset can be invoked safely. */
2174 tzset ();
2175 #endif
2178 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2179 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2180 type of object is Lisp_String). INHERIT is passed to
2181 INSERT_FROM_STRING_FUNC as the last argument. */
2183 static void
2184 general_insert_function (void (*insert_func)
2185 (const unsigned char *, EMACS_INT),
2186 void (*insert_from_string_func)
2187 (Lisp_Object, EMACS_INT, EMACS_INT,
2188 EMACS_INT, EMACS_INT, int),
2189 int inherit, int nargs, Lisp_Object *args)
2191 register int argnum;
2192 register Lisp_Object val;
2194 for (argnum = 0; argnum < nargs; argnum++)
2196 val = args[argnum];
2197 if (CHARACTERP (val))
2199 unsigned char str[MAX_MULTIBYTE_LENGTH];
2200 int len;
2202 if (!NILP (current_buffer->enable_multibyte_characters))
2203 len = CHAR_STRING (XFASTINT (val), str);
2204 else
2206 str[0] = (ASCII_CHAR_P (XINT (val))
2207 ? XINT (val)
2208 : multibyte_char_to_unibyte (XINT (val), Qnil));
2209 len = 1;
2211 (*insert_func) (str, len);
2213 else if (STRINGP (val))
2215 (*insert_from_string_func) (val, 0, 0,
2216 SCHARS (val),
2217 SBYTES (val),
2218 inherit);
2220 else
2221 wrong_type_argument (Qchar_or_string_p, val);
2225 void
2226 insert1 (arg)
2227 Lisp_Object arg;
2229 Finsert (1, &arg);
2233 /* Callers passing one argument to Finsert need not gcpro the
2234 argument "array", since the only element of the array will
2235 not be used after calling insert or insert_from_string, so
2236 we don't care if it gets trashed. */
2238 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2239 doc: /* Insert the arguments, either strings or characters, at point.
2240 Point and before-insertion markers move forward to end up
2241 after the inserted text.
2242 Any other markers at the point of insertion remain before the text.
2244 If the current buffer is multibyte, unibyte strings are converted
2245 to multibyte for insertion (see `string-make-multibyte').
2246 If the current buffer is unibyte, multibyte strings are converted
2247 to unibyte for insertion (see `string-make-unibyte').
2249 When operating on binary data, it may be necessary to preserve the
2250 original bytes of a unibyte string when inserting it into a multibyte
2251 buffer; to accomplish this, apply `string-as-multibyte' to the string
2252 and insert the result.
2254 usage: (insert &rest ARGS) */)
2255 (nargs, args)
2256 int nargs;
2257 register Lisp_Object *args;
2259 general_insert_function (insert, insert_from_string, 0, nargs, args);
2260 return Qnil;
2263 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2264 0, MANY, 0,
2265 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2266 Point and before-insertion markers move forward to end up
2267 after the inserted text.
2268 Any other markers at the point of insertion remain before the text.
2270 If the current buffer is multibyte, unibyte strings are converted
2271 to multibyte for insertion (see `unibyte-char-to-multibyte').
2272 If the current buffer is unibyte, multibyte strings are converted
2273 to unibyte for insertion.
2275 usage: (insert-and-inherit &rest ARGS) */)
2276 (nargs, args)
2277 int nargs;
2278 register Lisp_Object *args;
2280 general_insert_function (insert_and_inherit, insert_from_string, 1,
2281 nargs, args);
2282 return Qnil;
2285 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2286 doc: /* Insert strings or characters at point, relocating markers after the text.
2287 Point and markers move forward to end up after the inserted text.
2289 If the current buffer is multibyte, unibyte strings are converted
2290 to multibyte for insertion (see `unibyte-char-to-multibyte').
2291 If the current buffer is unibyte, multibyte strings are converted
2292 to unibyte for insertion.
2294 usage: (insert-before-markers &rest ARGS) */)
2295 (nargs, args)
2296 int nargs;
2297 register Lisp_Object *args;
2299 general_insert_function (insert_before_markers,
2300 insert_from_string_before_markers, 0,
2301 nargs, args);
2302 return Qnil;
2305 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2306 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2307 doc: /* Insert text at point, relocating markers and inheriting properties.
2308 Point and markers move forward to end up after the inserted text.
2310 If the current buffer is multibyte, unibyte strings are converted
2311 to multibyte for insertion (see `unibyte-char-to-multibyte').
2312 If the current buffer is unibyte, multibyte strings are converted
2313 to unibyte for insertion.
2315 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2316 (nargs, args)
2317 int nargs;
2318 register Lisp_Object *args;
2320 general_insert_function (insert_before_markers_and_inherit,
2321 insert_from_string_before_markers, 1,
2322 nargs, args);
2323 return Qnil;
2326 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2327 doc: /* Insert COUNT copies of CHARACTER.
2328 Point, and before-insertion markers, are relocated as in the function `insert'.
2329 The optional third arg INHERIT, if non-nil, says to inherit text properties
2330 from adjoining text, if those properties are sticky. */)
2331 (character, count, inherit)
2332 Lisp_Object character, count, inherit;
2334 register unsigned char *string;
2335 register int strlen;
2336 register int i, n;
2337 int len;
2338 unsigned char str[MAX_MULTIBYTE_LENGTH];
2340 CHECK_NUMBER (character);
2341 CHECK_NUMBER (count);
2343 if (!NILP (current_buffer->enable_multibyte_characters))
2344 len = CHAR_STRING (XFASTINT (character), str);
2345 else
2346 str[0] = XFASTINT (character), len = 1;
2347 n = XINT (count) * len;
2348 if (n <= 0)
2349 return Qnil;
2350 strlen = min (n, 256 * len);
2351 string = (unsigned char *) alloca (strlen);
2352 for (i = 0; i < strlen; i++)
2353 string[i] = str[i % len];
2354 while (n >= strlen)
2356 QUIT;
2357 if (!NILP (inherit))
2358 insert_and_inherit (string, strlen);
2359 else
2360 insert (string, strlen);
2361 n -= strlen;
2363 if (n > 0)
2365 if (!NILP (inherit))
2366 insert_and_inherit (string, n);
2367 else
2368 insert (string, n);
2370 return Qnil;
2373 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2374 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2375 Both arguments are required.
2376 BYTE is a number of the range 0..255.
2378 If BYTE is 128..255 and the current buffer is multibyte, the
2379 corresponding eight-bit character is inserted.
2381 Point, and before-insertion markers, are relocated as in the function `insert'.
2382 The optional third arg INHERIT, if non-nil, says to inherit text properties
2383 from adjoining text, if those properties are sticky. */)
2384 (byte, count, inherit)
2385 Lisp_Object byte, count, inherit;
2387 CHECK_NUMBER (byte);
2388 if (XINT (byte) < 0 || XINT (byte) > 255)
2389 args_out_of_range_3 (byte, make_number (0), make_number (255));
2390 if (XINT (byte) >= 128
2391 && ! NILP (current_buffer->enable_multibyte_characters))
2392 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2393 return Finsert_char (byte, count, inherit);
2397 /* Making strings from buffer contents. */
2399 /* Return a Lisp_String containing the text of the current buffer from
2400 START to END. If text properties are in use and the current buffer
2401 has properties in the range specified, the resulting string will also
2402 have them, if PROPS is nonzero.
2404 We don't want to use plain old make_string here, because it calls
2405 make_uninit_string, which can cause the buffer arena to be
2406 compacted. make_string has no way of knowing that the data has
2407 been moved, and thus copies the wrong data into the string. This
2408 doesn't effect most of the other users of make_string, so it should
2409 be left as is. But we should use this function when conjuring
2410 buffer substrings. */
2412 Lisp_Object
2413 make_buffer_string (start, end, props)
2414 int start, end;
2415 int props;
2417 int start_byte = CHAR_TO_BYTE (start);
2418 int end_byte = CHAR_TO_BYTE (end);
2420 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2423 /* Return a Lisp_String containing the text of the current buffer from
2424 START / START_BYTE to END / END_BYTE.
2426 If text properties are in use and the current buffer
2427 has properties in the range specified, the resulting string will also
2428 have them, if PROPS is nonzero.
2430 We don't want to use plain old make_string here, because it calls
2431 make_uninit_string, which can cause the buffer arena to be
2432 compacted. make_string has no way of knowing that the data has
2433 been moved, and thus copies the wrong data into the string. This
2434 doesn't effect most of the other users of make_string, so it should
2435 be left as is. But we should use this function when conjuring
2436 buffer substrings. */
2438 Lisp_Object
2439 make_buffer_string_both (start, start_byte, end, end_byte, props)
2440 int start, start_byte, end, end_byte;
2441 int props;
2443 Lisp_Object result, tem, tem1;
2445 if (start < GPT && GPT < end)
2446 move_gap (start);
2448 if (! NILP (current_buffer->enable_multibyte_characters))
2449 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2450 else
2451 result = make_uninit_string (end - start);
2452 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
2453 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 (start, end)
2476 int start, end;
2478 /* If this buffer has some access functions,
2479 call them, specifying the range of the buffer being accessed. */
2480 if (!NILP (Vbuffer_access_fontify_functions))
2482 Lisp_Object args[3];
2483 Lisp_Object tem;
2485 args[0] = Qbuffer_access_fontify_functions;
2486 XSETINT (args[1], start);
2487 XSETINT (args[2], end);
2489 /* But don't call them if we can tell that the work
2490 has already been done. */
2491 if (!NILP (Vbuffer_access_fontified_property))
2493 tem = Ftext_property_any (args[1], args[2],
2494 Vbuffer_access_fontified_property,
2495 Qnil, Qnil);
2496 if (! NILP (tem))
2497 Frun_hook_with_args (3, args);
2499 else
2500 Frun_hook_with_args (3, args);
2504 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2505 doc: /* Return the contents of part of the current buffer as a string.
2506 The two arguments START and END are character positions;
2507 they can be in either order.
2508 The string returned is multibyte if the buffer is multibyte.
2510 This function copies the text properties of that part of the buffer
2511 into the result string; if you don't want the text properties,
2512 use `buffer-substring-no-properties' instead. */)
2513 (start, end)
2514 Lisp_Object start, end;
2516 register int b, e;
2518 validate_region (&start, &end);
2519 b = XINT (start);
2520 e = XINT (end);
2522 return make_buffer_string (b, e, 1);
2525 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2526 Sbuffer_substring_no_properties, 2, 2, 0,
2527 doc: /* Return the characters of part of the buffer, without the text properties.
2528 The two arguments START and END are character positions;
2529 they can be in either order. */)
2530 (start, end)
2531 Lisp_Object start, end;
2533 register int b, e;
2535 validate_region (&start, &end);
2536 b = XINT (start);
2537 e = XINT (end);
2539 return make_buffer_string (b, e, 0);
2542 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2543 doc: /* Return the contents of the current buffer as a string.
2544 If narrowing is in effect, this function returns only the visible part
2545 of the buffer. */)
2548 return make_buffer_string (BEGV, ZV, 1);
2551 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2552 1, 3, 0,
2553 doc: /* Insert before point a substring of the contents of BUFFER.
2554 BUFFER may be a buffer or a buffer name.
2555 Arguments START and END are character positions specifying the substring.
2556 They default to the values of (point-min) and (point-max) in BUFFER. */)
2557 (buffer, start, end)
2558 Lisp_Object buffer, start, end;
2560 register int b, e, temp;
2561 register struct buffer *bp, *obuf;
2562 Lisp_Object buf;
2564 buf = Fget_buffer (buffer);
2565 if (NILP (buf))
2566 nsberror (buffer);
2567 bp = XBUFFER (buf);
2568 if (NILP (bp->name))
2569 error ("Selecting deleted buffer");
2571 if (NILP (start))
2572 b = BUF_BEGV (bp);
2573 else
2575 CHECK_NUMBER_COERCE_MARKER (start);
2576 b = XINT (start);
2578 if (NILP (end))
2579 e = BUF_ZV (bp);
2580 else
2582 CHECK_NUMBER_COERCE_MARKER (end);
2583 e = XINT (end);
2586 if (b > e)
2587 temp = b, b = e, e = temp;
2589 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2590 args_out_of_range (start, end);
2592 obuf = current_buffer;
2593 set_buffer_internal_1 (bp);
2594 update_buffer_properties (b, e);
2595 set_buffer_internal_1 (obuf);
2597 insert_from_buffer (bp, b, e - b, 0);
2598 return Qnil;
2601 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2602 6, 6, 0,
2603 doc: /* Compare two substrings of two buffers; return result as number.
2604 the value is -N if first string is less after N-1 chars,
2605 +N if first string is greater after N-1 chars, or 0 if strings match.
2606 Each substring is represented as three arguments: BUFFER, START and END.
2607 That makes six args in all, three for each substring.
2609 The value of `case-fold-search' in the current buffer
2610 determines whether case is significant or ignored. */)
2611 (buffer1, start1, end1, buffer2, start2, end2)
2612 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2614 register int begp1, endp1, begp2, endp2, temp;
2615 register struct buffer *bp1, *bp2;
2616 register Lisp_Object trt
2617 = (!NILP (current_buffer->case_fold_search)
2618 ? current_buffer->case_canon_table : Qnil);
2619 int chars = 0;
2620 int i1, i2, i1_byte, i2_byte;
2622 /* Find the first buffer and its substring. */
2624 if (NILP (buffer1))
2625 bp1 = current_buffer;
2626 else
2628 Lisp_Object buf1;
2629 buf1 = Fget_buffer (buffer1);
2630 if (NILP (buf1))
2631 nsberror (buffer1);
2632 bp1 = XBUFFER (buf1);
2633 if (NILP (bp1->name))
2634 error ("Selecting deleted buffer");
2637 if (NILP (start1))
2638 begp1 = BUF_BEGV (bp1);
2639 else
2641 CHECK_NUMBER_COERCE_MARKER (start1);
2642 begp1 = XINT (start1);
2644 if (NILP (end1))
2645 endp1 = BUF_ZV (bp1);
2646 else
2648 CHECK_NUMBER_COERCE_MARKER (end1);
2649 endp1 = XINT (end1);
2652 if (begp1 > endp1)
2653 temp = begp1, begp1 = endp1, endp1 = temp;
2655 if (!(BUF_BEGV (bp1) <= begp1
2656 && begp1 <= endp1
2657 && endp1 <= BUF_ZV (bp1)))
2658 args_out_of_range (start1, end1);
2660 /* Likewise for second substring. */
2662 if (NILP (buffer2))
2663 bp2 = current_buffer;
2664 else
2666 Lisp_Object buf2;
2667 buf2 = Fget_buffer (buffer2);
2668 if (NILP (buf2))
2669 nsberror (buffer2);
2670 bp2 = XBUFFER (buf2);
2671 if (NILP (bp2->name))
2672 error ("Selecting deleted buffer");
2675 if (NILP (start2))
2676 begp2 = BUF_BEGV (bp2);
2677 else
2679 CHECK_NUMBER_COERCE_MARKER (start2);
2680 begp2 = XINT (start2);
2682 if (NILP (end2))
2683 endp2 = BUF_ZV (bp2);
2684 else
2686 CHECK_NUMBER_COERCE_MARKER (end2);
2687 endp2 = XINT (end2);
2690 if (begp2 > endp2)
2691 temp = begp2, begp2 = endp2, endp2 = temp;
2693 if (!(BUF_BEGV (bp2) <= begp2
2694 && begp2 <= endp2
2695 && endp2 <= BUF_ZV (bp2)))
2696 args_out_of_range (start2, end2);
2698 i1 = begp1;
2699 i2 = begp2;
2700 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2701 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2703 while (i1 < endp1 && i2 < endp2)
2705 /* When we find a mismatch, we must compare the
2706 characters, not just the bytes. */
2707 int c1, c2;
2709 QUIT;
2711 if (! NILP (bp1->enable_multibyte_characters))
2713 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2714 BUF_INC_POS (bp1, i1_byte);
2715 i1++;
2717 else
2719 c1 = BUF_FETCH_BYTE (bp1, i1);
2720 MAKE_CHAR_MULTIBYTE (c1);
2721 i1++;
2724 if (! NILP (bp2->enable_multibyte_characters))
2726 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2727 BUF_INC_POS (bp2, i2_byte);
2728 i2++;
2730 else
2732 c2 = BUF_FETCH_BYTE (bp2, i2);
2733 MAKE_CHAR_MULTIBYTE (c2);
2734 i2++;
2737 if (!NILP (trt))
2739 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2740 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2742 if (c1 < c2)
2743 return make_number (- 1 - chars);
2744 if (c1 > c2)
2745 return make_number (chars + 1);
2747 chars++;
2750 /* The strings match as far as they go.
2751 If one is shorter, that one is less. */
2752 if (chars < endp1 - begp1)
2753 return make_number (chars + 1);
2754 else if (chars < endp2 - begp2)
2755 return make_number (- chars - 1);
2757 /* Same length too => they are equal. */
2758 return make_number (0);
2761 static Lisp_Object
2762 subst_char_in_region_unwind (arg)
2763 Lisp_Object arg;
2765 return current_buffer->undo_list = arg;
2768 static Lisp_Object
2769 subst_char_in_region_unwind_1 (arg)
2770 Lisp_Object arg;
2772 return current_buffer->filename = arg;
2775 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2776 Ssubst_char_in_region, 4, 5, 0,
2777 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2778 If optional arg NOUNDO is non-nil, don't record this change for undo
2779 and don't mark the buffer as really changed.
2780 Both characters must have the same length of multi-byte form. */)
2781 (start, end, fromchar, tochar, noundo)
2782 Lisp_Object start, end, fromchar, tochar, noundo;
2784 register int pos, pos_byte, stop, i, len, end_byte;
2785 /* Keep track of the first change in the buffer:
2786 if 0 we haven't found it yet.
2787 if < 0 we've found it and we've run the before-change-function.
2788 if > 0 we've actually performed it and the value is its position. */
2789 int changed = 0;
2790 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2791 unsigned char *p;
2792 int count = SPECPDL_INDEX ();
2793 #define COMBINING_NO 0
2794 #define COMBINING_BEFORE 1
2795 #define COMBINING_AFTER 2
2796 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2797 int maybe_byte_combining = COMBINING_NO;
2798 int last_changed = 0;
2799 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2801 restart:
2803 validate_region (&start, &end);
2804 CHECK_NUMBER (fromchar);
2805 CHECK_NUMBER (tochar);
2807 if (multibyte_p)
2809 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2810 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2811 error ("Characters in `subst-char-in-region' have different byte-lengths");
2812 if (!ASCII_BYTE_P (*tostr))
2814 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2815 complete multibyte character, it may be combined with the
2816 after bytes. If it is in the range 0xA0..0xFF, it may be
2817 combined with the before and after bytes. */
2818 if (!CHAR_HEAD_P (*tostr))
2819 maybe_byte_combining = COMBINING_BOTH;
2820 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2821 maybe_byte_combining = COMBINING_AFTER;
2824 else
2826 len = 1;
2827 fromstr[0] = XFASTINT (fromchar);
2828 tostr[0] = XFASTINT (tochar);
2831 pos = XINT (start);
2832 pos_byte = CHAR_TO_BYTE (pos);
2833 stop = CHAR_TO_BYTE (XINT (end));
2834 end_byte = stop;
2836 /* If we don't want undo, turn off putting stuff on the list.
2837 That's faster than getting rid of things,
2838 and it prevents even the entry for a first change.
2839 Also inhibit locking the file. */
2840 if (!changed && !NILP (noundo))
2842 record_unwind_protect (subst_char_in_region_unwind,
2843 current_buffer->undo_list);
2844 current_buffer->undo_list = Qt;
2845 /* Don't do file-locking. */
2846 record_unwind_protect (subst_char_in_region_unwind_1,
2847 current_buffer->filename);
2848 current_buffer->filename = Qnil;
2851 if (pos_byte < GPT_BYTE)
2852 stop = min (stop, GPT_BYTE);
2853 while (1)
2855 int pos_byte_next = pos_byte;
2857 if (pos_byte >= stop)
2859 if (pos_byte >= end_byte) break;
2860 stop = end_byte;
2862 p = BYTE_POS_ADDR (pos_byte);
2863 if (multibyte_p)
2864 INC_POS (pos_byte_next);
2865 else
2866 ++pos_byte_next;
2867 if (pos_byte_next - pos_byte == len
2868 && p[0] == fromstr[0]
2869 && (len == 1
2870 || (p[1] == fromstr[1]
2871 && (len == 2 || (p[2] == fromstr[2]
2872 && (len == 3 || p[3] == fromstr[3]))))))
2874 if (changed < 0)
2875 /* We've already seen this and run the before-change-function;
2876 this time we only need to record the actual position. */
2877 changed = pos;
2878 else if (!changed)
2880 changed = -1;
2881 modify_region (current_buffer, pos, XINT (end), 0);
2883 if (! NILP (noundo))
2885 if (MODIFF - 1 == SAVE_MODIFF)
2886 SAVE_MODIFF++;
2887 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2888 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2891 /* The before-change-function may have moved the gap
2892 or even modified the buffer so we should start over. */
2893 goto restart;
2896 /* Take care of the case where the new character
2897 combines with neighboring bytes. */
2898 if (maybe_byte_combining
2899 && (maybe_byte_combining == COMBINING_AFTER
2900 ? (pos_byte_next < Z_BYTE
2901 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2902 : ((pos_byte_next < Z_BYTE
2903 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2904 || (pos_byte > BEG_BYTE
2905 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2907 Lisp_Object tem, string;
2909 struct gcpro gcpro1;
2911 tem = current_buffer->undo_list;
2912 GCPRO1 (tem);
2914 /* Make a multibyte string containing this single character. */
2915 string = make_multibyte_string (tostr, 1, len);
2916 /* replace_range is less efficient, because it moves the gap,
2917 but it handles combining correctly. */
2918 replace_range (pos, pos + 1, string,
2919 0, 0, 1);
2920 pos_byte_next = CHAR_TO_BYTE (pos);
2921 if (pos_byte_next > pos_byte)
2922 /* Before combining happened. We should not increment
2923 POS. So, to cancel the later increment of POS,
2924 decrease it now. */
2925 pos--;
2926 else
2927 INC_POS (pos_byte_next);
2929 if (! NILP (noundo))
2930 current_buffer->undo_list = tem;
2932 UNGCPRO;
2934 else
2936 if (NILP (noundo))
2937 record_change (pos, 1);
2938 for (i = 0; i < len; i++) *p++ = tostr[i];
2940 last_changed = pos + 1;
2942 pos_byte = pos_byte_next;
2943 pos++;
2946 if (changed > 0)
2948 signal_after_change (changed,
2949 last_changed - changed, last_changed - changed);
2950 update_compositions (changed, last_changed, CHECK_ALL);
2953 unbind_to (count, Qnil);
2954 return Qnil;
2958 static Lisp_Object check_translation P_ ((int, int, int, Lisp_Object));
2960 /* Helper function for Ftranslate_region_internal.
2962 Check if a character sequence at POS (POS_BYTE) matches an element
2963 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2964 element is found, return it. Otherwise return Qnil. */
2966 static Lisp_Object
2967 check_translation (pos, pos_byte, end, val)
2968 int pos, pos_byte, end;
2969 Lisp_Object val;
2971 int buf_size = 16, buf_used = 0;
2972 int *buf = alloca (sizeof (int) * buf_size);
2974 for (; CONSP (val); val = XCDR (val))
2976 Lisp_Object elt;
2977 int len, i;
2979 elt = XCAR (val);
2980 if (! CONSP (elt))
2981 continue;
2982 elt = XCAR (elt);
2983 if (! VECTORP (elt))
2984 continue;
2985 len = ASIZE (elt);
2986 if (len <= end - pos)
2988 for (i = 0; i < len; i++)
2990 if (buf_used <= i)
2992 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2993 int len;
2995 if (buf_used == buf_size)
2997 int *newbuf;
2999 buf_size += 16;
3000 newbuf = alloca (sizeof (int) * buf_size);
3001 memcpy (newbuf, buf, sizeof (int) * buf_used);
3002 buf = newbuf;
3004 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len);
3005 pos_byte += len;
3007 if (XINT (AREF (elt, i)) != buf[i])
3008 break;
3010 if (i == len)
3011 return XCAR (val);
3014 return Qnil;
3018 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3019 Stranslate_region_internal, 3, 3, 0,
3020 doc: /* Internal use only.
3021 From START to END, translate characters according to TABLE.
3022 TABLE is a string or a char-table; the Nth character in it is the
3023 mapping for the character with code N.
3024 It returns the number of characters changed. */)
3025 (start, end, table)
3026 Lisp_Object start;
3027 Lisp_Object end;
3028 register Lisp_Object table;
3030 register unsigned char *tt; /* Trans table. */
3031 register int nc; /* New character. */
3032 int cnt; /* Number of changes made. */
3033 int size; /* Size of translate table. */
3034 int pos, pos_byte, end_pos;
3035 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3036 int string_multibyte;
3037 Lisp_Object val;
3039 validate_region (&start, &end);
3040 if (CHAR_TABLE_P (table))
3042 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3043 error ("Not a translation table");
3044 size = MAX_CHAR;
3045 tt = NULL;
3047 else
3049 CHECK_STRING (table);
3051 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3052 table = string_make_unibyte (table);
3053 string_multibyte = SCHARS (table) < SBYTES (table);
3054 size = SBYTES (table);
3055 tt = SDATA (table);
3058 pos = XINT (start);
3059 pos_byte = CHAR_TO_BYTE (pos);
3060 end_pos = XINT (end);
3061 modify_region (current_buffer, pos, end_pos, 0);
3063 cnt = 0;
3064 for (; pos < end_pos; )
3066 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3067 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3068 int len, str_len;
3069 int oc;
3070 Lisp_Object val;
3072 if (multibyte)
3073 oc = STRING_CHAR_AND_LENGTH (p, len);
3074 else
3075 oc = *p, len = 1;
3076 if (oc < size)
3078 if (tt)
3080 /* Reload as signal_after_change in last iteration may GC. */
3081 tt = SDATA (table);
3082 if (string_multibyte)
3084 str = tt + string_char_to_byte (table, oc);
3085 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3087 else
3089 nc = tt[oc];
3090 if (! ASCII_BYTE_P (nc) && multibyte)
3092 str_len = BYTE8_STRING (nc, buf);
3093 str = buf;
3095 else
3097 str_len = 1;
3098 str = tt + oc;
3102 else
3104 int c;
3106 nc = oc;
3107 val = CHAR_TABLE_REF (table, oc);
3108 if (CHARACTERP (val)
3109 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3111 nc = c;
3112 str_len = CHAR_STRING (nc, buf);
3113 str = buf;
3115 else if (VECTORP (val) || (CONSP (val)))
3117 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3118 where TO is TO-CHAR or [TO-CHAR ...]. */
3119 nc = -1;
3123 if (nc != oc && nc >= 0)
3125 /* Simple one char to one char translation. */
3126 if (len != str_len)
3128 Lisp_Object string;
3130 /* This is less efficient, because it moves the gap,
3131 but it should handle multibyte characters correctly. */
3132 string = make_multibyte_string (str, 1, str_len);
3133 replace_range (pos, pos + 1, string, 1, 0, 1);
3134 len = str_len;
3136 else
3138 record_change (pos, 1);
3139 while (str_len-- > 0)
3140 *p++ = *str++;
3141 signal_after_change (pos, 1, 1);
3142 update_compositions (pos, pos + 1, CHECK_BORDER);
3144 ++cnt;
3146 else if (nc < 0)
3148 Lisp_Object string;
3150 if (CONSP (val))
3152 val = check_translation (pos, pos_byte, end_pos, val);
3153 if (NILP (val))
3155 pos_byte += len;
3156 pos++;
3157 continue;
3159 /* VAL is ([FROM-CHAR ...] . TO). */
3160 len = ASIZE (XCAR (val));
3161 val = XCDR (val);
3163 else
3164 len = 1;
3166 if (VECTORP (val))
3168 string = Fconcat (1, &val);
3170 else
3172 string = Fmake_string (make_number (1), val);
3174 replace_range (pos, pos + len, string, 1, 0, 1);
3175 pos_byte += SBYTES (string);
3176 pos += SCHARS (string);
3177 cnt += SCHARS (string);
3178 end_pos += SCHARS (string) - len;
3179 continue;
3182 pos_byte += len;
3183 pos++;
3186 return make_number (cnt);
3189 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3190 doc: /* Delete the text between point and mark.
3192 When called from a program, expects two arguments,
3193 positions (integers or markers) specifying the stretch to be deleted. */)
3194 (start, end)
3195 Lisp_Object start, end;
3197 validate_region (&start, &end);
3198 del_range (XINT (start), XINT (end));
3199 return Qnil;
3202 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3203 Sdelete_and_extract_region, 2, 2, 0,
3204 doc: /* Delete the text between START and END and return it. */)
3205 (start, end)
3206 Lisp_Object start, end;
3208 validate_region (&start, &end);
3209 if (XINT (start) == XINT (end))
3210 return empty_unibyte_string;
3211 return del_range_1 (XINT (start), XINT (end), 1, 1);
3214 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3215 doc: /* Remove restrictions (narrowing) from current buffer.
3216 This allows the buffer's full text to be seen and edited. */)
3219 if (BEG != BEGV || Z != ZV)
3220 current_buffer->clip_changed = 1;
3221 BEGV = BEG;
3222 BEGV_BYTE = BEG_BYTE;
3223 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3224 /* Changing the buffer bounds invalidates any recorded current column. */
3225 invalidate_current_column ();
3226 return Qnil;
3229 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3230 doc: /* Restrict editing in this buffer to the current region.
3231 The rest of the text becomes temporarily invisible and untouchable
3232 but is not deleted; if you save the buffer in a file, the invisible
3233 text is included in the file. \\[widen] makes all visible again.
3234 See also `save-restriction'.
3236 When calling from a program, pass two arguments; positions (integers
3237 or markers) bounding the text that should remain visible. */)
3238 (start, end)
3239 register Lisp_Object start, end;
3241 CHECK_NUMBER_COERCE_MARKER (start);
3242 CHECK_NUMBER_COERCE_MARKER (end);
3244 if (XINT (start) > XINT (end))
3246 Lisp_Object tem;
3247 tem = start; start = end; end = tem;
3250 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3251 args_out_of_range (start, end);
3253 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3254 current_buffer->clip_changed = 1;
3256 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3257 SET_BUF_ZV (current_buffer, XFASTINT (end));
3258 if (PT < XFASTINT (start))
3259 SET_PT (XFASTINT (start));
3260 if (PT > XFASTINT (end))
3261 SET_PT (XFASTINT (end));
3262 /* Changing the buffer bounds invalidates any recorded current column. */
3263 invalidate_current_column ();
3264 return Qnil;
3267 Lisp_Object
3268 save_restriction_save ()
3270 if (BEGV == BEG && ZV == Z)
3271 /* The common case that the buffer isn't narrowed.
3272 We return just the buffer object, which save_restriction_restore
3273 recognizes as meaning `no restriction'. */
3274 return Fcurrent_buffer ();
3275 else
3276 /* We have to save a restriction, so return a pair of markers, one
3277 for the beginning and one for the end. */
3279 Lisp_Object beg, end;
3281 beg = buildmark (BEGV, BEGV_BYTE);
3282 end = buildmark (ZV, ZV_BYTE);
3284 /* END must move forward if text is inserted at its exact location. */
3285 XMARKER(end)->insertion_type = 1;
3287 return Fcons (beg, end);
3291 Lisp_Object
3292 save_restriction_restore (data)
3293 Lisp_Object data;
3295 struct buffer *cur = NULL;
3296 struct buffer *buf = (CONSP (data)
3297 ? XMARKER (XCAR (data))->buffer
3298 : XBUFFER (data));
3300 if (buf && buf != current_buffer && !NILP (buf->pt_marker))
3301 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3302 is the case if it is or has an indirect buffer), then make
3303 sure it is current before we update BEGV, so
3304 set_buffer_internal takes care of managing those markers. */
3305 cur = current_buffer;
3306 set_buffer_internal (buf);
3309 if (CONSP (data))
3310 /* A pair of marks bounding a saved restriction. */
3312 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3313 struct Lisp_Marker *end = XMARKER (XCDR (data));
3314 eassert (buf == end->buffer);
3316 if (buf /* Verify marker still points to a buffer. */
3317 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3318 /* The restriction has changed from the saved one, so restore
3319 the saved restriction. */
3321 int pt = BUF_PT (buf);
3323 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3324 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3326 if (pt < beg->charpos || pt > end->charpos)
3327 /* The point is outside the new visible range, move it inside. */
3328 SET_BUF_PT_BOTH (buf,
3329 clip_to_bounds (beg->charpos, pt, end->charpos),
3330 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3331 end->bytepos));
3333 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3336 else
3337 /* A buffer, which means that there was no old restriction. */
3339 if (buf /* Verify marker still points to a buffer. */
3340 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3341 /* The buffer has been narrowed, get rid of the narrowing. */
3343 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3344 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3346 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3350 if (cur)
3351 set_buffer_internal (cur);
3353 return Qnil;
3356 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3357 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3358 The buffer's restrictions make parts of the beginning and end invisible.
3359 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3360 This special form, `save-restriction', saves the current buffer's restrictions
3361 when it is entered, and restores them when it is exited.
3362 So any `narrow-to-region' within BODY lasts only until the end of the form.
3363 The old restrictions settings are restored
3364 even in case of abnormal exit (throw or error).
3366 The value returned is the value of the last form in BODY.
3368 Note: if you are using both `save-excursion' and `save-restriction',
3369 use `save-excursion' outermost:
3370 (save-excursion (save-restriction ...))
3372 usage: (save-restriction &rest BODY) */)
3373 (body)
3374 Lisp_Object body;
3376 register Lisp_Object val;
3377 int count = SPECPDL_INDEX ();
3379 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3380 val = Fprogn (body);
3381 return unbind_to (count, val);
3384 /* Buffer for the most recent text displayed by Fmessage_box. */
3385 static char *message_text;
3387 /* Allocated length of that buffer. */
3388 static int message_length;
3390 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3391 doc: /* Display a message at the bottom of the screen.
3392 The message also goes into the `*Messages*' buffer.
3393 \(In keyboard macros, that's all it does.)
3394 Return the message.
3396 The first argument is a format control string, and the rest are data
3397 to be formatted under control of the string. See `format' for details.
3399 Note: Use (message "%s" VALUE) to print the value of expressions and
3400 variables to avoid accidentally interpreting `%' as format specifiers.
3402 If the first argument is nil or the empty string, the function clears
3403 any existing message; this lets the minibuffer contents show. See
3404 also `current-message'.
3406 usage: (message FORMAT-STRING &rest ARGS) */)
3407 (nargs, args)
3408 int nargs;
3409 Lisp_Object *args;
3411 if (NILP (args[0])
3412 || (STRINGP (args[0])
3413 && SBYTES (args[0]) == 0))
3415 message (0);
3416 return args[0];
3418 else
3420 register Lisp_Object val;
3421 val = Fformat (nargs, args);
3422 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3423 return val;
3427 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3428 doc: /* Display a message, in a dialog box if possible.
3429 If a dialog box is not available, use the echo area.
3430 The first argument is a format control string, and the rest are data
3431 to be formatted under control of the string. See `format' for details.
3433 If the first argument is nil or the empty string, clear any existing
3434 message; let the minibuffer contents show.
3436 usage: (message-box FORMAT-STRING &rest ARGS) */)
3437 (nargs, args)
3438 int nargs;
3439 Lisp_Object *args;
3441 if (NILP (args[0]))
3443 message (0);
3444 return Qnil;
3446 else
3448 register Lisp_Object val;
3449 val = Fformat (nargs, args);
3450 #ifdef HAVE_MENUS
3451 /* The MS-DOS frames support popup menus even though they are
3452 not FRAME_WINDOW_P. */
3453 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3454 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3456 Lisp_Object pane, menu, obj;
3457 struct gcpro gcpro1;
3458 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3459 GCPRO1 (pane);
3460 menu = Fcons (val, pane);
3461 obj = Fx_popup_dialog (Qt, menu, Qt);
3462 UNGCPRO;
3463 return val;
3465 #endif /* HAVE_MENUS */
3466 /* Copy the data so that it won't move when we GC. */
3467 if (! message_text)
3469 message_text = (char *)xmalloc (80);
3470 message_length = 80;
3472 if (SBYTES (val) > message_length)
3474 message_length = SBYTES (val);
3475 message_text = (char *)xrealloc (message_text, message_length);
3477 bcopy (SDATA (val), message_text, SBYTES (val));
3478 message2 (message_text, SBYTES (val),
3479 STRING_MULTIBYTE (val));
3480 return val;
3483 #ifdef HAVE_MENUS
3484 extern Lisp_Object last_nonmenu_event;
3485 #endif
3487 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3488 doc: /* Display a message in a dialog box or in the echo area.
3489 If this command was invoked with the mouse, use a dialog box if
3490 `use-dialog-box' is non-nil.
3491 Otherwise, use the echo area.
3492 The first argument is a format control string, and the rest are data
3493 to be formatted under control of the string. See `format' for details.
3495 If the first argument is nil or the empty string, clear any existing
3496 message; let the minibuffer contents show.
3498 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3499 (nargs, args)
3500 int nargs;
3501 Lisp_Object *args;
3503 #ifdef HAVE_MENUS
3504 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3505 && use_dialog_box)
3506 return Fmessage_box (nargs, args);
3507 #endif
3508 return Fmessage (nargs, args);
3511 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3512 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3515 return current_message ();
3519 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3520 doc: /* Return a copy of STRING with text properties added.
3521 First argument is the string to copy.
3522 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3523 properties to add to the result.
3524 usage: (propertize STRING &rest PROPERTIES) */)
3525 (nargs, args)
3526 int nargs;
3527 Lisp_Object *args;
3529 Lisp_Object properties, string;
3530 struct gcpro gcpro1, gcpro2;
3531 int i;
3533 /* Number of args must be odd. */
3534 if ((nargs & 1) == 0 || nargs < 1)
3535 error ("Wrong number of arguments");
3537 properties = string = Qnil;
3538 GCPRO2 (properties, string);
3540 /* First argument must be a string. */
3541 CHECK_STRING (args[0]);
3542 string = Fcopy_sequence (args[0]);
3544 for (i = 1; i < nargs; i += 2)
3545 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3547 Fadd_text_properties (make_number (0),
3548 make_number (SCHARS (string)),
3549 properties, string);
3550 RETURN_UNGCPRO (string);
3554 /* Number of bytes that STRING will occupy when put into the result.
3555 MULTIBYTE is nonzero if the result should be multibyte. */
3557 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3558 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3559 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3560 : SBYTES (STRING))
3562 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3563 doc: /* Format a string out of a format-string and arguments.
3564 The first argument is a format control string.
3565 The other arguments are substituted into it to make the result, a string.
3567 The format control string may contain %-sequences meaning to substitute
3568 the next available argument:
3570 %s means print a string argument. Actually, prints any object, with `princ'.
3571 %d means print as number in decimal (%o octal, %x hex).
3572 %X is like %x, but uses upper case.
3573 %e means print a number in exponential notation.
3574 %f means print a number in decimal-point notation.
3575 %g means print a number in exponential notation
3576 or decimal-point notation, whichever uses fewer characters.
3577 %c means print a number as a single character.
3578 %S means print any object as an s-expression (using `prin1').
3580 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3581 Use %% to put a single % into the output.
3583 A %-sequence may contain optional flag, width, and precision
3584 specifiers, as follows:
3586 %<flags><width><precision>character
3588 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3590 The + flag character inserts a + before any positive number, while a
3591 space inserts a space before any positive number; these flags only
3592 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3593 The # flag means to use an alternate display form for %o, %x, %X, %e,
3594 %f, and %g sequences. The - and 0 flags affect the width specifier,
3595 as described below.
3597 The width specifier supplies a lower limit for the length of the
3598 printed representation. The padding, if any, normally goes on the
3599 left, but it goes on the right if the - flag is present. The padding
3600 character is normally a space, but it is 0 if the 0 flag is present.
3601 The - flag takes precedence over the 0 flag.
3603 For %e, %f, and %g sequences, the number after the "." in the
3604 precision specifier says how many decimal places to show; if zero, the
3605 decimal point itself is omitted. For %s and %S, the precision
3606 specifier truncates the string to the given width.
3608 usage: (format STRING &rest OBJECTS) */)
3609 (nargs, args)
3610 int nargs;
3611 register Lisp_Object *args;
3613 register int n; /* The number of the next arg to substitute */
3614 register int total; /* An estimate of the final length */
3615 char *buf, *p;
3616 register unsigned char *format, *end, *format_start;
3617 int nchars;
3618 /* Nonzero if the output should be a multibyte string,
3619 which is true if any of the inputs is one. */
3620 int multibyte = 0;
3621 /* When we make a multibyte string, we must pay attention to the
3622 byte combining problem, i.e., a byte may be combined with a
3623 multibyte charcter of the previous string. This flag tells if we
3624 must consider such a situation or not. */
3625 int maybe_combine_byte;
3626 unsigned char *this_format;
3627 /* Precision for each spec, or -1, a flag value meaning no precision
3628 was given in that spec. Element 0, corresonding to the format
3629 string itself, will not be used. Element NARGS, corresponding to
3630 no argument, *will* be assigned to in the case that a `%' and `.'
3631 occur after the final format specifier. */
3632 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
3633 int longest_format;
3634 Lisp_Object val;
3635 int arg_intervals = 0;
3636 USE_SAFE_ALLOCA;
3638 /* discarded[I] is 1 if byte I of the format
3639 string was not copied into the output.
3640 It is 2 if byte I was not the first byte of its character. */
3641 char *discarded = 0;
3643 /* Each element records, for one argument,
3644 the start and end bytepos in the output string,
3645 and whether the argument is a string with intervals.
3646 info[0] is unused. Unused elements have -1 for start. */
3647 struct info
3649 int start, end, intervals;
3650 } *info = 0;
3652 /* It should not be necessary to GCPRO ARGS, because
3653 the caller in the interpreter should take care of that. */
3655 /* Try to determine whether the result should be multibyte.
3656 This is not always right; sometimes the result needs to be multibyte
3657 because of an object that we will pass through prin1,
3658 and in that case, we won't know it here. */
3659 for (n = 0; n < nargs; n++)
3661 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3662 multibyte = 1;
3663 /* Piggyback on this loop to initialize precision[N]. */
3664 precision[n] = -1;
3666 precision[nargs] = -1;
3668 CHECK_STRING (args[0]);
3669 /* We may have to change "%S" to "%s". */
3670 args[0] = Fcopy_sequence (args[0]);
3672 /* GC should never happen here, so abort if it does. */
3673 abort_on_gc++;
3675 /* If we start out planning a unibyte result,
3676 then discover it has to be multibyte, we jump back to retry.
3677 That can only happen from the first large while loop below. */
3678 retry:
3680 format = SDATA (args[0]);
3681 format_start = format;
3682 end = format + SBYTES (args[0]);
3683 longest_format = 0;
3685 /* Make room in result for all the non-%-codes in the control string. */
3686 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3688 /* Allocate the info and discarded tables. */
3690 int nbytes = (nargs+1) * sizeof *info;
3691 int i;
3692 if (!info)
3693 info = (struct info *) alloca (nbytes);
3694 bzero (info, nbytes);
3695 for (i = 0; i <= nargs; i++)
3696 info[i].start = -1;
3697 if (!discarded)
3698 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3699 bzero (discarded, SBYTES (args[0]));
3702 /* Add to TOTAL enough space to hold the converted arguments. */
3704 n = 0;
3705 while (format != end)
3706 if (*format++ == '%')
3708 int thissize = 0;
3709 int actual_width = 0;
3710 unsigned char *this_format_start = format - 1;
3711 int field_width = 0;
3713 /* General format specifications look like
3715 '%' [flags] [field-width] [precision] format
3717 where
3719 flags ::= [-+ #0]+
3720 field-width ::= [0-9]+
3721 precision ::= '.' [0-9]*
3723 If a field-width is specified, it specifies to which width
3724 the output should be padded with blanks, if the output
3725 string is shorter than field-width.
3727 If precision is specified, it specifies the number of
3728 digits to print after the '.' for floats, or the max.
3729 number of chars to print from a string. */
3731 while (format != end
3732 && (*format == '-' || *format == '0' || *format == '#'
3733 || * format == ' ' || *format == '+'))
3734 ++format;
3736 if (*format >= '0' && *format <= '9')
3738 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3739 field_width = 10 * field_width + *format - '0';
3742 /* N is not incremented for another few lines below, so refer to
3743 element N+1 (which might be precision[NARGS]). */
3744 if (*format == '.')
3746 ++format;
3747 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3748 precision[n+1] = 10 * precision[n+1] + *format - '0';
3751 /* Extra +1 for 'l' that we may need to insert into the
3752 format. */
3753 if (format - this_format_start + 2 > longest_format)
3754 longest_format = format - this_format_start + 2;
3756 if (format == end)
3757 error ("Format string ends in middle of format specifier");
3758 if (*format == '%')
3759 format++;
3760 else if (++n >= nargs)
3761 error ("Not enough arguments for format string");
3762 else if (*format == 'S')
3764 /* For `S', prin1 the argument and then treat like a string. */
3765 register Lisp_Object tem;
3766 tem = Fprin1_to_string (args[n], Qnil);
3767 if (STRING_MULTIBYTE (tem) && ! multibyte)
3769 multibyte = 1;
3770 goto retry;
3772 args[n] = tem;
3773 /* If we restart the loop, we should not come here again
3774 because args[n] is now a string and calling
3775 Fprin1_to_string on it produces superflous double
3776 quotes. So, change "%S" to "%s" now. */
3777 *format = 's';
3778 goto string;
3780 else if (SYMBOLP (args[n]))
3782 args[n] = SYMBOL_NAME (args[n]);
3783 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3785 multibyte = 1;
3786 goto retry;
3788 goto string;
3790 else if (STRINGP (args[n]))
3792 string:
3793 if (*format != 's' && *format != 'S')
3794 error ("Format specifier doesn't match argument type");
3795 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3796 to be as large as is calculated here. Easy check for
3797 the case PRECISION = 0. */
3798 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3799 /* The precision also constrains how much of the argument
3800 string will finally appear (Bug#5710). */
3801 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3802 if (precision[n] != -1)
3803 actual_width = min(actual_width,precision[n]);
3805 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3806 else if (INTEGERP (args[n]) && *format != 's')
3808 /* The following loop assumes the Lisp type indicates
3809 the proper way to pass the argument.
3810 So make sure we have a flonum if the argument should
3811 be a double. */
3812 if (*format == 'e' || *format == 'f' || *format == 'g')
3813 args[n] = Ffloat (args[n]);
3814 else
3815 if (*format != 'd' && *format != 'o' && *format != 'x'
3816 && *format != 'i' && *format != 'X' && *format != 'c')
3817 error ("Invalid format operation %%%c", *format);
3819 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3820 if (*format == 'c')
3822 if (! ASCII_CHAR_P (XINT (args[n]))
3823 /* Note: No one can remeber why we have to treat
3824 the character 0 as a multibyte character here.
3825 But, until it causes a real problem, let's
3826 don't change it. */
3827 || XINT (args[n]) == 0)
3829 if (! multibyte)
3831 multibyte = 1;
3832 goto retry;
3834 args[n] = Fchar_to_string (args[n]);
3835 thissize = SBYTES (args[n]);
3837 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3839 args[n]
3840 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3841 thissize = SBYTES (args[n]);
3845 else if (FLOATP (args[n]) && *format != 's')
3847 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3849 if (*format != 'd' && *format != 'o' && *format != 'x'
3850 && *format != 'i' && *format != 'X' && *format != 'c')
3851 error ("Invalid format operation %%%c", *format);
3852 /* This fails unnecessarily if args[n] is bigger than
3853 most-positive-fixnum but smaller than MAXINT.
3854 These cases are important because we sometimes use floats
3855 to represent such integer values (typically such values
3856 come from UIDs or PIDs). */
3857 /* args[n] = Ftruncate (args[n], Qnil); */
3860 /* Note that we're using sprintf to print floats,
3861 so we have to take into account what that function
3862 prints. */
3863 /* Filter out flag value of -1. */
3864 thissize = (MAX_10_EXP + 100
3865 + (precision[n] > 0 ? precision[n] : 0));
3867 else
3869 /* Anything but a string, convert to a string using princ. */
3870 register Lisp_Object tem;
3871 tem = Fprin1_to_string (args[n], Qt);
3872 if (STRING_MULTIBYTE (tem) && ! multibyte)
3874 multibyte = 1;
3875 goto retry;
3877 args[n] = tem;
3878 goto string;
3881 thissize += max (0, field_width - actual_width);
3882 total += thissize + 4;
3885 abort_on_gc--;
3887 /* Now we can no longer jump to retry.
3888 TOTAL and LONGEST_FORMAT are known for certain. */
3890 this_format = (unsigned char *) alloca (longest_format + 1);
3892 /* Allocate the space for the result.
3893 Note that TOTAL is an overestimate. */
3894 SAFE_ALLOCA (buf, char *, total);
3896 p = buf;
3897 nchars = 0;
3898 n = 0;
3900 /* Scan the format and store result in BUF. */
3901 format = SDATA (args[0]);
3902 format_start = format;
3903 end = format + SBYTES (args[0]);
3904 maybe_combine_byte = 0;
3905 while (format != end)
3907 if (*format == '%')
3909 int minlen;
3910 int negative = 0;
3911 unsigned char *this_format_start = format;
3913 discarded[format - format_start] = 1;
3914 format++;
3916 while (index("-+0# ", *format))
3918 if (*format == '-')
3920 negative = 1;
3922 discarded[format - format_start] = 1;
3923 ++format;
3926 minlen = atoi (format);
3928 while ((*format >= '0' && *format <= '9') || *format == '.')
3930 discarded[format - format_start] = 1;
3931 format++;
3934 if (*format++ == '%')
3936 *p++ = '%';
3937 nchars++;
3938 continue;
3941 ++n;
3943 discarded[format - format_start - 1] = 1;
3944 info[n].start = nchars;
3946 if (STRINGP (args[n]))
3948 /* handle case (precision[n] >= 0) */
3950 int width, padding;
3951 int nbytes, start, end;
3952 int nchars_string;
3954 /* lisp_string_width ignores a precision of 0, but GNU
3955 libc functions print 0 characters when the precision
3956 is 0. Imitate libc behavior here. Changing
3957 lisp_string_width is the right thing, and will be
3958 done, but meanwhile we work with it. */
3960 if (precision[n] == 0)
3961 width = nchars_string = nbytes = 0;
3962 else if (precision[n] > 0)
3963 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3964 else
3965 { /* no precision spec given for this argument */
3966 width = lisp_string_width (args[n], -1, NULL, NULL);
3967 nbytes = SBYTES (args[n]);
3968 nchars_string = SCHARS (args[n]);
3971 /* If spec requires it, pad on right with spaces. */
3972 padding = minlen - width;
3973 if (! negative)
3974 while (padding-- > 0)
3976 *p++ = ' ';
3977 ++nchars;
3980 info[n].start = start = nchars;
3981 nchars += nchars_string;
3982 end = nchars;
3984 if (p > buf
3985 && multibyte
3986 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3987 && STRING_MULTIBYTE (args[n])
3988 && !CHAR_HEAD_P (SREF (args[n], 0)))
3989 maybe_combine_byte = 1;
3991 p += copy_text (SDATA (args[n]), p,
3992 nbytes,
3993 STRING_MULTIBYTE (args[n]), multibyte);
3995 info[n].end = nchars;
3997 if (negative)
3998 while (padding-- > 0)
4000 *p++ = ' ';
4001 nchars++;
4004 /* If this argument has text properties, record where
4005 in the result string it appears. */
4006 if (STRING_INTERVALS (args[n]))
4007 info[n].intervals = arg_intervals = 1;
4009 else if (INTEGERP (args[n]) || FLOATP (args[n]))
4011 int this_nchars;
4013 bcopy (this_format_start, this_format,
4014 format - this_format_start);
4015 this_format[format - this_format_start] = 0;
4017 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
4018 sprintf (p, this_format, XFLOAT_DATA (args[n]));
4019 else
4021 if (sizeof (EMACS_INT) > sizeof (int)
4022 && format[-1] != 'c')
4024 /* Insert 'l' before format spec. */
4025 this_format[format - this_format_start]
4026 = this_format[format - this_format_start - 1];
4027 this_format[format - this_format_start - 1] = 'l';
4028 this_format[format - this_format_start + 1] = 0;
4031 if (INTEGERP (args[n]))
4033 if (format[-1] == 'c')
4034 sprintf (p, this_format, (int) XINT (args[n]));
4035 else if (format[-1] == 'd')
4036 sprintf (p, this_format, XINT (args[n]));
4037 /* Don't sign-extend for octal or hex printing. */
4038 else
4039 sprintf (p, this_format, XUINT (args[n]));
4041 else if (format[-1] == 'c')
4042 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4043 else if (format[-1] == 'd')
4044 /* Maybe we should use "%1.0f" instead so it also works
4045 for values larger than MAXINT. */
4046 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4047 else
4048 /* Don't sign-extend for octal or hex printing. */
4049 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4052 if (p > buf
4053 && multibyte
4054 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4055 && !CHAR_HEAD_P (*((unsigned char *) p)))
4056 maybe_combine_byte = 1;
4057 this_nchars = strlen (p);
4058 if (multibyte)
4059 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
4060 else
4061 p += this_nchars;
4062 nchars += this_nchars;
4063 info[n].end = nchars;
4067 else if (STRING_MULTIBYTE (args[0]))
4069 /* Copy a whole multibyte character. */
4070 if (p > buf
4071 && multibyte
4072 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4073 && !CHAR_HEAD_P (*format))
4074 maybe_combine_byte = 1;
4075 *p++ = *format++;
4076 while (! CHAR_HEAD_P (*format))
4078 discarded[format - format_start] = 2;
4079 *p++ = *format++;
4081 nchars++;
4083 else if (multibyte)
4085 /* Convert a single-byte character to multibyte. */
4086 int len = copy_text (format, p, 1, 0, 1);
4088 p += len;
4089 format++;
4090 nchars++;
4092 else
4093 *p++ = *format++, nchars++;
4096 if (p > buf + total)
4097 abort ();
4099 if (maybe_combine_byte)
4100 nchars = multibyte_chars_in_text (buf, p - buf);
4101 val = make_specified_string (buf, nchars, p - buf, multibyte);
4103 /* If we allocated BUF with malloc, free it too. */
4104 SAFE_FREE ();
4106 /* If the format string has text properties, or any of the string
4107 arguments has text properties, set up text properties of the
4108 result string. */
4110 if (STRING_INTERVALS (args[0]) || arg_intervals)
4112 Lisp_Object len, new_len, props;
4113 struct gcpro gcpro1;
4115 /* Add text properties from the format string. */
4116 len = make_number (SCHARS (args[0]));
4117 props = text_property_list (args[0], make_number (0), len, Qnil);
4118 GCPRO1 (props);
4120 if (CONSP (props))
4122 int bytepos = 0, position = 0, translated = 0, argn = 1;
4123 Lisp_Object list;
4125 /* Adjust the bounds of each text property
4126 to the proper start and end in the output string. */
4128 /* Put the positions in PROPS in increasing order, so that
4129 we can do (effectively) one scan through the position
4130 space of the format string. */
4131 props = Fnreverse (props);
4133 /* BYTEPOS is the byte position in the format string,
4134 POSITION is the untranslated char position in it,
4135 TRANSLATED is the translated char position in BUF,
4136 and ARGN is the number of the next arg we will come to. */
4137 for (list = props; CONSP (list); list = XCDR (list))
4139 Lisp_Object item;
4140 int pos;
4142 item = XCAR (list);
4144 /* First adjust the property start position. */
4145 pos = XINT (XCAR (item));
4147 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4148 up to this position. */
4149 for (; position < pos; bytepos++)
4151 if (! discarded[bytepos])
4152 position++, translated++;
4153 else if (discarded[bytepos] == 1)
4155 position++;
4156 if (translated == info[argn].start)
4158 translated += info[argn].end - info[argn].start;
4159 argn++;
4164 XSETCAR (item, make_number (translated));
4166 /* Likewise adjust the property end position. */
4167 pos = XINT (XCAR (XCDR (item)));
4169 for (; position < pos; bytepos++)
4171 if (! discarded[bytepos])
4172 position++, translated++;
4173 else if (discarded[bytepos] == 1)
4175 position++;
4176 if (translated == info[argn].start)
4178 translated += info[argn].end - info[argn].start;
4179 argn++;
4184 XSETCAR (XCDR (item), make_number (translated));
4187 add_text_properties_from_list (val, props, make_number (0));
4190 /* Add text properties from arguments. */
4191 if (arg_intervals)
4192 for (n = 1; n < nargs; ++n)
4193 if (info[n].intervals)
4195 len = make_number (SCHARS (args[n]));
4196 new_len = make_number (info[n].end - info[n].start);
4197 props = text_property_list (args[n], make_number (0), len, Qnil);
4198 props = extend_property_ranges (props, new_len);
4199 /* If successive arguments have properties, be sure that
4200 the value of `composition' property be the copy. */
4201 if (n > 1 && info[n - 1].end)
4202 make_composition_value_copy (props);
4203 add_text_properties_from_list (val, props,
4204 make_number (info[n].start));
4207 UNGCPRO;
4210 return val;
4213 Lisp_Object
4214 format2 (string1, arg0, arg1)
4215 char *string1;
4216 Lisp_Object arg0, arg1;
4218 Lisp_Object args[3];
4219 args[0] = build_string (string1);
4220 args[1] = arg0;
4221 args[2] = arg1;
4222 return Fformat (3, args);
4225 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4226 doc: /* Return t if two characters match, optionally ignoring case.
4227 Both arguments must be characters (i.e. integers).
4228 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4229 (c1, c2)
4230 register Lisp_Object c1, c2;
4232 int i1, i2;
4233 /* Check they're chars, not just integers, otherwise we could get array
4234 bounds violations in DOWNCASE. */
4235 CHECK_CHARACTER (c1);
4236 CHECK_CHARACTER (c2);
4238 if (XINT (c1) == XINT (c2))
4239 return Qt;
4240 if (NILP (current_buffer->case_fold_search))
4241 return Qnil;
4243 /* Do these in separate statements,
4244 then compare the variables.
4245 because of the way DOWNCASE uses temp variables. */
4246 i1 = XFASTINT (c1);
4247 if (NILP (current_buffer->enable_multibyte_characters)
4248 && ! ASCII_CHAR_P (i1))
4250 MAKE_CHAR_MULTIBYTE (i1);
4252 i2 = XFASTINT (c2);
4253 if (NILP (current_buffer->enable_multibyte_characters)
4254 && ! ASCII_CHAR_P (i2))
4256 MAKE_CHAR_MULTIBYTE (i2);
4258 i1 = DOWNCASE (i1);
4259 i2 = DOWNCASE (i2);
4260 return (i1 == i2 ? Qt : Qnil);
4263 /* Transpose the markers in two regions of the current buffer, and
4264 adjust the ones between them if necessary (i.e.: if the regions
4265 differ in size).
4267 START1, END1 are the character positions of the first region.
4268 START1_BYTE, END1_BYTE are the byte positions.
4269 START2, END2 are the character positions of the second region.
4270 START2_BYTE, END2_BYTE are the byte positions.
4272 Traverses the entire marker list of the buffer to do so, adding an
4273 appropriate amount to some, subtracting from some, and leaving the
4274 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4276 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4278 static void
4279 transpose_markers (start1, end1, start2, end2,
4280 start1_byte, end1_byte, start2_byte, end2_byte)
4281 register int start1, end1, start2, end2;
4282 register int start1_byte, end1_byte, start2_byte, end2_byte;
4284 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4285 register struct Lisp_Marker *marker;
4287 /* Update point as if it were a marker. */
4288 if (PT < start1)
4290 else if (PT < end1)
4291 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4292 PT_BYTE + (end2_byte - end1_byte));
4293 else if (PT < start2)
4294 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4295 (PT_BYTE + (end2_byte - start2_byte)
4296 - (end1_byte - start1_byte)));
4297 else if (PT < end2)
4298 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4299 PT_BYTE - (start2_byte - start1_byte));
4301 /* We used to adjust the endpoints here to account for the gap, but that
4302 isn't good enough. Even if we assume the caller has tried to move the
4303 gap out of our way, it might still be at start1 exactly, for example;
4304 and that places it `inside' the interval, for our purposes. The amount
4305 of adjustment is nontrivial if there's a `denormalized' marker whose
4306 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4307 the dirty work to Fmarker_position, below. */
4309 /* The difference between the region's lengths */
4310 diff = (end2 - start2) - (end1 - start1);
4311 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4313 /* For shifting each marker in a region by the length of the other
4314 region plus the distance between the regions. */
4315 amt1 = (end2 - start2) + (start2 - end1);
4316 amt2 = (end1 - start1) + (start2 - end1);
4317 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4318 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4320 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4322 mpos = marker->bytepos;
4323 if (mpos >= start1_byte && mpos < end2_byte)
4325 if (mpos < end1_byte)
4326 mpos += amt1_byte;
4327 else if (mpos < start2_byte)
4328 mpos += diff_byte;
4329 else
4330 mpos -= amt2_byte;
4331 marker->bytepos = mpos;
4333 mpos = marker->charpos;
4334 if (mpos >= start1 && mpos < end2)
4336 if (mpos < end1)
4337 mpos += amt1;
4338 else if (mpos < start2)
4339 mpos += diff;
4340 else
4341 mpos -= amt2;
4343 marker->charpos = mpos;
4347 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4348 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4349 The regions should not be overlapping, because the size of the buffer is
4350 never changed in a transposition.
4352 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4353 any markers that happen to be located in the regions.
4355 Transposing beyond buffer boundaries is an error. */)
4356 (startr1, endr1, startr2, endr2, leave_markers)
4357 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4359 register EMACS_INT start1, end1, start2, end2;
4360 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4361 EMACS_INT gap, len1, len_mid, len2;
4362 unsigned char *start1_addr, *start2_addr, *temp;
4364 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4365 Lisp_Object buf;
4367 XSETBUFFER (buf, current_buffer);
4368 cur_intv = BUF_INTERVALS (current_buffer);
4370 validate_region (&startr1, &endr1);
4371 validate_region (&startr2, &endr2);
4373 start1 = XFASTINT (startr1);
4374 end1 = XFASTINT (endr1);
4375 start2 = XFASTINT (startr2);
4376 end2 = XFASTINT (endr2);
4377 gap = GPT;
4379 /* Swap the regions if they're reversed. */
4380 if (start2 < end1)
4382 register int glumph = start1;
4383 start1 = start2;
4384 start2 = glumph;
4385 glumph = end1;
4386 end1 = end2;
4387 end2 = glumph;
4390 len1 = end1 - start1;
4391 len2 = end2 - start2;
4393 if (start2 < end1)
4394 error ("Transposed regions overlap");
4395 else if (start1 == end1 || start2 == end2)
4396 error ("Transposed region has length 0");
4398 /* The possibilities are:
4399 1. Adjacent (contiguous) regions, or separate but equal regions
4400 (no, really equal, in this case!), or
4401 2. Separate regions of unequal size.
4403 The worst case is usually No. 2. It means that (aside from
4404 potential need for getting the gap out of the way), there also
4405 needs to be a shifting of the text between the two regions. So
4406 if they are spread far apart, we are that much slower... sigh. */
4408 /* It must be pointed out that the really studly thing to do would
4409 be not to move the gap at all, but to leave it in place and work
4410 around it if necessary. This would be extremely efficient,
4411 especially considering that people are likely to do
4412 transpositions near where they are working interactively, which
4413 is exactly where the gap would be found. However, such code
4414 would be much harder to write and to read. So, if you are
4415 reading this comment and are feeling squirrely, by all means have
4416 a go! I just didn't feel like doing it, so I will simply move
4417 the gap the minimum distance to get it out of the way, and then
4418 deal with an unbroken array. */
4420 /* Make sure the gap won't interfere, by moving it out of the text
4421 we will operate on. */
4422 if (start1 < gap && gap < end2)
4424 if (gap - start1 < end2 - gap)
4425 move_gap (start1);
4426 else
4427 move_gap (end2);
4430 start1_byte = CHAR_TO_BYTE (start1);
4431 start2_byte = CHAR_TO_BYTE (start2);
4432 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4433 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4435 #ifdef BYTE_COMBINING_DEBUG
4436 if (end1 == start2)
4438 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4439 len2_byte, start1, start1_byte)
4440 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4441 len1_byte, end2, start2_byte + len2_byte)
4442 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4443 len1_byte, end2, start2_byte + len2_byte))
4444 abort ();
4446 else
4448 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4449 len2_byte, start1, start1_byte)
4450 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4451 len1_byte, start2, start2_byte)
4452 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4453 len2_byte, end1, start1_byte + len1_byte)
4454 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4455 len1_byte, end2, start2_byte + len2_byte))
4456 abort ();
4458 #endif
4460 /* Hmmm... how about checking to see if the gap is large
4461 enough to use as the temporary storage? That would avoid an
4462 allocation... interesting. Later, don't fool with it now. */
4464 /* Working without memmove, for portability (sigh), so must be
4465 careful of overlapping subsections of the array... */
4467 if (end1 == start2) /* adjacent regions */
4469 modify_region (current_buffer, start1, end2, 0);
4470 record_change (start1, len1 + len2);
4472 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4473 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4474 /* Don't use Fset_text_properties: that can cause GC, which can
4475 clobber objects stored in the tmp_intervals. */
4476 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4477 if (!NULL_INTERVAL_P (tmp_interval3))
4478 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4480 /* First region smaller than second. */
4481 if (len1_byte < len2_byte)
4483 USE_SAFE_ALLOCA;
4485 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4487 /* Don't precompute these addresses. We have to compute them
4488 at the last minute, because the relocating allocator might
4489 have moved the buffer around during the xmalloc. */
4490 start1_addr = BYTE_POS_ADDR (start1_byte);
4491 start2_addr = BYTE_POS_ADDR (start2_byte);
4493 bcopy (start2_addr, temp, len2_byte);
4494 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4495 bcopy (temp, start1_addr, len2_byte);
4496 SAFE_FREE ();
4498 else
4499 /* First region not smaller than second. */
4501 USE_SAFE_ALLOCA;
4503 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4504 start1_addr = BYTE_POS_ADDR (start1_byte);
4505 start2_addr = BYTE_POS_ADDR (start2_byte);
4506 bcopy (start1_addr, temp, len1_byte);
4507 bcopy (start2_addr, start1_addr, len2_byte);
4508 bcopy (temp, start1_addr + len2_byte, len1_byte);
4509 SAFE_FREE ();
4511 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4512 len1, current_buffer, 0);
4513 graft_intervals_into_buffer (tmp_interval2, start1,
4514 len2, current_buffer, 0);
4515 update_compositions (start1, start1 + len2, CHECK_BORDER);
4516 update_compositions (start1 + len2, end2, CHECK_TAIL);
4518 /* Non-adjacent regions, because end1 != start2, bleagh... */
4519 else
4521 len_mid = start2_byte - (start1_byte + len1_byte);
4523 if (len1_byte == len2_byte)
4524 /* Regions are same size, though, how nice. */
4526 USE_SAFE_ALLOCA;
4528 modify_region (current_buffer, start1, end1, 0);
4529 modify_region (current_buffer, start2, end2, 0);
4530 record_change (start1, len1);
4531 record_change (start2, len2);
4532 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4533 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4535 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4536 if (!NULL_INTERVAL_P (tmp_interval3))
4537 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4539 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4540 if (!NULL_INTERVAL_P (tmp_interval3))
4541 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4543 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4544 start1_addr = BYTE_POS_ADDR (start1_byte);
4545 start2_addr = BYTE_POS_ADDR (start2_byte);
4546 bcopy (start1_addr, temp, len1_byte);
4547 bcopy (start2_addr, start1_addr, len2_byte);
4548 bcopy (temp, start2_addr, len1_byte);
4549 SAFE_FREE ();
4551 graft_intervals_into_buffer (tmp_interval1, start2,
4552 len1, current_buffer, 0);
4553 graft_intervals_into_buffer (tmp_interval2, start1,
4554 len2, current_buffer, 0);
4557 else if (len1_byte < len2_byte) /* Second region larger than first */
4558 /* Non-adjacent & unequal size, area between must also be shifted. */
4560 USE_SAFE_ALLOCA;
4562 modify_region (current_buffer, start1, end2, 0);
4563 record_change (start1, (end2 - start1));
4564 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4565 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4566 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4568 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4569 if (!NULL_INTERVAL_P (tmp_interval3))
4570 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4572 /* holds region 2 */
4573 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4574 start1_addr = BYTE_POS_ADDR (start1_byte);
4575 start2_addr = BYTE_POS_ADDR (start2_byte);
4576 bcopy (start2_addr, temp, len2_byte);
4577 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4578 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4579 bcopy (temp, start1_addr, len2_byte);
4580 SAFE_FREE ();
4582 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4583 len1, current_buffer, 0);
4584 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4585 len_mid, current_buffer, 0);
4586 graft_intervals_into_buffer (tmp_interval2, start1,
4587 len2, current_buffer, 0);
4589 else
4590 /* Second region smaller than first. */
4592 USE_SAFE_ALLOCA;
4594 record_change (start1, (end2 - start1));
4595 modify_region (current_buffer, start1, end2, 0);
4597 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4598 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4599 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4601 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4602 if (!NULL_INTERVAL_P (tmp_interval3))
4603 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4605 /* holds region 1 */
4606 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4607 start1_addr = BYTE_POS_ADDR (start1_byte);
4608 start2_addr = BYTE_POS_ADDR (start2_byte);
4609 bcopy (start1_addr, temp, len1_byte);
4610 bcopy (start2_addr, start1_addr, len2_byte);
4611 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4612 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
4613 SAFE_FREE ();
4615 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4616 len1, current_buffer, 0);
4617 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4618 len_mid, current_buffer, 0);
4619 graft_intervals_into_buffer (tmp_interval2, start1,
4620 len2, current_buffer, 0);
4623 update_compositions (start1, start1 + len2, CHECK_BORDER);
4624 update_compositions (end2 - len1, end2, CHECK_BORDER);
4627 /* When doing multiple transpositions, it might be nice
4628 to optimize this. Perhaps the markers in any one buffer
4629 should be organized in some sorted data tree. */
4630 if (NILP (leave_markers))
4632 transpose_markers (start1, end1, start2, end2,
4633 start1_byte, start1_byte + len1_byte,
4634 start2_byte, start2_byte + len2_byte);
4635 fix_start_end_in_overlays (start1, end2);
4638 signal_after_change (start1, end2 - start1, end2 - start1);
4639 return Qnil;
4643 void
4644 syms_of_editfns ()
4646 environbuf = 0;
4647 initial_tz = 0;
4649 Qbuffer_access_fontify_functions
4650 = intern_c_string ("buffer-access-fontify-functions");
4651 staticpro (&Qbuffer_access_fontify_functions);
4653 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4654 doc: /* Non-nil means text motion commands don't notice fields. */);
4655 Vinhibit_field_text_motion = Qnil;
4657 DEFVAR_LISP ("buffer-access-fontify-functions",
4658 &Vbuffer_access_fontify_functions,
4659 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4660 Each function is called with two arguments which specify the range
4661 of the buffer being accessed. */);
4662 Vbuffer_access_fontify_functions = Qnil;
4665 Lisp_Object obuf;
4666 extern Lisp_Object Vprin1_to_string_buffer;
4667 obuf = Fcurrent_buffer ();
4668 /* Do this here, because init_buffer_once is too early--it won't work. */
4669 Fset_buffer (Vprin1_to_string_buffer);
4670 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4671 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4672 Qnil);
4673 Fset_buffer (obuf);
4676 DEFVAR_LISP ("buffer-access-fontified-property",
4677 &Vbuffer_access_fontified_property,
4678 doc: /* Property which (if non-nil) indicates text has been fontified.
4679 `buffer-substring' need not call the `buffer-access-fontify-functions'
4680 functions if all the text being accessed has this property. */);
4681 Vbuffer_access_fontified_property = Qnil;
4683 DEFVAR_LISP ("system-name", &Vsystem_name,
4684 doc: /* The host name of the machine Emacs is running on. */);
4686 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4687 doc: /* The full name of the user logged in. */);
4689 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4690 doc: /* The user's name, taken from environment variables if possible. */);
4692 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4693 doc: /* The user's name, based upon the real uid only. */);
4695 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4696 doc: /* The release of the operating system Emacs is running on. */);
4698 defsubr (&Spropertize);
4699 defsubr (&Schar_equal);
4700 defsubr (&Sgoto_char);
4701 defsubr (&Sstring_to_char);
4702 defsubr (&Schar_to_string);
4703 defsubr (&Sbyte_to_string);
4704 defsubr (&Sbuffer_substring);
4705 defsubr (&Sbuffer_substring_no_properties);
4706 defsubr (&Sbuffer_string);
4708 defsubr (&Spoint_marker);
4709 defsubr (&Smark_marker);
4710 defsubr (&Spoint);
4711 defsubr (&Sregion_beginning);
4712 defsubr (&Sregion_end);
4714 staticpro (&Qfield);
4715 Qfield = intern_c_string ("field");
4716 staticpro (&Qboundary);
4717 Qboundary = intern_c_string ("boundary");
4718 defsubr (&Sfield_beginning);
4719 defsubr (&Sfield_end);
4720 defsubr (&Sfield_string);
4721 defsubr (&Sfield_string_no_properties);
4722 defsubr (&Sdelete_field);
4723 defsubr (&Sconstrain_to_field);
4725 defsubr (&Sline_beginning_position);
4726 defsubr (&Sline_end_position);
4728 /* defsubr (&Smark); */
4729 /* defsubr (&Sset_mark); */
4730 defsubr (&Ssave_excursion);
4731 defsubr (&Ssave_current_buffer);
4733 defsubr (&Sbufsize);
4734 defsubr (&Spoint_max);
4735 defsubr (&Spoint_min);
4736 defsubr (&Spoint_min_marker);
4737 defsubr (&Spoint_max_marker);
4738 defsubr (&Sgap_position);
4739 defsubr (&Sgap_size);
4740 defsubr (&Sposition_bytes);
4741 defsubr (&Sbyte_to_position);
4743 defsubr (&Sbobp);
4744 defsubr (&Seobp);
4745 defsubr (&Sbolp);
4746 defsubr (&Seolp);
4747 defsubr (&Sfollowing_char);
4748 defsubr (&Sprevious_char);
4749 defsubr (&Schar_after);
4750 defsubr (&Schar_before);
4751 defsubr (&Sinsert);
4752 defsubr (&Sinsert_before_markers);
4753 defsubr (&Sinsert_and_inherit);
4754 defsubr (&Sinsert_and_inherit_before_markers);
4755 defsubr (&Sinsert_char);
4756 defsubr (&Sinsert_byte);
4758 defsubr (&Suser_login_name);
4759 defsubr (&Suser_real_login_name);
4760 defsubr (&Suser_uid);
4761 defsubr (&Suser_real_uid);
4762 defsubr (&Suser_full_name);
4763 defsubr (&Semacs_pid);
4764 defsubr (&Scurrent_time);
4765 defsubr (&Sget_internal_run_time);
4766 defsubr (&Sformat_time_string);
4767 defsubr (&Sfloat_time);
4768 defsubr (&Sdecode_time);
4769 defsubr (&Sencode_time);
4770 defsubr (&Scurrent_time_string);
4771 defsubr (&Scurrent_time_zone);
4772 defsubr (&Sset_time_zone_rule);
4773 defsubr (&Ssystem_name);
4774 defsubr (&Smessage);
4775 defsubr (&Smessage_box);
4776 defsubr (&Smessage_or_box);
4777 defsubr (&Scurrent_message);
4778 defsubr (&Sformat);
4780 defsubr (&Sinsert_buffer_substring);
4781 defsubr (&Scompare_buffer_substrings);
4782 defsubr (&Ssubst_char_in_region);
4783 defsubr (&Stranslate_region_internal);
4784 defsubr (&Sdelete_region);
4785 defsubr (&Sdelete_and_extract_region);
4786 defsubr (&Swiden);
4787 defsubr (&Snarrow_to_region);
4788 defsubr (&Ssave_restriction);
4789 defsubr (&Stranspose_regions);
4792 /* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4793 (do not change this comment) */