* doc/emacs/display.texi (Auto Scrolling): Fix scroll-up/scroll-down confusion.
[emacs.git] / src / editfns.c
bloba751d6df3b2e83262fd8dbfa7ce6cce54bdbb7a1
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, 2011 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 /* Changing the buffer bounds invalidates any recorded current column. */
3351 invalidate_current_column ();
3353 if (cur)
3354 set_buffer_internal (cur);
3356 return Qnil;
3359 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3360 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3361 The buffer's restrictions make parts of the beginning and end invisible.
3362 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3363 This special form, `save-restriction', saves the current buffer's restrictions
3364 when it is entered, and restores them when it is exited.
3365 So any `narrow-to-region' within BODY lasts only until the end of the form.
3366 The old restrictions settings are restored
3367 even in case of abnormal exit (throw or error).
3369 The value returned is the value of the last form in BODY.
3371 Note: if you are using both `save-excursion' and `save-restriction',
3372 use `save-excursion' outermost:
3373 (save-excursion (save-restriction ...))
3375 usage: (save-restriction &rest BODY) */)
3376 (body)
3377 Lisp_Object body;
3379 register Lisp_Object val;
3380 int count = SPECPDL_INDEX ();
3382 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3383 val = Fprogn (body);
3384 return unbind_to (count, val);
3387 /* Buffer for the most recent text displayed by Fmessage_box. */
3388 static char *message_text;
3390 /* Allocated length of that buffer. */
3391 static int message_length;
3393 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3394 doc: /* Display a message at the bottom of the screen.
3395 The message also goes into the `*Messages*' buffer.
3396 \(In keyboard macros, that's all it does.)
3397 Return the message.
3399 The first argument is a format control string, and the rest are data
3400 to be formatted under control of the string. See `format' for details.
3402 Note: Use (message "%s" VALUE) to print the value of expressions and
3403 variables to avoid accidentally interpreting `%' as format specifiers.
3405 If the first argument is nil or the empty string, the function clears
3406 any existing message; this lets the minibuffer contents show. See
3407 also `current-message'.
3409 usage: (message FORMAT-STRING &rest ARGS) */)
3410 (nargs, args)
3411 int nargs;
3412 Lisp_Object *args;
3414 if (NILP (args[0])
3415 || (STRINGP (args[0])
3416 && SBYTES (args[0]) == 0))
3418 message (0);
3419 return args[0];
3421 else
3423 register Lisp_Object val;
3424 val = Fformat (nargs, args);
3425 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3426 return val;
3430 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3431 doc: /* Display a message, in a dialog box if possible.
3432 If a dialog box is not available, use the echo area.
3433 The first argument is a format control string, and the rest are data
3434 to be formatted under control of the string. See `format' for details.
3436 If the first argument is nil or the empty string, clear any existing
3437 message; let the minibuffer contents show.
3439 usage: (message-box FORMAT-STRING &rest ARGS) */)
3440 (nargs, args)
3441 int nargs;
3442 Lisp_Object *args;
3444 if (NILP (args[0]))
3446 message (0);
3447 return Qnil;
3449 else
3451 register Lisp_Object val;
3452 val = Fformat (nargs, args);
3453 #ifdef HAVE_MENUS
3454 /* The MS-DOS frames support popup menus even though they are
3455 not FRAME_WINDOW_P. */
3456 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3457 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3459 Lisp_Object pane, menu, obj;
3460 struct gcpro gcpro1;
3461 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3462 GCPRO1 (pane);
3463 menu = Fcons (val, pane);
3464 obj = Fx_popup_dialog (Qt, menu, Qt);
3465 UNGCPRO;
3466 return val;
3468 #endif /* HAVE_MENUS */
3469 /* Copy the data so that it won't move when we GC. */
3470 if (! message_text)
3472 message_text = (char *)xmalloc (80);
3473 message_length = 80;
3475 if (SBYTES (val) > message_length)
3477 message_length = SBYTES (val);
3478 message_text = (char *)xrealloc (message_text, message_length);
3480 bcopy (SDATA (val), message_text, SBYTES (val));
3481 message2 (message_text, SBYTES (val),
3482 STRING_MULTIBYTE (val));
3483 return val;
3486 #ifdef HAVE_MENUS
3487 extern Lisp_Object last_nonmenu_event;
3488 #endif
3490 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3491 doc: /* Display a message in a dialog box or in the echo area.
3492 If this command was invoked with the mouse, use a dialog box if
3493 `use-dialog-box' is non-nil.
3494 Otherwise, use the echo area.
3495 The first argument is a format control string, and the rest are data
3496 to be formatted under control of the string. See `format' for details.
3498 If the first argument is nil or the empty string, clear any existing
3499 message; let the minibuffer contents show.
3501 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3502 (nargs, args)
3503 int nargs;
3504 Lisp_Object *args;
3506 #ifdef HAVE_MENUS
3507 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3508 && use_dialog_box)
3509 return Fmessage_box (nargs, args);
3510 #endif
3511 return Fmessage (nargs, args);
3514 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3515 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3518 return current_message ();
3522 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3523 doc: /* Return a copy of STRING with text properties added.
3524 First argument is the string to copy.
3525 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3526 properties to add to the result.
3527 usage: (propertize STRING &rest PROPERTIES) */)
3528 (nargs, args)
3529 int nargs;
3530 Lisp_Object *args;
3532 Lisp_Object properties, string;
3533 struct gcpro gcpro1, gcpro2;
3534 int i;
3536 /* Number of args must be odd. */
3537 if ((nargs & 1) == 0 || nargs < 1)
3538 error ("Wrong number of arguments");
3540 properties = string = Qnil;
3541 GCPRO2 (properties, string);
3543 /* First argument must be a string. */
3544 CHECK_STRING (args[0]);
3545 string = Fcopy_sequence (args[0]);
3547 for (i = 1; i < nargs; i += 2)
3548 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3550 Fadd_text_properties (make_number (0),
3551 make_number (SCHARS (string)),
3552 properties, string);
3553 RETURN_UNGCPRO (string);
3557 /* Number of bytes that STRING will occupy when put into the result.
3558 MULTIBYTE is nonzero if the result should be multibyte. */
3560 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3561 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3562 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3563 : SBYTES (STRING))
3565 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3566 doc: /* Format a string out of a format-string and arguments.
3567 The first argument is a format control string.
3568 The other arguments are substituted into it to make the result, a string.
3570 The format control string may contain %-sequences meaning to substitute
3571 the next available argument:
3573 %s means print a string argument. Actually, prints any object, with `princ'.
3574 %d means print as number in decimal (%o octal, %x hex).
3575 %X is like %x, but uses upper case.
3576 %e means print a number in exponential notation.
3577 %f means print a number in decimal-point notation.
3578 %g means print a number in exponential notation
3579 or decimal-point notation, whichever uses fewer characters.
3580 %c means print a number as a single character.
3581 %S means print any object as an s-expression (using `prin1').
3583 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3584 Use %% to put a single % into the output.
3586 A %-sequence may contain optional flag, width, and precision
3587 specifiers, as follows:
3589 %<flags><width><precision>character
3591 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3593 The + flag character inserts a + before any positive number, while a
3594 space inserts a space before any positive number; these flags only
3595 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3596 The # flag means to use an alternate display form for %o, %x, %X, %e,
3597 %f, and %g sequences. The - and 0 flags affect the width specifier,
3598 as described below.
3600 The width specifier supplies a lower limit for the length of the
3601 printed representation. The padding, if any, normally goes on the
3602 left, but it goes on the right if the - flag is present. The padding
3603 character is normally a space, but it is 0 if the 0 flag is present.
3604 The - flag takes precedence over the 0 flag.
3606 For %e, %f, and %g sequences, the number after the "." in the
3607 precision specifier says how many decimal places to show; if zero, the
3608 decimal point itself is omitted. For %s and %S, the precision
3609 specifier truncates the string to the given width.
3611 usage: (format STRING &rest OBJECTS) */)
3612 (nargs, args)
3613 int nargs;
3614 register Lisp_Object *args;
3616 register int n; /* The number of the next arg to substitute */
3617 register int total; /* An estimate of the final length */
3618 char *buf, *p;
3619 register unsigned char *format, *end, *format_start;
3620 int nchars;
3621 /* Nonzero if the output should be a multibyte string,
3622 which is true if any of the inputs is one. */
3623 int multibyte = 0;
3624 /* When we make a multibyte string, we must pay attention to the
3625 byte combining problem, i.e., a byte may be combined with a
3626 multibyte character of the previous string. This flag tells if we
3627 must consider such a situation or not. */
3628 int maybe_combine_byte;
3629 unsigned char *this_format;
3630 /* Precision for each spec, or -1, a flag value meaning no precision
3631 was given in that spec. Element 0, corresponding to the format
3632 string itself, will not be used. Element NARGS, corresponding to
3633 no argument, *will* be assigned to in the case that a `%' and `.'
3634 occur after the final format specifier. */
3635 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
3636 int longest_format;
3637 Lisp_Object val;
3638 int arg_intervals = 0;
3639 USE_SAFE_ALLOCA;
3641 /* discarded[I] is 1 if byte I of the format
3642 string was not copied into the output.
3643 It is 2 if byte I was not the first byte of its character. */
3644 char *discarded = 0;
3646 /* Each element records, for one argument,
3647 the start and end bytepos in the output string,
3648 and whether the argument is a string with intervals.
3649 info[0] is unused. Unused elements have -1 for start. */
3650 struct info
3652 int start, end, intervals;
3653 } *info = 0;
3655 /* It should not be necessary to GCPRO ARGS, because
3656 the caller in the interpreter should take care of that. */
3658 /* Try to determine whether the result should be multibyte.
3659 This is not always right; sometimes the result needs to be multibyte
3660 because of an object that we will pass through prin1,
3661 and in that case, we won't know it here. */
3662 for (n = 0; n < nargs; n++)
3664 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3665 multibyte = 1;
3666 /* Piggyback on this loop to initialize precision[N]. */
3667 precision[n] = -1;
3669 precision[nargs] = -1;
3671 CHECK_STRING (args[0]);
3672 /* We may have to change "%S" to "%s". */
3673 args[0] = Fcopy_sequence (args[0]);
3675 /* GC should never happen here, so abort if it does. */
3676 abort_on_gc++;
3678 /* If we start out planning a unibyte result,
3679 then discover it has to be multibyte, we jump back to retry.
3680 That can only happen from the first large while loop below. */
3681 retry:
3683 format = SDATA (args[0]);
3684 format_start = format;
3685 end = format + SBYTES (args[0]);
3686 longest_format = 0;
3688 /* Make room in result for all the non-%-codes in the control string. */
3689 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3691 /* Allocate the info and discarded tables. */
3693 int nbytes = (nargs+1) * sizeof *info;
3694 int i;
3695 if (!info)
3696 info = (struct info *) alloca (nbytes);
3697 bzero (info, nbytes);
3698 for (i = 0; i <= nargs; i++)
3699 info[i].start = -1;
3700 if (!discarded)
3701 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3702 bzero (discarded, SBYTES (args[0]));
3705 /* Add to TOTAL enough space to hold the converted arguments. */
3707 n = 0;
3708 while (format != end)
3709 if (*format++ == '%')
3711 int thissize = 0;
3712 int actual_width = 0;
3713 unsigned char *this_format_start = format - 1;
3714 int field_width = 0;
3716 /* General format specifications look like
3718 '%' [flags] [field-width] [precision] format
3720 where
3722 flags ::= [-+ #0]+
3723 field-width ::= [0-9]+
3724 precision ::= '.' [0-9]*
3726 If a field-width is specified, it specifies to which width
3727 the output should be padded with blanks, if the output
3728 string is shorter than field-width.
3730 If precision is specified, it specifies the number of
3731 digits to print after the '.' for floats, or the max.
3732 number of chars to print from a string. */
3734 while (format != end
3735 && (*format == '-' || *format == '0' || *format == '#'
3736 || * format == ' ' || *format == '+'))
3737 ++format;
3739 if (*format >= '0' && *format <= '9')
3741 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3742 field_width = 10 * field_width + *format - '0';
3745 /* N is not incremented for another few lines below, so refer to
3746 element N+1 (which might be precision[NARGS]). */
3747 if (*format == '.')
3749 ++format;
3750 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3751 precision[n+1] = 10 * precision[n+1] + *format - '0';
3754 /* Extra +1 for 'l' that we may need to insert into the
3755 format. */
3756 if (format - this_format_start + 2 > longest_format)
3757 longest_format = format - this_format_start + 2;
3759 if (format == end)
3760 error ("Format string ends in middle of format specifier");
3761 if (*format == '%')
3762 format++;
3763 else if (++n >= nargs)
3764 error ("Not enough arguments for format string");
3765 else if (*format == 'S')
3767 /* For `S', prin1 the argument and then treat like a string. */
3768 register Lisp_Object tem;
3769 tem = Fprin1_to_string (args[n], Qnil);
3770 if (STRING_MULTIBYTE (tem) && ! multibyte)
3772 multibyte = 1;
3773 goto retry;
3775 args[n] = tem;
3776 /* If we restart the loop, we should not come here again
3777 because args[n] is now a string and calling
3778 Fprin1_to_string on it produces superflous double
3779 quotes. So, change "%S" to "%s" now. */
3780 *format = 's';
3781 goto string;
3783 else if (SYMBOLP (args[n]))
3785 args[n] = SYMBOL_NAME (args[n]);
3786 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3788 multibyte = 1;
3789 goto retry;
3791 goto string;
3793 else if (STRINGP (args[n]))
3795 string:
3796 if (*format != 's' && *format != 'S')
3797 error ("Format specifier doesn't match argument type");
3798 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3799 to be as large as is calculated here. Easy check for
3800 the case PRECISION = 0. */
3801 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3802 /* The precision also constrains how much of the argument
3803 string will finally appear (Bug#5710). */
3804 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3805 if (precision[n] != -1)
3806 actual_width = min(actual_width,precision[n]);
3808 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3809 else if (INTEGERP (args[n]) && *format != 's')
3811 /* The following loop assumes the Lisp type indicates
3812 the proper way to pass the argument.
3813 So make sure we have a flonum if the argument should
3814 be a double. */
3815 if (*format == 'e' || *format == 'f' || *format == 'g')
3816 args[n] = Ffloat (args[n]);
3817 else
3818 if (*format != 'd' && *format != 'o' && *format != 'x'
3819 && *format != 'i' && *format != 'X' && *format != 'c')
3820 error ("Invalid format operation %%%c", *format);
3822 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3823 if (*format == 'c')
3825 if (! ASCII_CHAR_P (XINT (args[n]))
3826 /* Note: No one can remeber why we have to treat
3827 the character 0 as a multibyte character here.
3828 But, until it causes a real problem, let's
3829 don't change it. */
3830 || XINT (args[n]) == 0)
3832 if (! multibyte)
3834 multibyte = 1;
3835 goto retry;
3837 args[n] = Fchar_to_string (args[n]);
3838 thissize = SBYTES (args[n]);
3840 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3842 args[n]
3843 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3844 thissize = SBYTES (args[n]);
3848 else if (FLOATP (args[n]) && *format != 's')
3850 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3852 if (*format != 'd' && *format != 'o' && *format != 'x'
3853 && *format != 'i' && *format != 'X' && *format != 'c')
3854 error ("Invalid format operation %%%c", *format);
3855 /* This fails unnecessarily if args[n] is bigger than
3856 most-positive-fixnum but smaller than MAXINT.
3857 These cases are important because we sometimes use floats
3858 to represent such integer values (typically such values
3859 come from UIDs or PIDs). */
3860 /* args[n] = Ftruncate (args[n], Qnil); */
3863 /* Note that we're using sprintf to print floats,
3864 so we have to take into account what that function
3865 prints. */
3866 /* Filter out flag value of -1. */
3867 thissize = (MAX_10_EXP + 100
3868 + (precision[n] > 0 ? precision[n] : 0));
3870 else
3872 /* Anything but a string, convert to a string using princ. */
3873 register Lisp_Object tem;
3874 tem = Fprin1_to_string (args[n], Qt);
3875 if (STRING_MULTIBYTE (tem) && ! multibyte)
3877 multibyte = 1;
3878 goto retry;
3880 args[n] = tem;
3881 goto string;
3884 thissize += max (0, field_width - actual_width);
3885 total += thissize + 4;
3888 abort_on_gc--;
3890 /* Now we can no longer jump to retry.
3891 TOTAL and LONGEST_FORMAT are known for certain. */
3893 this_format = (unsigned char *) alloca (longest_format + 1);
3895 /* Allocate the space for the result.
3896 Note that TOTAL is an overestimate. */
3897 SAFE_ALLOCA (buf, char *, total);
3899 p = buf;
3900 nchars = 0;
3901 n = 0;
3903 /* Scan the format and store result in BUF. */
3904 format = SDATA (args[0]);
3905 format_start = format;
3906 end = format + SBYTES (args[0]);
3907 maybe_combine_byte = 0;
3908 while (format != end)
3910 if (*format == '%')
3912 int minlen;
3913 int negative = 0;
3914 unsigned char *this_format_start = format;
3916 discarded[format - format_start] = 1;
3917 format++;
3919 while (index("-+0# ", *format))
3921 if (*format == '-')
3923 negative = 1;
3925 discarded[format - format_start] = 1;
3926 ++format;
3929 minlen = atoi (format);
3931 while ((*format >= '0' && *format <= '9') || *format == '.')
3933 discarded[format - format_start] = 1;
3934 format++;
3937 if (*format++ == '%')
3939 *p++ = '%';
3940 nchars++;
3941 continue;
3944 ++n;
3946 discarded[format - format_start - 1] = 1;
3947 info[n].start = nchars;
3949 if (STRINGP (args[n]))
3951 /* handle case (precision[n] >= 0) */
3953 int width, padding;
3954 int nbytes, start, end;
3955 int nchars_string;
3957 /* lisp_string_width ignores a precision of 0, but GNU
3958 libc functions print 0 characters when the precision
3959 is 0. Imitate libc behavior here. Changing
3960 lisp_string_width is the right thing, and will be
3961 done, but meanwhile we work with it. */
3963 if (precision[n] == 0)
3964 width = nchars_string = nbytes = 0;
3965 else if (precision[n] > 0)
3966 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3967 else
3968 { /* no precision spec given for this argument */
3969 width = lisp_string_width (args[n], -1, NULL, NULL);
3970 nbytes = SBYTES (args[n]);
3971 nchars_string = SCHARS (args[n]);
3974 /* If spec requires it, pad on right with spaces. */
3975 padding = minlen - width;
3976 if (! negative)
3977 while (padding-- > 0)
3979 *p++ = ' ';
3980 ++nchars;
3983 info[n].start = start = nchars;
3984 nchars += nchars_string;
3985 end = nchars;
3987 if (p > buf
3988 && multibyte
3989 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3990 && STRING_MULTIBYTE (args[n])
3991 && !CHAR_HEAD_P (SREF (args[n], 0)))
3992 maybe_combine_byte = 1;
3994 p += copy_text (SDATA (args[n]), p,
3995 nbytes,
3996 STRING_MULTIBYTE (args[n]), multibyte);
3998 info[n].end = nchars;
4000 if (negative)
4001 while (padding-- > 0)
4003 *p++ = ' ';
4004 nchars++;
4007 /* If this argument has text properties, record where
4008 in the result string it appears. */
4009 if (STRING_INTERVALS (args[n]))
4010 info[n].intervals = arg_intervals = 1;
4012 else if (INTEGERP (args[n]) || FLOATP (args[n]))
4014 int this_nchars;
4016 bcopy (this_format_start, this_format,
4017 format - this_format_start);
4018 this_format[format - this_format_start] = 0;
4020 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
4021 sprintf (p, this_format, XFLOAT_DATA (args[n]));
4022 else
4024 if (sizeof (EMACS_INT) > sizeof (int)
4025 && format[-1] != 'c')
4027 /* Insert 'l' before format spec. */
4028 this_format[format - this_format_start]
4029 = this_format[format - this_format_start - 1];
4030 this_format[format - this_format_start - 1] = 'l';
4031 this_format[format - this_format_start + 1] = 0;
4034 if (INTEGERP (args[n]))
4036 if (format[-1] == 'c')
4037 sprintf (p, this_format, (int) XINT (args[n]));
4038 else if (format[-1] == 'd')
4039 sprintf (p, this_format, XINT (args[n]));
4040 /* Don't sign-extend for octal or hex printing. */
4041 else
4042 sprintf (p, this_format, XUINT (args[n]));
4044 else if (format[-1] == 'c')
4045 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4046 else if (format[-1] == 'd')
4047 /* Maybe we should use "%1.0f" instead so it also works
4048 for values larger than MAXINT. */
4049 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4050 else
4051 /* Don't sign-extend for octal or hex printing. */
4052 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4055 if (p > buf
4056 && multibyte
4057 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4058 && !CHAR_HEAD_P (*((unsigned char *) p)))
4059 maybe_combine_byte = 1;
4060 this_nchars = strlen (p);
4061 if (multibyte)
4062 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
4063 else
4064 p += this_nchars;
4065 nchars += this_nchars;
4066 info[n].end = nchars;
4070 else if (STRING_MULTIBYTE (args[0]))
4072 /* Copy a whole multibyte character. */
4073 if (p > buf
4074 && multibyte
4075 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4076 && !CHAR_HEAD_P (*format))
4077 maybe_combine_byte = 1;
4078 *p++ = *format++;
4079 while (! CHAR_HEAD_P (*format))
4081 discarded[format - format_start] = 2;
4082 *p++ = *format++;
4084 nchars++;
4086 else if (multibyte)
4088 /* Convert a single-byte character to multibyte. */
4089 int len = copy_text (format, p, 1, 0, 1);
4091 p += len;
4092 format++;
4093 nchars++;
4095 else
4096 *p++ = *format++, nchars++;
4099 if (p > buf + total)
4100 abort ();
4102 if (maybe_combine_byte)
4103 nchars = multibyte_chars_in_text (buf, p - buf);
4104 val = make_specified_string (buf, nchars, p - buf, multibyte);
4106 /* If we allocated BUF with malloc, free it too. */
4107 SAFE_FREE ();
4109 /* If the format string has text properties, or any of the string
4110 arguments has text properties, set up text properties of the
4111 result string. */
4113 if (STRING_INTERVALS (args[0]) || arg_intervals)
4115 Lisp_Object len, new_len, props;
4116 struct gcpro gcpro1;
4118 /* Add text properties from the format string. */
4119 len = make_number (SCHARS (args[0]));
4120 props = text_property_list (args[0], make_number (0), len, Qnil);
4121 GCPRO1 (props);
4123 if (CONSP (props))
4125 int bytepos = 0, position = 0, translated = 0, argn = 1;
4126 Lisp_Object list;
4128 /* Adjust the bounds of each text property
4129 to the proper start and end in the output string. */
4131 /* Put the positions in PROPS in increasing order, so that
4132 we can do (effectively) one scan through the position
4133 space of the format string. */
4134 props = Fnreverse (props);
4136 /* BYTEPOS is the byte position in the format string,
4137 POSITION is the untranslated char position in it,
4138 TRANSLATED is the translated char position in BUF,
4139 and ARGN is the number of the next arg we will come to. */
4140 for (list = props; CONSP (list); list = XCDR (list))
4142 Lisp_Object item;
4143 int pos;
4145 item = XCAR (list);
4147 /* First adjust the property start position. */
4148 pos = XINT (XCAR (item));
4150 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4151 up to this position. */
4152 for (; position < pos; bytepos++)
4154 if (! discarded[bytepos])
4155 position++, translated++;
4156 else if (discarded[bytepos] == 1)
4158 position++;
4159 if (translated == info[argn].start)
4161 translated += info[argn].end - info[argn].start;
4162 argn++;
4167 XSETCAR (item, make_number (translated));
4169 /* Likewise adjust the property end position. */
4170 pos = XINT (XCAR (XCDR (item)));
4172 for (; position < pos; bytepos++)
4174 if (! discarded[bytepos])
4175 position++, translated++;
4176 else if (discarded[bytepos] == 1)
4178 position++;
4179 if (translated == info[argn].start)
4181 translated += info[argn].end - info[argn].start;
4182 argn++;
4187 XSETCAR (XCDR (item), make_number (translated));
4190 add_text_properties_from_list (val, props, make_number (0));
4193 /* Add text properties from arguments. */
4194 if (arg_intervals)
4195 for (n = 1; n < nargs; ++n)
4196 if (info[n].intervals)
4198 len = make_number (SCHARS (args[n]));
4199 new_len = make_number (info[n].end - info[n].start);
4200 props = text_property_list (args[n], make_number (0), len, Qnil);
4201 props = extend_property_ranges (props, new_len);
4202 /* If successive arguments have properties, be sure that
4203 the value of `composition' property be the copy. */
4204 if (n > 1 && info[n - 1].end)
4205 make_composition_value_copy (props);
4206 add_text_properties_from_list (val, props,
4207 make_number (info[n].start));
4210 UNGCPRO;
4213 return val;
4216 Lisp_Object
4217 format2 (string1, arg0, arg1)
4218 char *string1;
4219 Lisp_Object arg0, arg1;
4221 Lisp_Object args[3];
4222 args[0] = build_string (string1);
4223 args[1] = arg0;
4224 args[2] = arg1;
4225 return Fformat (3, args);
4228 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4229 doc: /* Return t if two characters match, optionally ignoring case.
4230 Both arguments must be characters (i.e. integers).
4231 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4232 (c1, c2)
4233 register Lisp_Object c1, c2;
4235 int i1, i2;
4236 /* Check they're chars, not just integers, otherwise we could get array
4237 bounds violations in DOWNCASE. */
4238 CHECK_CHARACTER (c1);
4239 CHECK_CHARACTER (c2);
4241 if (XINT (c1) == XINT (c2))
4242 return Qt;
4243 if (NILP (current_buffer->case_fold_search))
4244 return Qnil;
4246 /* Do these in separate statements,
4247 then compare the variables.
4248 because of the way DOWNCASE uses temp variables. */
4249 i1 = XFASTINT (c1);
4250 if (NILP (current_buffer->enable_multibyte_characters)
4251 && ! ASCII_CHAR_P (i1))
4253 MAKE_CHAR_MULTIBYTE (i1);
4255 i2 = XFASTINT (c2);
4256 if (NILP (current_buffer->enable_multibyte_characters)
4257 && ! ASCII_CHAR_P (i2))
4259 MAKE_CHAR_MULTIBYTE (i2);
4261 i1 = DOWNCASE (i1);
4262 i2 = DOWNCASE (i2);
4263 return (i1 == i2 ? Qt : Qnil);
4266 /* Transpose the markers in two regions of the current buffer, and
4267 adjust the ones between them if necessary (i.e.: if the regions
4268 differ in size).
4270 START1, END1 are the character positions of the first region.
4271 START1_BYTE, END1_BYTE are the byte positions.
4272 START2, END2 are the character positions of the second region.
4273 START2_BYTE, END2_BYTE are the byte positions.
4275 Traverses the entire marker list of the buffer to do so, adding an
4276 appropriate amount to some, subtracting from some, and leaving the
4277 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4279 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4281 static void
4282 transpose_markers (start1, end1, start2, end2,
4283 start1_byte, end1_byte, start2_byte, end2_byte)
4284 register int start1, end1, start2, end2;
4285 register int start1_byte, end1_byte, start2_byte, end2_byte;
4287 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4288 register struct Lisp_Marker *marker;
4290 /* Update point as if it were a marker. */
4291 if (PT < start1)
4293 else if (PT < end1)
4294 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4295 PT_BYTE + (end2_byte - end1_byte));
4296 else if (PT < start2)
4297 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4298 (PT_BYTE + (end2_byte - start2_byte)
4299 - (end1_byte - start1_byte)));
4300 else if (PT < end2)
4301 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4302 PT_BYTE - (start2_byte - start1_byte));
4304 /* We used to adjust the endpoints here to account for the gap, but that
4305 isn't good enough. Even if we assume the caller has tried to move the
4306 gap out of our way, it might still be at start1 exactly, for example;
4307 and that places it `inside' the interval, for our purposes. The amount
4308 of adjustment is nontrivial if there's a `denormalized' marker whose
4309 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4310 the dirty work to Fmarker_position, below. */
4312 /* The difference between the region's lengths */
4313 diff = (end2 - start2) - (end1 - start1);
4314 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4316 /* For shifting each marker in a region by the length of the other
4317 region plus the distance between the regions. */
4318 amt1 = (end2 - start2) + (start2 - end1);
4319 amt2 = (end1 - start1) + (start2 - end1);
4320 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4321 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4323 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4325 mpos = marker->bytepos;
4326 if (mpos >= start1_byte && mpos < end2_byte)
4328 if (mpos < end1_byte)
4329 mpos += amt1_byte;
4330 else if (mpos < start2_byte)
4331 mpos += diff_byte;
4332 else
4333 mpos -= amt2_byte;
4334 marker->bytepos = mpos;
4336 mpos = marker->charpos;
4337 if (mpos >= start1 && mpos < end2)
4339 if (mpos < end1)
4340 mpos += amt1;
4341 else if (mpos < start2)
4342 mpos += diff;
4343 else
4344 mpos -= amt2;
4346 marker->charpos = mpos;
4350 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4351 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4352 The regions should not be overlapping, because the size of the buffer is
4353 never changed in a transposition.
4355 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4356 any markers that happen to be located in the regions.
4358 Transposing beyond buffer boundaries is an error. */)
4359 (startr1, endr1, startr2, endr2, leave_markers)
4360 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4362 register EMACS_INT start1, end1, start2, end2;
4363 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4364 EMACS_INT gap, len1, len_mid, len2;
4365 unsigned char *start1_addr, *start2_addr, *temp;
4367 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4368 Lisp_Object buf;
4370 XSETBUFFER (buf, current_buffer);
4371 cur_intv = BUF_INTERVALS (current_buffer);
4373 validate_region (&startr1, &endr1);
4374 validate_region (&startr2, &endr2);
4376 start1 = XFASTINT (startr1);
4377 end1 = XFASTINT (endr1);
4378 start2 = XFASTINT (startr2);
4379 end2 = XFASTINT (endr2);
4380 gap = GPT;
4382 /* Swap the regions if they're reversed. */
4383 if (start2 < end1)
4385 register int glumph = start1;
4386 start1 = start2;
4387 start2 = glumph;
4388 glumph = end1;
4389 end1 = end2;
4390 end2 = glumph;
4393 len1 = end1 - start1;
4394 len2 = end2 - start2;
4396 if (start2 < end1)
4397 error ("Transposed regions overlap");
4398 else if (start1 == end1 || start2 == end2)
4399 error ("Transposed region has length 0");
4401 /* The possibilities are:
4402 1. Adjacent (contiguous) regions, or separate but equal regions
4403 (no, really equal, in this case!), or
4404 2. Separate regions of unequal size.
4406 The worst case is usually No. 2. It means that (aside from
4407 potential need for getting the gap out of the way), there also
4408 needs to be a shifting of the text between the two regions. So
4409 if they are spread far apart, we are that much slower... sigh. */
4411 /* It must be pointed out that the really studly thing to do would
4412 be not to move the gap at all, but to leave it in place and work
4413 around it if necessary. This would be extremely efficient,
4414 especially considering that people are likely to do
4415 transpositions near where they are working interactively, which
4416 is exactly where the gap would be found. However, such code
4417 would be much harder to write and to read. So, if you are
4418 reading this comment and are feeling squirrely, by all means have
4419 a go! I just didn't feel like doing it, so I will simply move
4420 the gap the minimum distance to get it out of the way, and then
4421 deal with an unbroken array. */
4423 /* Make sure the gap won't interfere, by moving it out of the text
4424 we will operate on. */
4425 if (start1 < gap && gap < end2)
4427 if (gap - start1 < end2 - gap)
4428 move_gap (start1);
4429 else
4430 move_gap (end2);
4433 start1_byte = CHAR_TO_BYTE (start1);
4434 start2_byte = CHAR_TO_BYTE (start2);
4435 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4436 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4438 #ifdef BYTE_COMBINING_DEBUG
4439 if (end1 == start2)
4441 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4442 len2_byte, start1, start1_byte)
4443 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4444 len1_byte, end2, start2_byte + len2_byte)
4445 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4446 len1_byte, end2, start2_byte + len2_byte))
4447 abort ();
4449 else
4451 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4452 len2_byte, start1, start1_byte)
4453 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4454 len1_byte, start2, start2_byte)
4455 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4456 len2_byte, end1, start1_byte + len1_byte)
4457 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4458 len1_byte, end2, start2_byte + len2_byte))
4459 abort ();
4461 #endif
4463 /* Hmmm... how about checking to see if the gap is large
4464 enough to use as the temporary storage? That would avoid an
4465 allocation... interesting. Later, don't fool with it now. */
4467 /* Working without memmove, for portability (sigh), so must be
4468 careful of overlapping subsections of the array... */
4470 if (end1 == start2) /* adjacent regions */
4472 modify_region (current_buffer, start1, end2, 0);
4473 record_change (start1, len1 + len2);
4475 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4476 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4477 /* Don't use Fset_text_properties: that can cause GC, which can
4478 clobber objects stored in the tmp_intervals. */
4479 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4480 if (!NULL_INTERVAL_P (tmp_interval3))
4481 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4483 /* First region smaller than second. */
4484 if (len1_byte < len2_byte)
4486 USE_SAFE_ALLOCA;
4488 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4490 /* Don't precompute these addresses. We have to compute them
4491 at the last minute, because the relocating allocator might
4492 have moved the buffer around during the xmalloc. */
4493 start1_addr = BYTE_POS_ADDR (start1_byte);
4494 start2_addr = BYTE_POS_ADDR (start2_byte);
4496 bcopy (start2_addr, temp, len2_byte);
4497 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4498 bcopy (temp, start1_addr, len2_byte);
4499 SAFE_FREE ();
4501 else
4502 /* First region not smaller than second. */
4504 USE_SAFE_ALLOCA;
4506 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4507 start1_addr = BYTE_POS_ADDR (start1_byte);
4508 start2_addr = BYTE_POS_ADDR (start2_byte);
4509 bcopy (start1_addr, temp, len1_byte);
4510 bcopy (start2_addr, start1_addr, len2_byte);
4511 bcopy (temp, start1_addr + len2_byte, len1_byte);
4512 SAFE_FREE ();
4514 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4515 len1, current_buffer, 0);
4516 graft_intervals_into_buffer (tmp_interval2, start1,
4517 len2, current_buffer, 0);
4518 update_compositions (start1, start1 + len2, CHECK_BORDER);
4519 update_compositions (start1 + len2, end2, CHECK_TAIL);
4521 /* Non-adjacent regions, because end1 != start2, bleagh... */
4522 else
4524 len_mid = start2_byte - (start1_byte + len1_byte);
4526 if (len1_byte == len2_byte)
4527 /* Regions are same size, though, how nice. */
4529 USE_SAFE_ALLOCA;
4531 modify_region (current_buffer, start1, end1, 0);
4532 modify_region (current_buffer, start2, end2, 0);
4533 record_change (start1, len1);
4534 record_change (start2, len2);
4535 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4536 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4538 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4539 if (!NULL_INTERVAL_P (tmp_interval3))
4540 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4542 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4543 if (!NULL_INTERVAL_P (tmp_interval3))
4544 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4546 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4547 start1_addr = BYTE_POS_ADDR (start1_byte);
4548 start2_addr = BYTE_POS_ADDR (start2_byte);
4549 bcopy (start1_addr, temp, len1_byte);
4550 bcopy (start2_addr, start1_addr, len2_byte);
4551 bcopy (temp, start2_addr, len1_byte);
4552 SAFE_FREE ();
4554 graft_intervals_into_buffer (tmp_interval1, start2,
4555 len1, current_buffer, 0);
4556 graft_intervals_into_buffer (tmp_interval2, start1,
4557 len2, current_buffer, 0);
4560 else if (len1_byte < len2_byte) /* Second region larger than first */
4561 /* Non-adjacent & unequal size, area between must also be shifted. */
4563 USE_SAFE_ALLOCA;
4565 modify_region (current_buffer, start1, end2, 0);
4566 record_change (start1, (end2 - start1));
4567 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4568 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4569 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4571 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4572 if (!NULL_INTERVAL_P (tmp_interval3))
4573 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4575 /* holds region 2 */
4576 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4577 start1_addr = BYTE_POS_ADDR (start1_byte);
4578 start2_addr = BYTE_POS_ADDR (start2_byte);
4579 bcopy (start2_addr, temp, len2_byte);
4580 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4581 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4582 bcopy (temp, start1_addr, len2_byte);
4583 SAFE_FREE ();
4585 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4586 len1, current_buffer, 0);
4587 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4588 len_mid, current_buffer, 0);
4589 graft_intervals_into_buffer (tmp_interval2, start1,
4590 len2, current_buffer, 0);
4592 else
4593 /* Second region smaller than first. */
4595 USE_SAFE_ALLOCA;
4597 record_change (start1, (end2 - start1));
4598 modify_region (current_buffer, start1, end2, 0);
4600 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4601 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4602 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4604 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4605 if (!NULL_INTERVAL_P (tmp_interval3))
4606 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4608 /* holds region 1 */
4609 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4610 start1_addr = BYTE_POS_ADDR (start1_byte);
4611 start2_addr = BYTE_POS_ADDR (start2_byte);
4612 bcopy (start1_addr, temp, len1_byte);
4613 bcopy (start2_addr, start1_addr, len2_byte);
4614 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4615 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
4616 SAFE_FREE ();
4618 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4619 len1, current_buffer, 0);
4620 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4621 len_mid, current_buffer, 0);
4622 graft_intervals_into_buffer (tmp_interval2, start1,
4623 len2, current_buffer, 0);
4626 update_compositions (start1, start1 + len2, CHECK_BORDER);
4627 update_compositions (end2 - len1, end2, CHECK_BORDER);
4630 /* When doing multiple transpositions, it might be nice
4631 to optimize this. Perhaps the markers in any one buffer
4632 should be organized in some sorted data tree. */
4633 if (NILP (leave_markers))
4635 transpose_markers (start1, end1, start2, end2,
4636 start1_byte, start1_byte + len1_byte,
4637 start2_byte, start2_byte + len2_byte);
4638 fix_start_end_in_overlays (start1, end2);
4641 signal_after_change (start1, end2 - start1, end2 - start1);
4642 return Qnil;
4646 void
4647 syms_of_editfns ()
4649 environbuf = 0;
4650 initial_tz = 0;
4652 Qbuffer_access_fontify_functions
4653 = intern_c_string ("buffer-access-fontify-functions");
4654 staticpro (&Qbuffer_access_fontify_functions);
4656 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4657 doc: /* Non-nil means text motion commands don't notice fields. */);
4658 Vinhibit_field_text_motion = Qnil;
4660 DEFVAR_LISP ("buffer-access-fontify-functions",
4661 &Vbuffer_access_fontify_functions,
4662 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4663 Each function is called with two arguments which specify the range
4664 of the buffer being accessed. */);
4665 Vbuffer_access_fontify_functions = Qnil;
4668 Lisp_Object obuf;
4669 extern Lisp_Object Vprin1_to_string_buffer;
4670 obuf = Fcurrent_buffer ();
4671 /* Do this here, because init_buffer_once is too early--it won't work. */
4672 Fset_buffer (Vprin1_to_string_buffer);
4673 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4674 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4675 Qnil);
4676 Fset_buffer (obuf);
4679 DEFVAR_LISP ("buffer-access-fontified-property",
4680 &Vbuffer_access_fontified_property,
4681 doc: /* Property which (if non-nil) indicates text has been fontified.
4682 `buffer-substring' need not call the `buffer-access-fontify-functions'
4683 functions if all the text being accessed has this property. */);
4684 Vbuffer_access_fontified_property = Qnil;
4686 DEFVAR_LISP ("system-name", &Vsystem_name,
4687 doc: /* The host name of the machine Emacs is running on. */);
4689 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4690 doc: /* The full name of the user logged in. */);
4692 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4693 doc: /* The user's name, taken from environment variables if possible. */);
4695 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4696 doc: /* The user's name, based upon the real uid only. */);
4698 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4699 doc: /* The release of the operating system Emacs is running on. */);
4701 defsubr (&Spropertize);
4702 defsubr (&Schar_equal);
4703 defsubr (&Sgoto_char);
4704 defsubr (&Sstring_to_char);
4705 defsubr (&Schar_to_string);
4706 defsubr (&Sbyte_to_string);
4707 defsubr (&Sbuffer_substring);
4708 defsubr (&Sbuffer_substring_no_properties);
4709 defsubr (&Sbuffer_string);
4711 defsubr (&Spoint_marker);
4712 defsubr (&Smark_marker);
4713 defsubr (&Spoint);
4714 defsubr (&Sregion_beginning);
4715 defsubr (&Sregion_end);
4717 staticpro (&Qfield);
4718 Qfield = intern_c_string ("field");
4719 staticpro (&Qboundary);
4720 Qboundary = intern_c_string ("boundary");
4721 defsubr (&Sfield_beginning);
4722 defsubr (&Sfield_end);
4723 defsubr (&Sfield_string);
4724 defsubr (&Sfield_string_no_properties);
4725 defsubr (&Sdelete_field);
4726 defsubr (&Sconstrain_to_field);
4728 defsubr (&Sline_beginning_position);
4729 defsubr (&Sline_end_position);
4731 /* defsubr (&Smark); */
4732 /* defsubr (&Sset_mark); */
4733 defsubr (&Ssave_excursion);
4734 defsubr (&Ssave_current_buffer);
4736 defsubr (&Sbufsize);
4737 defsubr (&Spoint_max);
4738 defsubr (&Spoint_min);
4739 defsubr (&Spoint_min_marker);
4740 defsubr (&Spoint_max_marker);
4741 defsubr (&Sgap_position);
4742 defsubr (&Sgap_size);
4743 defsubr (&Sposition_bytes);
4744 defsubr (&Sbyte_to_position);
4746 defsubr (&Sbobp);
4747 defsubr (&Seobp);
4748 defsubr (&Sbolp);
4749 defsubr (&Seolp);
4750 defsubr (&Sfollowing_char);
4751 defsubr (&Sprevious_char);
4752 defsubr (&Schar_after);
4753 defsubr (&Schar_before);
4754 defsubr (&Sinsert);
4755 defsubr (&Sinsert_before_markers);
4756 defsubr (&Sinsert_and_inherit);
4757 defsubr (&Sinsert_and_inherit_before_markers);
4758 defsubr (&Sinsert_char);
4759 defsubr (&Sinsert_byte);
4761 defsubr (&Suser_login_name);
4762 defsubr (&Suser_real_login_name);
4763 defsubr (&Suser_uid);
4764 defsubr (&Suser_real_uid);
4765 defsubr (&Suser_full_name);
4766 defsubr (&Semacs_pid);
4767 defsubr (&Scurrent_time);
4768 defsubr (&Sget_internal_run_time);
4769 defsubr (&Sformat_time_string);
4770 defsubr (&Sfloat_time);
4771 defsubr (&Sdecode_time);
4772 defsubr (&Sencode_time);
4773 defsubr (&Scurrent_time_string);
4774 defsubr (&Scurrent_time_zone);
4775 defsubr (&Sset_time_zone_rule);
4776 defsubr (&Ssystem_name);
4777 defsubr (&Smessage);
4778 defsubr (&Smessage_box);
4779 defsubr (&Smessage_or_box);
4780 defsubr (&Scurrent_message);
4781 defsubr (&Sformat);
4783 defsubr (&Sinsert_buffer_substring);
4784 defsubr (&Scompare_buffer_substrings);
4785 defsubr (&Ssubst_char_in_region);
4786 defsubr (&Stranslate_region_internal);
4787 defsubr (&Sdelete_region);
4788 defsubr (&Sdelete_and_extract_region);
4789 defsubr (&Swiden);
4790 defsubr (&Snarrow_to_region);
4791 defsubr (&Ssave_restriction);
4792 defsubr (&Stranspose_regions);
4795 /* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4796 (do not change this comment) */